根据需求,取其中的一部分参考实现,需要有一定基础的PHP的程序员:
第一步:获取Code
protected function getWxCode($appid, $type = false)
{
if ($type) {
$scope = 'snsapi_userinfo';
} else {
$scope = 'snsapi_base';
}
$url = urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
$href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%d#wechat_redirect";
$href = sprintf($href, $appid, $url, $scope, 123);
$this->redirect($href);
}
第二步:根据Code获取到授权会员的信息
// 用户信息
protected function getWxInfo($appid, $appsecret, $code, $type = false)
{
$result = http_get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code');
$result = json_decode($result, 1);
if ($type) {
if ($result['access_token']) {
$Userinfo = http_get('https://api.weixin.qq.com/sns/userinfo?access_token=' . $result['access_token'] . '&openid=' . $result['openid']);
$Userinfo = json_decode($Userinfo, 1);
return $Userinfo;
}
} else {
return $result;
}
return false;
}
第三步:通过调用getWxInfo()方法,至少可以获取到用户的openid。
扩展阅读:
------------------------------------------------------
具体而言,网页授权流程分为四步:
1、引导用户进入授权页面同意授权,获取code
如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。
code说明 : code作为换取access_token的票据,每次用户授权带上的code将不一样,code只 能使用一次,5分钟未被使用自动过期。
2、通过code换取网页授权access_token(与基础支持中的access_token不同)
如果网页授权的作用域为snsapi_base,则本步骤中获取到网页授权access_token的同时,也获取到了openid,snsapi_base式的网页授权流程即到此为止。
3、如果需要,开发者可以刷新网页授权access_token,避免过期
4、通过网页授权access_token和openid获取用户基本信息(支持UnionID机制)
如果网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_token和openid拉取用户信息了。
5、两种scope的区别:
应用授权作用域不同:
静默授权:snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid)
手动授权:snsapi_userinfo (弹出授权页面,可通过openid拿到昵称性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
必须验证是用户手动同意授权,才允许开发者通过openid拿到具体的用户信息,静默授权没有用户手动同意授权这一动作,所以只能拿到openid,不能通过openid进一步取用户详细信息。