WechatMiniController.php 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. <?php
  2. namespace App\Http\Api;
  3. use App\Services\Login\LoginTokenService;
  4. use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
  5. use EasyWeChat\MiniApp\Application;
  6. use Illuminate\Http\JsonResponse;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Request;
  9. use Illuminate\Support\Str;
  10. use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
  11. use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
  12. use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
  13. use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
  14. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  15. class WechatMiniController extends HttpBaseController
  16. {
  17. protected $app = '';
  18. public function __construct()
  19. {
  20. parent::__construct();
  21. $this->setWebsite(__NAMESPACE__);
  22. $config = config('easywechat.mini_app.default');
  23. try {
  24. $this->app = new Application($config);
  25. } catch (InvalidArgumentException $e) {
  26. }
  27. }
  28. public function loginIn(): JsonResponse
  29. {
  30. $sceneStr = Request::post('sceneStr'); // 场景值
  31. $code = Request::post('code');
  32. $wxInfo = Request::post('userInfo');
  33. if (empty($productMid)) {
  34. return responseMessage(3000, '参数错误,请重试!');
  35. }
  36. if (empty($code) || empty($wxInfo)) {
  37. return responseMessage(3001, '参数错误,请重试!');
  38. }
  39. $response = $this->app->getClient()->get('/sns/jscode2session', [
  40. 'js_code' => $code,
  41. 'grant_type' => 'authorization_code',
  42. ]);
  43. try {
  44. $result = $response->toArray();
  45. if ($result) {
  46. // 判断用户是否已经存在
  47. $openid = $result['openid'];
  48. $unionid = $result['unionid'];
  49. $userInfo = DB::table('user_wechat_mini_program')->where(['openid' => $openid, 'unionid' => $unionid])->first();
  50. if ($userInfo) {
  51. // 更新头像和昵称
  52. $data = [
  53. 'nick' => $wxInfo['nickname'],
  54. 'wx_avatar' => $wxInfo['avatar'],
  55. 'wx_info' => json_encode($wxInfo),
  56. ];
  57. $userId = $userInfo->id;
  58. $isSuccess = DB::table('user_wechat_mini_program')->where('user_id', $userId)->update($data);
  59. } else {
  60. // 插入数据
  61. $isSuccess = DB::transaction(function () use ($result, $wxInfo) {
  62. $userData = [
  63. 'mid' => Str::random(12),
  64. 'username' => $wxInfo['nickname'],
  65. 'real_username' => '',
  66. 'avatar' => $wxInfo['avatar'],
  67. 'roles' => json_encode([]),
  68. 'remember_token' => '',
  69. 'status' => 1,
  70. 'created_at' => time(),
  71. 'updated_at' => time(),
  72. ];
  73. $userId = DB::table('user')->insertGetId($userData);
  74. $data = [
  75. 'mid' => Str::random(12),
  76. 'user_id' => $userId,
  77. 'openid' => $result['openid'],
  78. 'session_key' => $result['session_key'],
  79. 'unionid' => $result['unionid'],
  80. 'nick' => $wxInfo['nickname'],
  81. 'wx_avatar' => $wxInfo['avatar'],
  82. 'wx_info' => json_encode($wxInfo),
  83. ];
  84. DB::table('user_wechat_mini_program')->insertGetId($data);
  85. });
  86. }
  87. if ($isSuccess) {
  88. // 设置登录的token
  89. $loginToken = new LoginTokenService('user_access_token');
  90. if (!in_array($sceneStr, ['web', 'mobile', 'officialAccount', 'miniProgram'])) {
  91. $token = $loginToken->createToken($userId, $sceneStr);
  92. } else {
  93. // 该场景值,可以为软件的mid
  94. $isExist = DB::table('product')->where('mid', $sceneStr)->count();
  95. if ($isExist) {
  96. $token = $loginToken->createOnlyOneToken($userId, $sceneStr);
  97. } else {
  98. return responseMessage(3003, '参数错误,请重试!');
  99. }
  100. }
  101. return responseMessage(1001, '操作成功!', ['token' => $token]);
  102. } else {
  103. return responseMessage(3002, '操作失败!');
  104. }
  105. }
  106. } catch (ClientExceptionInterface $e) {
  107. } catch (DecodingExceptionInterface $e) {
  108. } catch (RedirectionExceptionInterface $e) {
  109. } catch (ServerExceptionInterface $e) {
  110. } catch (TransportExceptionInterface $e) {
  111. }
  112. return responseMessage(3004, '操作失败,请重试!');
  113. }
  114. }