1.小程序app.js onLaunch()方法中插入
let token = wx.getStorageSync('token')
if (!token) {
wx.login({
success:ret=>{
let code = ret.code
wx.request({
url: 'http://www.zy.com/api/wxlogin',
method:"POST",
data:{code},
success:res=>{
console.log(res.data);
wx.setStorageSync('token', res.data.data)
}
})
}
})
}
2.后台代码
/**
* 微信静默登录
*/
public function wxLogin(Request $request)
{
$code = $request->post('code');
$appid = '**********';
$appSecret= '**********';
$url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appSecret&js_code=$code&grant_type=authorization_code";
$res = json_decode(file_get_contents($url), true); //返回openid,session_key
$getUserInfo = User::where('openid',$res['openid'])->first();
if ($getUserInfo) {
$userId = $getUserInfo->id;
} else {
$create['openid'] = $res['openid'];
$create['session_key'] = $res['session_key'];
$result = User::create($create);
$userId = $result->id;
}
$token=JwtService::createToken($userId);
return ['code'=>200,'msg'=>'ok','data'=>$token];
}