//app.js App({ onLaunch: function () { // 展示本地存储能力 var logs = wx.getStorageSync('logs') || [] logs.unshift(Date.now()) wx.setStorageSync('logs', logs) var obj=this // 登录 wx.login({ success: res => { // 发送 res.code 到后台换取 openId, sessionKey, unionId wx.request({ url: '<a href="http://www.example.com/api/v1/mini/auth/register', ">http://www.example.com/api/v1/mini/auth/register', </a> data: { code: res.code }, method: 'POST', success(res) { if (res.statusCode == 200) { //console.log(res); try { wx.setStorageSync('access_token', res.data.access_token); //wx.setStorageSync('openid', res.data.openid); } catch (e) { } //end of success obj.get_user_settings(); } } }) } }) }, get_user_settings: function() { // 获取用户信息 wx.getSetting({ success: res => { if (res.authSetting['scope.userInfo']) { // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框 wx.getUserInfo({ success: res => { // 可以将 res 发送给后台解码出 unionId this.globalData.userInfo = res.userInfo wx.request({ url: '<a href="http://www.example.com/api/v1/mini/auth', ">http://www.example.com/api/v1/mini/auth', </a> data: { iv: res.iv, encrypted_data: res.encryptedData }, method: 'POST', header: { 'Authorization': 'Bearer ' + wx.getStorageSync('access_token') }, success(res) { console.log(res) } }) // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回 // 所以此处加入 callback 以防止这种情况 if (this.userInfoReadyCallback) { this.userInfoReadyCallback(res) } } }) } } }) }, globalData: { userInfo: null } })
Laravel backend to handle request;
namespace App\Api\V1\Controllers; use Auth; use App\User; use JWTAuth; use Response; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Requests\Api\MiniAuthorizationRequest; use App\Http\Requests\Api\MiniGetCodeRequest; use Tymon\JWTAuth\Exceptions\JWTException; class MinisController extends Controller { // public function register(MiniGetCodeRequest $request){ $miniProgram = \EasyWeChat::miniProgram(); $data = $miniProgram->auth->session($request->code); $user = User::where('wechat_openId', $data['openid'])->first(); if( !$user) { $user = User::Create([ 'name' => 'wechat', 'email' => $data['openid'].'@wechat.com', 'wechat_openId' => $data['openid'], 'wechat_session_key' => $data['session_key'] ]); } else { $user->update([ 'wechat_session_key' => $data['session_key'] ]); } try { // attempt to verify the credentials and create a token for the user if (!$token = Auth::guard('api')->fromUser($user)) { return Response::json(['error' => 'invalid_credentials'], 401); } } catch (JWTException $e) { // something went wrong whilst attempting to encode the token return Response::json(['error' => 'could_not_create_token'], 500); } return $this->respondWithToken($token)->setStatusCode(200); } //store public function store(MiniAuthorizationRequest $request){ $encrypted_data = $request->encrypted_data; $iv = $request->iv; $token_user = Auth::guard('api')->getUser(); $user = User::where('wechat_openId', $token_user->wechat_openId)->first(); $miniProgram = \EasyWeChat::miniProgram(); try { $r = $miniProgram->encryptor->decryptData($user->wechat_session_key, $iv, $encrypted_data); } catch (\Exception $e) { return resonse()->json(['error' => 'decrypt user data failed'], 500); } $user->update([ 'name' => $r['nickName'], 'wechat_gender' => $r['gender'], 'wechat_city' => $r['city'], 'wechat_province' => $r['province'], 'wechat_country' => $r['country'], 'wechat_unionId' => $r['unionId'] ?? NULL , 'avatar' => $r['avatarUrl'] ]); return response()->json(['message' => 'user profile update successfully']); } //update token public function refresh() { $token = Auth::guard('api')->refresh(); return $this->respondWithToken($token); } /** * Get the authenticated User. * * @return \Illuminate\Http\JsonResponse */ public function me() { return response()->json(Auth::guard('api')->getUser()); } // destroy token public function destroy() { Auth::guard('api')->logout(); return response()->json(['message' => 'Successfully logged out']); } //return standard format protected function respondWithToken($token) { return response()->json([ 'access_token' => $token, 'token_type' => 'Bearer', 'expires_in' => Auth::guard('api')->factory()->getTTL() * 60 ]); } }