1、小程序封装
getUserProfile 获取用户信息。页面产生点击事件(例如 button 上 bindtap 的回调中)后才可调用,每次请求都会弹出授权窗口,用户同意后返回 userInfo。该接口用于替换 wx.getUserInfo,详见 用户信息接口调整说明
async weixinlogin () {
let wxLoginRt={code:''}
// 获取code
Promisify('login').then(res=>{
wxLoginRt.code=res.code
}).catch((err) => {
})
const wxUserInfo = await Promisify('getUserProfile', { lang: 'zh_CN',desc:'登录' }).catch((err) => {
throw Error('获取用户信息失败')
})
console.log(wxUserInfo)
const { code: lp_code } = wxLoginRt
wxUserInfo.rawData = JSON.parse(wxUserInfo.rawData)
loginByWxLp({
code: lp_code,
encryptedData:wxUserInfo.encryptedData,
iv:wxUserInfo.iv,
rawData: JSON.stringify(wxUserInfo.rawData),
signature:wxUserInfo.signature,
}).then(res=>{
if(res.code == 1){
console.log('登录成功');
}
}).catch(e=>{
console.error(e);
})
}
},
2、后台接口
使用easywachat
public function loginByWxLp()
{
$post = $this->request->post();
$code = $post['code'];
$encryptedData = $post['encryptedData'];
$rawData = $post['rawData'];
$signature = $post['signature'];
$iv = $post['iv'];
if (empty($code) || empty($encryptedData) || empty($iv) || empty($rawData)) {
$this->error('missing params');
}
$app = Factory::miniProgram(config('wechat'));
$open_res = $app->auth->session($code);
if (empty($open_res['session_key'])) {
Log::write('wxLoginFail:' . json_encode($open_res, JSON_UNESCAPED_UNICODE), 'notice');
$this->apiError('code2session fail');
}
try {
$wx_info = $app->encryptor->decryptData($open_res['session_key'], $iv, $encryptedData);
$wx_info = array_merge($open_res, $wx_info);
Log::write('wxLoginSucess:' . json_encode($wx_info, JSON_UNESCAPED_UNICODE), 'notice');
} catch (\Throwable $e) {
Log::write('wxLoginFail:' . $e->getMessage(), 'notice');
}
$user = User::where('open_id', $open_res['openid'])->find();
if($user){
//用户已存在,则返回用户信息
}else{
//用户不存在,则新增用户
}
}