1.微信端访问,用户同意授权:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
2.同意授权后跳转到第三方URL,通过code参数得到网页授权access_token
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
3.刷新access_token(如果需要)
https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
3.获取微信用户信息(需scope为 snsapi_userinfo)
使用上一步获取的ACCESS_TOKEN和OPENID
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
下面我将这个过程写为了一个PHP函数,供大家使用:
/**
* $appid str 公众号ID
* $secret str 公众号秘钥
* $code str 用户授权登录后传过来的参数
*/
function getWechatOpenId($appid,$secret,$code){
//1.微信端访问,用户同意授权
//2.同意授权后跳转到第三方URL,通过code换取网页授权access_token
$get_token_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,$get_token_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$res = curl_exec($ch);
curl_close($ch);
$json_obj = json_decode($res,true);
//3.刷新access_token(如果需要)
$refresh_token = $json_obj['refresh_token'];
$refresh_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$refresh_token;
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$refresh_token_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$res = curl_exec($ch);
curl_close($ch);
$json_obj = json_decode($res,true);
//4.根据openid和access_token拉取用户信息(需scope为 snsapi_userinfo)
$access_token = $json_obj['access_token'];
$openid = $json_obj['openid'];
$get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$get_user_info_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$res = curl_exec($ch);
curl_close($ch);
$user_obj = json_decode($res,true);
return $user_obj;
}标签:微信公众平台 微信授权 微信开发 微信OAUTH2 微信网页授权 网页授权
版权声明:本站部分内容来自互联网,若涉及版权问题请及时通知我们,我们将及时予以删除!谢谢大家的理解与支持!

发表评论