引言
目前微信是最为大众化的社交平台,想在微信上做推广且又想简化用户的注册登录流程,那么我们就可以使用微信官方提供的授权登录功能,作为开发者的我们要该如何实现这一功能呢,本次笔者记录一下使用微信服务号进行授权登录的过程。
查看权限
想要使用授权登录的便利,那是需要一定的资质才可以使用的,简单的说就是要进行微信认证,认证完后我们可以在自己的微信公众号里看到网页授权登录的权限。


根据提示,设置一下自己的网页授权域名,必须要通过备案的域名才可以。
授权登录
官方文档传送门
2 第二步:通过code换取网页授权access_token
下面笔者记录一下自己的使用经验
获取用户授权的code有两种,分别是snsapi_base和snsapi_userinfo,简单的说就是,如果只是想要拿到用户的openid的话那就使用snsapi_base,想要拿到用户的详细信息的话那就使用snsapi_userinfo
snsapi_base形式
function getBaseCode(){
// 微信服务号的APPID
$appid='*****************';
// 授权登录回调地址
$redirect_uri=urlencode("http://www.huangqianxinxi.com/wechat/code.php");
$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
header('location:'.$url);
}
在回调地址里获取用户的基本信息
function getBaseInfo(){
$appid="****************";
$secret="*****************************";
$code=$_GET['code'];
$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$baseInfo=json_decode($output);
curl_close($ch);
var_dump($baseInfo);
}
返回的数据格式
{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE"
}
snsapi_userinfo形式
function getInfoCode(){
// 微信服务号APPID
$appid='****************';
// 授权登录回调地址
$redirect_uri=urlencode("http://www.huangqianxinxi.com/wechat/info.php");
$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
header('location:'.$url);
}
在回调地址里获取用户的详细信息
function getUserInfo(){
$appid="*************";
$secret="*******************************";
$code=$_GET['code'];
$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$userInfo=json_decode($output,true);
curl_close($ch);
var_dump($userInfo);
}
返回的数据格式
{
"openid":" OPENID",
"nickname": NICKNAME,
"sex":"1",
"province":"PROVINCE",
"city":"CITY",
"country":"COUNTRY",
"headimgurl": "http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
"privilege":[ "PRIVILEGE1" "PRIVILEGE2" ],
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
总结
微信服务号授权就是这么个流程,具体需要哪些信息根据业务来选择就好了,另外希望此笔记可以帮助到小伙伴。
本文介绍了如何利用微信服务号实现授权登录功能。首先,需要进行微信认证以获得网页授权登录权限,并设置授权域名。接着,按照官方文档的四步流程:获取code、换取access_token、刷新access_token(如果需要)、拉取用户信息。用户授权分为snsapi_base和snsapi_userinfo两种,前者获取openid,后者获取用户详细信息。最后,文章提供了不同授权方式的回调数据格式,并提醒开发者根据业务需求选择所需信息。
4719

被折叠的 条评论
为什么被折叠?



