小程序授权登录并获取手机号

记录:小程序授权登录并获取手机号

PHP代码:

	public function __construct()
    {
    	$site = Config::get("site");
        $WX_AppID = $site['WX_AppID'];
        $WX_AppSecret = $site['WX_AppSecret'];
        $this->appid = $WX_AppID;
        $this->secret = $WX_AppSecret;
        parent::__construct();
    }
    
    /**
     * 小程序登录
     *
     * @ApiMethod (POST)
     * @param string $code     Code码
     */
    public function wxlogin()
    {
        $code = $this->request->post('code');
        if (!$code) {
            $this->error('code不能为空');
        }
        $nick_name = $this->request->post('nick_name/s','','trim');
        $avatar = $this->request->post('avatar/s','','trim');
        $gender = $this->request->post('gender/d','','trim');
        $city = $this->request->post('city/s','','trim');
        $province = $this->request->post('province/s','','trim');
        $country = $this->request->post('country/s','','trim');
        $share_id = $this->request->post('share_id/d',0);

        // 获取小程序配配置,获取openid 跟 session_key
        $wxData = $this->getOpenid($code);
        if($wxData['status'] == 'error'){
            $this->error($wxData['msg']);
        }
        $openid = $wxData['data']['openid'];
        $sessionKey = $wxData['data']['session_key'];
        $unionid = $wxData['data']['unionid'];

        //检测上级
        $pid = 0;
        $parentids = '';
        if($share_id){
            $parentUser = model('user')->field('id,parentids')->find($share_id);
            if($parentUser){
                $pid = $parentUser['id'];
                if($parentUser['parentids']){
                    $parentids = $parentUser['parentids'].','.$pid;
                }else{
                    $parentids = $pid;
                }                
            }
        }

        $userinfo = \app\admin\model\User::where(['openid' => $openid])->find();
        if ($userinfo) {
            $userinfo->nickname = $nick_name;
            $userinfo->avatar = $avatar;
            $userinfo->gender = $gender;
            $userinfo->city = $city;
            $userinfo->province = $province;
            $userinfo->country = $country;
            $userinfo->unionid = $unionid;
            $userinfo->save();
            $this->auth->direct($userinfo['id']);
        } else {
            //生成邀请码
            $invite_code = $this->callcheckstr();
            $user = new \app\admin\model\User();
            $user->data([
                'nickname' => $nick_name,
                'avatar' => $avatar,
                'gender' => $gender,
                'city' => $city,
                'province' => $province,
                'country' => $country,
                'status' => 'normal',
                'openid' => $openid,
                'unionid' => $unionid,
                'invite_code'=>$invite_code,
                'pid'=>$pid,
                'parentids'=>$parentids,
                'group_id'=>1,
            ]);
            $user->save();
            $this->auth->direct($user->id);
        }
        $this->success('登录成功', $this->auth->getUserinfo());
    }


    /**
     * 小程序授权获取手机号
     */
    public function wxGetPhone()
    {
        $iv = $this->request->post("iv", '', 'trim');
        $encryptedData = $this->request->post("encryptedData", '', 'trim');
        $code = $this->request->post('code');
        if (!$code) {
            $this->error('code不能为空');
        }

        // 获取小程序配配置,获取openid 跟 session_key
        $wxData = $this->getOpenid($code);
        if($wxData['status'] == 'error'){
            $this->error($wxData['msg']);
        }
        $sessionKey = $wxData['data']['session_key'];

        $datainfo = $this->auth->getUserinfo();
        if (!$iv || !$encryptedData) {
            $this->error('传参有误');
        }
        $errCode = self::decryptData($encryptedData, $iv, $data, $sessionKey, $this->appid);
        if ($errCode == 0) {
            $result = json_decode($data, true);
            if (isset($result['phoneNumber'])) {
                $user = \app\admin\model\User::get($datainfo['id']);
                $user->mobile = $result['phoneNumber'];
                $user->save();
                $this->success('获取成功', $result);
            } else {
                $this->error('号码获取失败');
            }
        } else {
            $this->error('用户信息更新失败');
        }
    }

    
    /**
     * 获取小程序配配置
     * @param $code 用来交换获取openid 跟 session_key
     */
    static function getOpenid($code)
    {
        $url = sprintf('https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code', $this->appid, $this->secret, $code);
        $result = Http::get($url);
        $wxResult = json_decode($result, true);
        if (empty($wxResult)) {
            return ['status'=>'error','msg'=>'获取sessin_key及openID时异常'];
        }
        if (isset($wxResult['errcode']) && $wxResult['errcode'] != 0) {
            return ['status'=>'error','msg'=>$wxResult['errmsg']];
        }
        $item = [
            'openid' => $wxResult['openid'],
            'session_key' => $wxResult['session_key'],
            'unionid' => isset($wxResult['unionid']) ? $wxResult['unionid'] : '',
        ];
        return ['status'=>'success','data'=>$item];
    }

    
    /**
     * 检验数据的真实性,并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0,失败返回对应的错误码
     */
    static function decryptData($encryptedData, $iv, &$data, $sessionKey, $appid)
    {
        if (strlen($sessionKey) != 24) {
            return -41001;
        }
        $aesKey = base64_decode($sessionKey);


        if (strlen($iv) != 24) {
            return -41002;
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            return -41003;
        }
        if ($dataObj->watermark->appid != $appid) {
            return -41003;
        }
        $data = $result;
        return 0;
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值