微信小程序实现微信登录功能

想要实现微信小程序登录并与APP的微信登录实现数据想通,首先,需要在微信开放平台将微信小程序进行绑定,从而实现在微信后台能将数据打通。

其次是通过微信小程序提供的方法获取微信提供的开放信息,然后通过wx.login获取用户唯一的code值,然后通过该code值获取到用户的unionid.

那么,该unionid就是用户在站点内的唯一三方ID。

通过该unionid,我们的后端程序可以判断该微信用户是否在站点内已经注册成功,从而可以实现用户的注册/登录功能。

 

一:首先在模板文件上创建微信登录的图标

<button class="login_wx" bindtap="wx_login" open-type="getUserInfo">

    <view>

        <image src="../image/wechat.png"></image>

    </view>

    <text>微信登录</text>

</button>

 

二:微信小程序微信登录事件

//微信三方登陆

    

 //微信三方登陆

    wx_login:function(){

        var app=getApp();

        var _this=this;

        var wx_userinfo='';

        //console.log("canIUse:"+this.data.canIUse);

        //获取用户的微信信息

        wx.getUserProfile({

            desc: '获取你的昵称、头像、地区及性别', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写

            success: (res) => {

              //console.log(res);

              wx_userinfo=res.userInfo;

              wx.login({

                success:function(res1){

                    var code=res1.code;

                    var methodName='Login.getUnionid';

                    var unionid='';

                    var data={"code":code};

                    var sign='';

                    var sign_data='';

                    var system='';

                    var source='android';

                    util.requestData(methodName,data,function(code,msg,info){

                        //console.log(info);

                        unionid=info[0].unionid;

                        //console.log("unionid:"+unionid);

                        app.globalData.openid=info[0].openid;

                        //将openid存入缓存

                        wx.setStorageSync('openid',info[0].openid);

                        //获取系统消息

                        wx.getSystemInfo({

                            success (res2) {

                                system=res2.system;

                                if(system.indexOf("iOS")!=-1){

                                    source='ios';

                                }else if(system.indexOf("Android")!=-1){

                                    source='android';

                                }

 

                                wx.showLoading({

                                    title: '登录中……',

                                })

 

                                //生成sign

                                sign_data={"openid":unionid};

                                sign=util.createSign(sign_data);

                                //console.log(sign);

                                _this.setData({

                                    "login_hidden":false

                                });

 

                                //调用三方登录接口

                                methodName="Login.userLoginByThird";

                                data={

                                    "openid":unionid,

                                    "type":"wx",

                                    "nicename":wx_userinfo.nickName,

                                    "avatar":encodeURI(wx_userinfo.avatarUrl),

                                    "sign":sign,

                                    "source":source

                                };

 

                                //console.log(data);

 

                                util.requestData(methodName,data,function(code,msg,info1){

                                    //console.log(info1);

                                    //获取用户的信息

                                    var data1={

                                        'uid':info1[0].id,

                                        'token':info1[0].token

                                    };

                                    util.requestData("User.getBaseInfo",data1,function(code1,msg1,info2){

                                        info1[0].vip=info2[0].vip;

                                        info1[0].liang=info2[0].liang;

                                        //console.log(typeof(info2));

                                        wx.setStorageSync('userinfo',info1[0]);

                                        app.globalData.userinfo=info1[0];

                                        //console.log(wx.getStorageSync("userinfo"));

                                        //console.log(app.globalData.userinfo);

                                        wx.hideLoading();

                                        setTimeout(function(){

                                            _this.setData({

                                                "login_hidden":true

                                            });

                                            wx.switchTab({ 

                                                url: '/pages/my/index',

                                            })

                                        },100);

                                        

                                        //console.log("微信登陆跳转结束");

 

                                    });

                                    

                                });

 

                            }

                        });

 

                    });

 

                },

                error:function(res){

                    util.showSimpleMsg("获取用户信息失败");

                }

              })

            },

            error:(res)=>{

                util.showSimpleMsg("获取用户信息失败");

            }

        })

        

        

    },

 

三:接口:

'getUnionid' => array(
                'code' => array('name' => 'code', 'type' => 'string','desc' => '微信code'),
            ),

 

