必须关联同一微信开放平台
必须关联同一微信开放平台
必须关联同一微信开放平台
小程序页面点击登录 需要现获取code
/**
* 测试登陆
*/
function testLogin(url,cancleurl)
{
wx.showLoading({
title: '加载中...',
})
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
wx.login({
success: function(res){
var s = res.code
loginModel.login(res.code)
.then(loginres => {
wx.getUserInfo({
success: function(res){
loginModel.uniid(res.encryptedData ,res.iv , s ,loginres.data.session_key)
.then(res=>{
app.userInfo = res.data[0]
wx.hideLoading({
})
})
}
})
})
},
})
// 所以此处加入 callback 以防止这种情况
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
wx.hideLoading({
})
} else {
wx.hideLoading({
})
wx.reLaunch({
url: '/pages/login/login?url=' + url + '&cancleurl=' + cancleurl
})
}
}
})
}
wx.log函数 现获取code 然后带着code 去服务器请求下边的函数
下边是服务器获取code 的处理方法
/**
* 登录 code
*/
public function index()
{
$code = $_GET['code'];
$url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$this->appid."&secret=".$this->secret."&js_code=".$code."&grant_type=authorization_code";
$res = $this->CurlRequest($url);
return $res;
}
然后 获得返回的数据后再次请求
带上参数 encryptedData iv code session_key 调用服务器上的方法
$data = [];
$param = Request::instance()->param();
$this->unionid = new Unionid($this->appid ,$param['session_key']);
$this->unionid->decryptData($param['encryptdata'],$param['iv'] ,$data);
$tmpdata = json_decode($data , true);
这里调用了 new Unionid这个类 下边是这个类里边所有的数据
<?php
namespace app\shebao\controller;
class Unionid
{
private $appid;
private $sessionKey;
/**
* 构造函数
* @param $sessionKey string 用户在小程序登录后获取的会话密钥
* @param $appid string 小程序的appid
*/
public function __construct( $appid, $sessionKey)
{
$this->sessionKey = $sessionKey;
$this->appid = $appid;
}
/**
* 检验数据的真实性,并且获取解密后的明文.
* @param $encryptedData string 加密的用户数据
* @param $iv string 与用户数据一同返回的初始向量
* @param $data string 解密后的原文
*
* @return int 成功0,失败返回对应的错误码
*/
public function decryptData( $encryptedData, $iv, &$data )
{
if (strlen($this->sessionKey) != 24) {
return 'sessionKey error...';
}
$aesKey=base64_decode($this->sessionKey);
if (strlen($iv) != 24) {
return 'iv error...';
}
$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 'dataObj error...';
}
if( $dataObj->watermark->appid != $this->appid )
{
return 'dataObj error...';
}
$data = $result;
return 'OK';
}
}
实例化后 在调用decryptData() 这个方法 最后$data 里边的数据为返回的数据 转化为数组之后里边就有需要的Unionid
到这来就获取到Unionid 然后根据自己的逻辑存储信息到数据库
自己瞎捉摸的 数据反正是出来了 如果哪里写的不好欢迎提出