1, small program packaging
GetUserProfile Gets user information. The page is invoked after a click event (such as in the bindtap callback on a Button), and an authorization window pops up for each request, which returns userInfo after the user agrees. This interface is used to replace wx.getUserInfo. For details, see User Information Interface Adjustment
async weixinlogin () {
let wxLoginRt={code:' '}
/ / access code
Promisify('login').then(res= >{
wxLoginRt.code=res.code
}).catch((err) = >{})const wxUserInfo = await Promisify('getUserProfile', { lang: 'zh_CN'.desc:'login' }).catch((err) = > {
throw Error('Failed to obtain user information')})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('Login successful');
}
}).catch(e= >{
console.error(e); })}},Copy the code
2. Background interface
Using 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) {// If the user already exists, the user information is displayed
}else{
// If the user does not exist, a new user is added}}Copy the code