/**
     * 获取微信登录unionid
     * @desc 用于获取微信登录unionid
     * @return int code 操作码,0表示成功,2发送失败
     * @return array info 
     * @return string info[0].unionid 微信unionid
     * @return string msg 提示信息
     */    
    public function getUnionid(){
        
        $rs = array('code' => 0, 'msg' => '', 'info' => array());
        $code=checkNull($this->code);
        
        if($code==''){
            $rs['code']=1001;
            $rs['msg']='参数错误';
            return $rs;
            
        }

        $configpri=getConfigPri();
    
        $AppID = $configpri['wx_mini_appid'];
        $AppSecret = $configpri['wx_mini_appsecret'];
        /* 获取token */
        //$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$AppID}&secret={$AppSecret}&code={$code}&grant_type=authorization_code";
        $url="https://api.weixin.qq.com/sns/jscode2session?appid={$AppID}&secret={$AppSecret}&js_code={$code}&grant_type=authorization_code";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_URL, $url);
        $json =  curl_exec($ch);
        curl_close($ch);
        $arr=json_decode($json,1);
        //file_put_contents('./getUnionid.txt',date('Y-m-d H:i:s').' 提交参数信息 code:'.json_encode($code)."\r\n",FILE_APPEND);
        //file_put_contents('./getUnionid.txt',date('Y-m-d H:i:s').' 提交参数信息 arr:'.json_encode($arr)."\r\n",FILE_APPEND);
        if($arr['errcode']){
            $rs['code']=1003;
            $rs['msg']='配置错误';
            //file_put_contents('./getUnionid.txt',date('Y-m-d H:i:s').' 提交参数信息 arr:'.json_encode($arr)."\r\n",FILE_APPEND);
            return $rs;
        }
        
        

        /* 小程序 绑定到 开放平台 才有 unionid  否则 用 openid  */
        $unionid=$arr['unionid'];

        if(!$unionid){
            //$rs['code']=1002;
            //$rs['msg']='公众号未绑定到开放平台';
            //return $rs;
            
            $unionid=$arr['openid'];
        }
        
        $rs['info'][0]['unionid'] = $unionid;
        $rs['info'][0]['openid'] = $arr['openid'];
        return $rs;
    }

 

'userLoginByThird' => array(
                'openid' => array('name' => 'openid', 'type' => 'string', 'min' => 1, 'require' => true,   'desc' => '第三方openid'),
                'type' => array('name' => 'type', 'type' => 'string', 'min' => 1, 'require' => true,   'desc' => '第三方标识'),
                'nicename' => array('name' => 'nicename', 'type' => 'string',   'default'=>'',  'desc' => '第三方昵称'),
                'avatar' => array('name' => 'avatar', 'type' => 'string',  'default'=>'', 'desc' => '第三方头像'),
                'sign' => array('name' => 'sign', 'type' => 'string',  'default'=>'', 'desc' => '签名'),
                'source' => array('name' => 'source', 'type' => 'string',  'default'=>'pc', 'desc' => '来源设备'),
            ),

 

/**
     * 第三方登录
     * @desc 用于用户登陆信息
     * @return int code 操作码,0表示成功
     * @return array info 用户信息
     * @return string info[0].id 用户ID
     * @return string info[0].user_nicename 昵称
     * @return string info[0].avatar 头像
     * @return string info[0].avatar_thumb 头像缩略图
     * @return string info[0].sex 性别
     * @return string info[0].signature 签名
     * @return string info[0].coin 用户余额
     * @return string info[0].login_type 注册类型
     * @return string info[0].level 等级
     * @return string info[0].province 省份
     * @return string info[0].city 城市
     * @return string info[0].birthday 生日
     * @return string info[0].token 用户Token
     * @return string msg 提示信息
     */
    public function userLoginByThird() {
        $rs = array('code' => 0, 'msg' => '', 'info' => array());
        $openid=checkNull($this->openid);
        $type=checkNull($this->type);
        $nicename=checkNull($this->nicename);
        $avatar=checkNull($this->avatar);
        $source=checkNull($this->source);
        $sign=checkNull($this->sign);
        
        
        $checkdata=array(
            'openid'=>$openid
        );
        
        $issign=checkSign($checkdata,$sign);
        if(!$issign){
            $rs['code']=1001;
            $rs['msg']='签名错误';
            return $rs;    
        }
        
        
        
        $domain = new Domain_Login();
        $info = $domain->userLoginByThird($openid,$type,$nicename,$avatar,$source);
        
        if($info==1002){
            $rs['code'] = 1002;
            //禁用信息
            $baninfo=$domain->getThirdUserban($openid,$type);
            $rs['info'][0] =$baninfo;
            return $rs;                    
        }else if($info==1003){
            $rs['code'] = 1003;
            $rs['msg'] = '该账号已被禁用';
            return $rs;    
        }

        $rs['info'][0] = $info;
        

        return $rs;
    }

……后续的数据库操作根据自己的实际项目需求自行处理。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值