小程序段JS代码:
login(){ var that = this wx.getUserProfile({ desc: '授权登录', success(res){ console.log(res) that.setData({ 'username':res.userInfo.nickName, 'faceUrl':res.userInfo.avatarUrl, 'encryptedData':res.encryptedData, 'iv':res.iv }) wx.login({ success(res){ console.log(res) that.setData({ 'js_code' : res.code }) wx.request({ url: 'XXXXXXXXXXXXXXXXXX',//此处写你自己的服务器URL地址 method:'POST', header:{ 'content-type':'application/x-www-form-urlencoded' }, data:{ 'js_code':that.data.js_code, 'encryptedData':that.data.encryptedData, 'iv':that.data.iv }, success(res){ console.log(res) that.setData({ 'openid':res.data }) console.log(that.data.openid) var openid = that.data.openid } }) } }) } }) }
PHP代码:
<?php $appid = 'XXXXXXXXXXXX'; $secret = 'XXXXXXXXXXXXXXXXXXXXXXX'; $js_code = $_POST['js_code']; $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $js_code . '&grant_type=authorization_code'; $getOpenid = curl_init(); curl_setopt($getOpenid, CURLOPT_URL, $url); curl_setopt($getOpenid, CURLOPT_RETURNTRANSFER, 1); curl_setopt($getOpenid, CURLOPT_HEADER, 0); curl_setopt($getOpenid, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($getOpenid, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($getOpenid, CURLOPT_CONNECTTIMEOUT, 10); $resultSession = curl_exec($getOpenid); //echo $resultSession; $disposeData = json_decode($resultSession,true); $openid = $disposeData['openid']; $sessionKey = $disposeData['session_key']; echo $openid; /** * 分割线,上方获取sessionKey,下方使用sessionKey进行解密 */ $encryptedData = $_POST['encryptedData']; $iv = $_POST['iv']; $encryptedData = str_replace(' ', '+', $encryptedData); //此处接收到微信发送的数据时,PHP会将数据中的+转化为空格,此处需要将空格转化为+ $iv = str_replace(' ', '+', $iv); $aesKey = base64_decode($sessionKey); $aesIV = base64_decode($iv); $aesCipher = base64_decode($encryptedData); $result = openssl_decrypt($aesCipher, 'AES-128-CBC', $aesKey, 1, $aesIV); $userData = json_decode($result,true); $userName = $userData['nickName']; $faceUrl = $userData['avatarUrl']; //echo $userName . $faceUrl; /** * 连接数据库,存入用户基础信息 */ $dataHost = '127.0.0.1:3306'; $dataName = 'root'; $dataPass = 'root'; $dataBase = 'testin'; $connect = new mysqli($dataHost, $dataName, $dataPass, $dataBase); $selectOpenid = 'select * from in_database where openid = "'.$openid.'"'; $sql = 'insert into in_database (username,faceUrl,openid) values ("' . $userName . '","' . $faceUrl . '","' . $openid . '");'; if($connect){ $selectResult = $connect -> query($selectOpenid); $resultNum = $selectResult -> num_rows; if($resultNum == 1){ $connect -> close(); }else if($connect -> query($sql) == 1){ echo '数据插入成功'; $connect -> close(); } }
以上代码大致流程为:
1.在小程序界面点击按钮发送js_code与encryptedData和iv到自己的服务器
2.服务器接收到js_code后配合appid与secret共同调用微信接口获取session_key与openid
3.使用获取到的encryptedData与iv以及获取到的session_key进行解密,将返回的数据转化为数组,提取其中的nickName与avatarUrl
4.连接服务器,将openid,nickName,avatarUrl,存入数据库之中