手把手教你实现微信网页授权登录,成功获取用户信息

基础准备

1.需要一台线上服务器+域名
2.申请微信公众号(请自行查阅普通订阅号/认证订阅号/普通服务号/认证服务号区别) 或 直接申请公众测试账号http://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
3.设置接口配置

token.php 此文件只在设置接口配置时使用一次

<?php
$timestamp = $_GET['timestamp'];
$nonce = $_GET['nonce'];
$token = 'token';  //在网页中配置的token
$signature = $_GET['signature'];
$array = array($timestamp,$nonce,$token);
$tmpstr= implode('',$array);
$tmpstr = sha1($tmpstr);
if ($tmpstr == $signature){
   echo $_GET['echostr'];
   exit;
}
?>

4.扫描关注测试账号

5.配置回调函数


关于授权回调页面域名填写:不要加http或https,只需要填写好域名地址即可,如dingdingmaoer.com


业务开发

1.用户授权并获取code

替换参数1:appid (微信公众号appID)
替换参数2:redirect_uri (回调地址,请求成功微信会返回code码,请使用GET方式获取)
注意:这里的回调地址需具体指向,url使用UrlEncode编码格式

使用GET请求:https://open.weixin.qq.com/connect/oauth2/authorize?appid=appid&redirect_uri=redirect_uri&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect

成功返回:
Array (
 [code] => 011uxTrF1Qlax80C9yoF1DdPrF1uxTrY 
 [state] => STATE
)

2.使用code换取access_token

替换参数1:appid (微信公众号appID)
替换参数2:secret (微信公众号密钥appsecret)
替换参数3:code (code码)

使用GET请求:https://api.weixin.qq.com/sns/oauth2/access_token?appid=appid&secret=appsecret&code=011uxTrF1Qlax80C9yoF1DdPrF1uxTrY&grant_type=authorization_code

成功返回:
{
    "access_token":"19_LyIGHhebxD9O3GFzLZ7YclFIwNN-uIq2kvTgO5Qt2xqRJKzk0kWeBIWz3Ybwbpl-vH0NcrSsEjo3cFACZJHyKw",
    "expires_in":7200,
    "refresh_token":"19_2tzt5RwIzu5MchwR-RXqylPp-7uc0I-ZTl3HNA9aAZiOaF3urxoo7TCCv27t7u6SWyhvPiwyHH3Vv3qt2Tx18Q",
    "openid":"oGScV5pKQnakoKYmGRhE4KqSMMig",
    "scope":"snsapi_userinfo"
}

3.通过access_token、openid获取用户信息

替换参数1:access_token
替换参数2:openid

使用GET请求:https://api.weixin.qq.com/sns/userinfo?access_token=access_token&openid=openid&lang=zh_CN

成功返回:
 {
"openid":"oGScV5pKQnakoKYmGRhE4KqSMMig",
"nickname":"超°",
"sex":1,
"language":"zh_CN",
"city":"彭水",
"province":"重庆",
"country":"中国",
"headimgurl":"http:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/EsR5sbT6fWfzkGJtWZKDIpVHoQE7zs3ia5M5AvVIpSurjnFWHWl0AGwX97M6qyNHT7oYvZgmcRbgHKFg2I537hw\/132",
"privilege":[]
}

Last modification:March 26th, 2019 at 04:25 pm
如果觉得我的文章对你有用,请随意赞赏

Leave a Comment