PHP 实现微信公众平台OAuth2.0网页授权

在Web应用中,用户登录是非常常见的功能之一。为了提供更好的用户体验,并且方便用户进行登录,很多应用选择通过第三方平台进行登录授权,比如微信、QQ等。
本文将以微信登录授权为例,介绍如何使用PHP实现网页授权登录,并将用户昵称和头像更新到用户表中。
图片
一个可以运行PHP的环境,比如搭建好的服务器或者本地开发环境。注册并获取微信公众号的AppID和AppSecret,这个要去微信公众号后台获取。
图片
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
4.获取微信用户信息(需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;}
看完本文有收获?点赞、分享是最大的支持!