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方法代码。

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方法代码:

    public function weixin(){
        $code=input('get.code');
    }

code获取很简单,我们看下打印效果:

ThinkPHP6实现对接微信扫码登录的方法

3、获得Access Token 和openid,我们在weixin()方法中继续添加代码:

public function weixin(){
        $code=input('get.code');
        $appid='wx868f988d79a4f25b';
        $appsecret='82b426f2882b6a1398b8312cc1de037b';
        $url='https://api.weixin.qq.com/sns/oauth3/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
        
        //json对象变成数组
        $res=json_decode(file_get_contents($url),true);
        $access_token=$res['access_token'];
        $openid=$res['openid'];

    }

这样我们就获取到了access_token和openid,我们看下打印效果:

ThinkPHP6实现对接微信扫码登录的方法

5、获取用户全部信息,我们在weixin()方法中继续添加代码:

public function weixin(){
        $code=input('get.code');
        $appid='wx868f988d79a4f25b';
        $appsecret='82b426f2882b6a1398b8312cc1de037b';
        $url='https://api.weixin.qq.com/sns/oauth3/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
        
        //json对象变成数组
        $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实现对接微信扫码登录的方法

在我们获取用户微信信息后,我们就可以整理数据入库了。

如果是用户第一次登录,我们可以设置绑定手机号的界面,绑定手机号后即算是注册成功。如果我们检测到已经绑定手机号,即代表登录成功跳转到成功界面。

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章