关于利于tp5后台,进行微信小程序的登录验证

1.首先先贴出我的后端代码

public function wxlogin1(){
         $get = input('post.');
         $param['appid'] = 'xxxxxxxxxxx';    //小程序id
         $param['secret'] = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';    //小程序密钥
         $param['js_code'] = str_replace(' ','+',$get['code']);
         $param['grant_type'] = 'authorization_code';

         /**
         * 发送HTTP请求方法
         * @param  string $url    请求URL
         * @param  array  $params 请求参数
         * @param  string $method 请求方法GET/POST
         * @return array  $data   响应数据
         */
          function httpCurl($url, $params, $method = 'POST', $header = array(), $multi = false){
            date_default_timezone_set('PRC');
            $opts = array(
                CURLOPT_TIMEOUT        => 30,
                CURLOPT_RETURNTRANSFER => 1,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_HTTPHEADER     => $header,
                CURLOPT_COOKIESESSION  => true,
                CURLOPT_FOLLOWLOCATION => 1,
                CURLOPT_COOKIE         =>session_name().'='.session_id(),
            );
            /* 根据请求类型设置特定参数 */
            switch(strtoupper($method)){
                case 'GET':
                    // $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                    // 链接后拼接参数  &  非?
                    $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                    break;
                case 'POST':
                    //判断是否传输文件
                    $params = $multi ? $params : http_build_query($params);
                    $opts[CURLOPT_URL] = $url;
                    $opts[CURLOPT_POST] = 1;
                    $opts[CURLOPT_POSTFIELDS] = $params;
                    break;
                default:
                    throw new Exception('不支持的请求方式!');
            }
            /* 初始化并执行curl请求 */
            $ch = curl_init();
            curl_setopt_array($ch, $opts);
            $data  = curl_exec($ch);
            $error = curl_error($ch);
            curl_close($ch);
            if($error) throw new Exception('请求发生错误:' . $error);
            return  $data;
        }


         $http_key = httpCurl('https://api.weixin.qq.com/sns/jscode2session', $param, 'GET');
        $session_key = json_decode($http_key,true);
        //print_r(http_build_query($param));
        if (!empty($session_key['session_key'])) {
        $appid = $param['appid'];
        $encrypteData = urldecode($get['encrypteData']);
        $iv = str_replace(' ','+',$get['iv']);


         function decryptData( $appid , $sessionKey, $encryptedData, $iv ){
            $OK = 0;
            $IllegalAesKey = -41001;
            $IllegalIv = -41002;
            $IllegalBuffer = -41003;
            $DecodeBase64Error = -41004;
         
            if (strlen($sessionKey) != 24) {
                return $IllegalAesKey;
            }
            $aesKey=base64_decode($sessionKey);
         
            if (strlen($iv) != 24) {
                return $IllegalIv;
            }
            $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 $IllegalBuffer;
            }
            if( $dataObj->watermark->appid != $appid )
            {
                return $DecodeBase64Error;
            }
            $data = json_decode($result,true);
         
            return $data;
        }

        $errCode = decryptData($appid, $session_key['session_key'], $encrypteData, $iv);
        //把appid写入到数据库中
        $data['appid'] = $errCode['openId'];
        $data['nicheng'] = $errCode['nickName'];
        $data['publishtime'] = time();
        $data['sex'] = $errCode['gender'];
        $data['avatarUrl'] = $errCode['avatarUrl'];
        // $data['platform'] = $get['platform'];
        if (false == Db::name('message_user')->where(['appid' => $data['appid']])->find()) {
            Db::name('message_user')->insert($data);
            $value = Db::name('message_user')->where(['appid' => $data['appid']])->field('uId,appid,nicheng,publishtime,sex,platform,avatarUrl')->select();
        }else{
            $value = Db::name('message_user')->where(['appid' => $data['appid']])->field('uId,appid,nicheng,publishtime,sex,platform,avatarUrl')->select();
        }
        // $array = array_merge_recursive($errCode, $value);
        return json_encode(['data'=>$get['code'],'status'=>1]);
    }else{
        return json_encode(['status'=>0]);
    }
           // return json(['status' =>1]);
     }

2.我的小程序端代码

var app = getApp();

var url = 'http://shzujune.com/mianya/public/index/index/wxlogin';

var login = function (code, encrypteData, iv) {

var that = this

扫描二维码关注公众号,回复: 6212227 查看本文章

//创建一个dialog提示

wx.showToast({

title: '正在登录...',

icon: 'loading',

duration: 5000

});

wx.request({

url: url,

method: 'post',

data: {

code: code,

encrypteData: encrypteData,

iv: iv

},

header: {

'Content-Type': 'application/json'

},

success: function (res) {

wx.hideToast()

console.log( res.data)

app.globalData.userInfo = res.data

console.log(app.globalData.userInfo);

},

fail: function () {

wx.showToast({

title: '网络错误!',

duration: 2000

})

},

complete: function () {

}

})

}

Page({

data: {

//判断小程序的API,回调,参数,组件等是否在当前版本可用。

canIUse: wx.canIUse('button.open-type.getUserInfo')

},

onLoad: function () {

var that = this

wx.login({

success: function (res) { //登录成功

//console.log(res)

if (res.code) {

var code = res.code

wx.getUserInfo({ //getUserInfo流程

success: function (data) { //getUserInfo获取用户信息成功

//console.log(data)

//encrypteData加密密文,iv偏移向量,encodeURIComponent把加密字符串解密成URI字符串

var encryptedData = encodeURIComponent(data.encryptedData);

var iv = data.iv;

//请求自己的服务器

login(code, encryptedData, iv);

//已经授权的用户

wx.switchTab({

url: '../rec/rec',

})

}

})

} else {

console.log('用户没有进行授权!' + res.errMsg)

}

}

});

},

bindGetUserInfo: function (e) {

//console.log(e)

if (e.detail.userInfo) {

//用户按了允许授权的按钮

var that = this

wx.login({

success: function (res) {

if (res.code) {

var code = res.code

wx.getUserInfo({

success: function (data) {

var encryptedData = encodeURIComponent(data.encryptedData);

var iv = data.iv;

//请求自己的服务器

login(code, encryptedData, iv);

}

})

}

}

})

//授权成功后,跳转进入小程序首页

wx.switchTab({

url: '../rec/rec'

})

} else {

//用户按了拒绝按钮

wx.showModal({

title: '警告',

content: '您点击了拒绝授权,将无法进入小程序,请授权之后再进入!!!',

showCancel: false,

confirmText: '返回授权',

success: function (res) {

if (res.confirm) {

console.log('用户点击了“返回授权”')

}

}

})

}

},

})

3.经过调试,就可以正常使用了

猜你喜欢

转载自blog.csdn.net/qq_41240287/article/details/89078720
今日推荐