Status message

Maintenant, vous regardez: WeChat mini program login args and returns

WeChat mini program login args and returns

  1. //app.js
  2. App({
  3. onLaunch: function () {
  4. // 展示本地存储能力
  5. var logs = wx.getStorageSync('logs') || []
  6. logs.unshift(Date.now())
  7. wx.setStorageSync('logs', logs)
  8. var obj=this
  9. // 登录
  10. wx.login({
  11. success: res => {
  12. // 发送 res.code 到后台换取 openId, sessionKey, unionId
  13. wx.request({
  14. url: '<a href="http://www.example.com/api/v1/mini/auth/register',
  15. ">http://www.example.com/api/v1/mini/auth/register',
  16. </a> data: {
  17. code: res.code
  18. },
  19. method: 'POST',
  20. success(res) {
  21. if (res.statusCode == 200) {
  22. //console.log(res);
  23. try {
  24. wx.setStorageSync('access_token', res.data.access_token);
  25. //wx.setStorageSync('openid', res.data.openid);
  26. } catch (e) { } //end of success
  27. obj.get_user_settings();
  28. }
  29. }
  30. })
  31. }
  32. })
  33.  
  34. },
  35.  
  36. get_user_settings: function() {
  37.  
  38. // 获取用户信息
  39. wx.getSetting({
  40. success: res => {
  41. if (res.authSetting['scope.userInfo']) {
  42. // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
  43. wx.getUserInfo({
  44. success: res => {
  45. // 可以将 res 发送给后台解码出 unionId
  46. this.globalData.userInfo = res.userInfo
  47.  
  48. wx.request({
  49. url: '<a href="http://www.example.com/api/v1/mini/auth',
  50. ">http://www.example.com/api/v1/mini/auth',
  51. </a> data: {
  52. iv: res.iv,
  53. encrypted_data: res.encryptedData
  54. },
  55. method: 'POST',
  56. header: {
  57. 'Authorization': 'Bearer ' + wx.getStorageSync('access_token')
  58. },
  59. success(res) {
  60. console.log(res)
  61. }
  62. })
  63.  
  64. // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
  65. // 所以此处加入 callback 以防止这种情况
  66. if (this.userInfoReadyCallback) {
  67. this.userInfoReadyCallback(res)
  68. }
  69. }
  70. })
  71. }
  72. }
  73. })
  74. },
  75.  
  76. globalData: {
  77. userInfo: null
  78. }
  79. })

Laravel backend to handle request;

  1. namespace App\Api\V1\Controllers;
  2.  
  3. use Auth;
  4. use App\User;
  5. use JWTAuth;
  6. use Response;
  7. use Illuminate\Http\Request;
  8. use App\Http\Controllers\Controller;
  9. use App\Http\Requests\Api\MiniAuthorizationRequest;
  10. use App\Http\Requests\Api\MiniGetCodeRequest;
  11. use Illuminate\Support\Facades\Hash;
  12. use Tymon\JWTAuth\Exceptions\JWTException;
  13.  
  14. class MinisController extends Controller
  15. {
  16. //
  17. public function register(MiniGetCodeRequest $request){
  18.  
  19. $miniProgram = \EasyWeChat::miniProgram();
  20. $data = $miniProgram->auth->session($request->code);
  21.  
  22. $user = User::where('wechat_openId', $data['openid'])->first();
  23.  
  24. if( !$user) {
  25. $user = User::Create([
  26. 'name' => 'wechat',
  27. 'email' => $data['openid'].'@wechat.com',
  28. 'password' => Hash::make(str_random(8)),
  29. 'wechat_openId' => $data['openid'],
  30. 'wechat_session_key' => $data['session_key']
  31. ]);
  32. } else {
  33. $user->update([
  34. 'wechat_session_key' => $data['session_key']
  35. ]);
  36.  
  37. }
  38.  
  39.  
  40. try {
  41. // attempt to verify the credentials and create a token for the user
  42. if (!$token = Auth::guard('api')->fromUser($user)) {
  43. return Response::json(['error' => 'invalid_credentials'], 401);
  44. }
  45.  
  46. } catch (JWTException $e) {
  47. // something went wrong whilst attempting to encode the token
  48. return Response::json(['error' => 'could_not_create_token'], 500);
  49. }
  50.  
  51. return $this->respondWithToken($token)->setStatusCode(200);
  52.  
  53. }
  54.  
  55.  
  56. //store
  57. public function store(MiniAuthorizationRequest $request){
  58.  
  59. $encrypted_data = $request->encrypted_data;
  60. $iv = $request->iv;
  61. $token_user = Auth::guard('api')->getUser();
  62. $user = User::where('wechat_openId', $token_user->wechat_openId)->first();
  63.  
  64. $miniProgram = \EasyWeChat::miniProgram();
  65.  
  66. try {
  67. $r = $miniProgram->encryptor->decryptData($user->wechat_session_key, $iv, $encrypted_data);
  68. } catch (\Exception $e) {
  69. return resonse()->json(['error' => 'decrypt user data failed'], 500);
  70. }
  71.  
  72. $user->update([
  73. 'name' => $r['nickName'],
  74. 'wechat_gender' => $r['gender'],
  75. 'wechat_city' => $r['city'],
  76. 'wechat_province' => $r['province'],
  77. 'wechat_country' => $r['country'],
  78. 'wechat_unionId' => $r['unionId'] ?? NULL ,
  79. 'avatar' => $r['avatarUrl']
  80. ]);
  81.  
  82. return response()->json(['message' => 'user profile update successfully']);
  83. }
  84.  
  85.  
  86. //update token
  87. public function refresh()
  88. {
  89. $token = Auth::guard('api')->refresh();
  90. return $this->respondWithToken($token);
  91. }
  92.  
  93. /**
  94.   * Get the authenticated User.
  95.   *
  96.   * @return \Illuminate\Http\JsonResponse
  97.   */
  98. public function me()
  99. {
  100. return response()->json(Auth::guard('api')->getUser());
  101. }
  102.  
  103.  
  104. // destroy token
  105. public function destroy()
  106. {
  107. Auth::guard('api')->logout();
  108. return response()->json(['message' => 'Successfully logged out']);
  109. }
  110.  
  111. //return standard format
  112. protected function respondWithToken($token)
  113. {
  114. return response()->json([
  115. 'access_token' => $token,
  116. 'token_type' => 'Bearer',
  117. 'expires_in' => Auth::guard('api')->factory()->getTTL() * 60
  118. ]);
  119. }
  120.  
  121. }