在近几年的互联网网站中,使用微信登录的场景可是越来越多。据统计2020年,全球微信高达11亿,也确实如此,微信这个好用的社交工具,可以说小到一个小学生大到你的七大姑八大姨,很多人可能没有QQ,但他一定有微信。所以微信登录是程序员必备的一项工作技能。
微信扫码登录对接ThinkPHP6,话不多说,直接上车。
一、准备资料:
1、访问 https://open.weixin.qq.com/,注册账户。
2、开发者认证:企业。
3、创建一个网站应用:网站域名必须备案(可使用二级域名),获得相应的AppID和AppSecret,申请微信登录且通过审核。
二、接入微信登录步骤:
首先看下微信官网给出的步骤说明:https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html
1. 第三方发起微信授权登录请求,微信用户允许授权第三方应用后,微信会拉起应用或重定向到第三方网站,并且带上授权临时票据code参数;
2. 通过code参数加上AppID和AppSecret等,通过API换取access_token;
3. 通过access_token进行接口调用,获取用户基本数据资源或帮助用户实现基本操作。
三、接入微信登录实操环节:
1、放好微信登录图标,并添加链接。
比如链接到www.a,com/index/user/weixindenglu。下面我们看下weixindenglu方法代码。
1 2 3 4 5 6 | public function weixindenglu(){
$appid = 'wx868f988d79a4f2bb' ;
$redirect_uri =urldecode( 'http://www.dongpaiweb.cn/index/index/weixin.html' );
$url = 'https://open.weixin.qq.com/connect/qrconnect?appid=' . $appid . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect' ;
header( "location:" . $url );
}
|
这个时候我们点击微信小图标就会出现扫码的界面。拿出手机赶紧微信扫码。
(注意:$redirect_uri是我们的回调地址,意思是用户微信扫码后的处理地址)。
2、获得用户的code。
微信扫码后就跳转到了上面定义的回调地址weixin方法。我们看下weixin方法代码:
1 2 3 | public function weixin(){
$code =input( 'get.code' );
}
|
code获取很简单,我们看下打印效果:
3、获得Access Token 和openid,我们在weixin()方法中继续添加代码:
1 2 3 4 5 6 7 8 9 10 11 12 | public function weixin(){
$code =input( 'get.code' );
$appid = 'wx868f988d79a4f25b' ;
$appsecret = '82b426f2882b6a1398b8312cc1de037b' ;
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code' ;
$res =json_decode( file_get_contents ( $url ),true);
$access_token = $res [ 'access_token' ];
$openid = $res [ 'openid' ];
}
|
这样我们就获取到了access_token和openid,我们看下打印效果:
5、获取用户全部信息,我们在weixin()方法中继续添加代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public function weixin(){
$code =input( 'get.code' );
$appid = 'wx868f988d79a4f25b' ;
$appsecret = '82b426f2882b6a1398b8312cc1de037b' ;
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code' ;
$res =json_decode( file_get_contents ( $url ),true);
$access_token = $res [ 'access_token' ];
$openid = $res [ 'openid' ];
$urlyonghu = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid ;
$user =json_decode( file_get_contents ( $urlyonghu ),true);
print_r( $user );
}
|
这样我们就获取了用户的昵称、地址、头像等信息,看下打印效果:
在我们获取用户微信信息后,我们就可以整理数据入库了。
如果是用户第一次登录,我们可以设置绑定手机号的界面,绑定手机号后即算是注册成功。如果我们检测到已经绑定手机号,即代表登录成功跳转到成功界面。
以上就是ThinkPHP6对接微信扫码登录的操作步骤。加薪升职,赶紧get此技能!
以上就是【干货】ThinkPHP6对接微信扫码登录的详细内容