Browse Source

fix:修复微信登录逻辑,没有修复好

景好勇 4 months ago
parent
commit
6dcb817a9f

+ 0 - 0
app/Http/Controllers/Auth/LoginController.php


+ 2 - 2
app/Http/Controllers/Client/WechatController.php

@@ -53,7 +53,7 @@ class WechatController extends Controller
         $validated = $request->validated();
 
         $result = $this->wechatService->getAuthUrl(
-            $validated['redirect_url'],
+            $validated['redirect_uri'],
             $validated['scope'] ?? 'snsapi_userinfo'
         );
 
@@ -87,7 +87,7 @@ class WechatController extends Controller
      * }
      * @response 422 scenario="参数验证失败" {
      *   "code": 422,
-     *   "message": "授权码不能为空|状码长度必须为32位"
+     *   "message": "授权码不能为空|状���码长度必须为32位"
      * }
      * @response 400 scenario="无效的state" {
      *   "code": 400,

+ 2 - 2
app/Http/Requests/Client/Wechat/GetAuthUrlRequest.php

@@ -22,7 +22,7 @@ class GetAuthUrlRequest extends FormRequest
     public function rules(): array
     {
         return [
-            'redirect_url' => ['required', 'url'],
+            'redirect_uri' => ['required', 'url'],
             'scope' => ['nullable', 'string', 'in:snsapi_base,snsapi_userinfo'],
         ];
     }
@@ -35,7 +35,7 @@ class GetAuthUrlRequest extends FormRequest
     public function attributes(): array
     {
         return [
-            'redirect_url' => '回调地址',
+            'redirect_uri' => '回调地址',
             'scope' => '授权范围',
         ];
     }

+ 25 - 3
app/Models/MemberSocialAccount.php

@@ -10,9 +10,31 @@ use Slowlyo\OwlAdmin\Models\BaseModel as Model;
  */
 class MemberSocialAccount extends Model
 {
-	use SoftDeletes;
+    use SoftDeletes;
 
-	protected $table = 'member_social_accounts';
+    protected $table = 'member_social_accounts';
+
+    /**
+     * 允许批量赋值的属性
+     *
+     * @var array<string>
+     */
+    protected $fillable = [
+        'user_id',
+        'platform',
+        'openid',
+        'unionid',
+        'nickname',
+        'avatar',
+        'gender',
+        'country',
+        'province',
+        'city',
+        'access_token',
+        'refresh_token',
+        'expires_in',
+        'state',
+    ];
 
     /**
      * @Author FelixYin
@@ -22,4 +44,4 @@ class MemberSocialAccount extends Model
     {
         return $this->belongsTo('App\Models\MemberUser', 'user_id');
     }
-}
+}

+ 1 - 0
app/Models/User.php

@@ -0,0 +1 @@
+ 

+ 2 - 4
app/Services/Client/AccountService.php

@@ -233,7 +233,7 @@ class AccountService
     private function storeVerifyCode(string $mobile, int $code): void
     {
         // 构建缓存键名(verify_code:手机号)
-        $key = self::VERIFY_CODE_PREFIX.$mobile;
+        $key = self::VERIFY_CODE_PREFIX . $mobile;
 
         // 将验证码存入缓存,并设置过期时间
         Cache::put($key, $code, self::VERIFY_CODE_EXPIRE);
@@ -284,7 +284,7 @@ class AccountService
     private function verifyCode(string $mobile, string $code): void
     {
         // 使用手机号和前缀构建缓存键,获取存储的验证码
-        $cacheCode = Cache::get(self::VERIFY_CODE_PREFIX.$mobile);
+        $cacheCode = Cache::get(self::VERIFY_CODE_PREFIX . $mobile);
 
         // 验证码不存在或不匹配则抛出业务异常
         if (! $cacheCode || $cacheCode != $code) {
@@ -357,7 +357,6 @@ class AccountService
             'avatar' => $userInfo['avatar'] ?? null,      // 设置微信头像,可选
             'gender' => $userInfo['gender'] ?? null,      // 设置性别,可选
         ]);
-
     }
 
     /**
@@ -566,7 +565,6 @@ class AccountService
                     'status' => 1,                    // 设置状态为有效
                 ]);
             });
-
         } catch (\Exception $e) {
             // 记录处理邀请关系时的错误日志
             Log::error('Failed to handle invite relation', [

+ 39 - 17
app/Services/Client/WechatService.php

@@ -85,7 +85,6 @@ class WechatService
 
             // 执行登录
             return $this->accountService->wxLogin($user->getId(), $userInfo);
-
         } catch (BusinessException $e) {
             throw $e;
         } catch (\Exception $e) {
@@ -98,24 +97,22 @@ class WechatService
         }
     }
 
-    /**
-     * 生成随机state
-     */
-    protected function generateState(): string
-    {
-        return md5(uniqid(microtime(true), true));
-    }
-
     /**
      * 缓存授权state
      */
     protected function cacheAuthState(string $state): void
     {
-        Cache::put(
-            $this->getAuthStateKey($state),
-            true,
-            config('wechat.auth.cache_ttl')
-        );
+        try {
+            $states = Cache::get('wechat_auth_states', []);
+            $states[$state] = true;
+            Cache::put('wechat_auth_states', $states, now()->addMinutes(30));
+        } catch (\Exception $e) {
+            Log::error('缓存微信授权state失败', [
+                'state' => $state,
+                'error' => $e->getMessage()
+            ]);
+            throw new BusinessException('系统错误,请稍后重试');
+        }
     }
 
     /**
@@ -125,11 +122,36 @@ class WechatService
      */
     protected function validateState(string $state): void
     {
-        if (! Cache::pull($this->getAuthStateKey($state))) {
-            throw new BusinessException('无效的授权请求');
+        try {
+            $states = Cache::get('wechat_auth_states', []);
+
+            if (!isset($states[$state])) {
+                Log::warning('微信授权state无效', ['state' => $state]);
+                throw new BusinessException('授权已过期,请重新授权');
+            }
+
+            // 移除已使用的state
+            unset($states[$state]);
+            Cache::put('wechat_auth_states', $states, now()->addMinutes(30));
+        } catch (BusinessException $e) {
+            throw $e;
+        } catch (\Exception $e) {
+            Log::error('验证微信授权state失败', [
+                'state' => $state,
+                'error' => $e->getMessage()
+            ]);
+            throw new BusinessException('系统错误,请稍后重试');
         }
     }
 
+    /**
+     * 生成随机state
+     */
+    protected function generateState(): string
+    {
+        return md5(uniqid((string)mt_rand(), true));
+    }
+
     /**
      * 格式化用户信息
      *
@@ -182,7 +204,7 @@ class WechatService
 
     protected function getAuthStateKey(string $state): string
     {
-        return config('wechat.auth.cache_prefix').$state;
+        return config('wechat.auth.cache_prefix') . $state;
     }
 
     /**

+ 1 - 0
resources/views/auth/login.blade.php

@@ -0,0 +1 @@
+ 

+ 8 - 16
routes/api.php

@@ -31,11 +31,18 @@ Route::prefix('client')->group(function () {
         // 发验证码
         Route::post('send-code', [AccountController::class, 'sendVerifyCode']);
         // 手机号登录
-        Route::post('login', [AccountController::class, 'login']);
+        Route::post('login', [AccountController::class, 'login'])->name('login');
         // 微信登录
         Route::post('wx-login', [AccountController::class, 'wxLogin']);
     });
 
+    // 微信相关路由(无需认证)
+    Route::prefix('wechat')->group(function () {
+        Route::get('auth-url', [WechatController::class, 'getAuthUrl']);
+        Route::post('callback', [WechatController::class, 'handleCallback']);
+        Route::get('js-config', [WechatController::class, 'getJsConfig']);
+    });
+
     // 需要认证的路由组
     Route::middleware('auth:sanctum')->group(function () {
         // 账号相关
@@ -127,27 +134,12 @@ Route::prefix('client')->group(function () {
             Route::get('{id}/code', [OrderController::class, 'generateCode']);
         });
 
-        // 钱包相关
-        Route::prefix('wallet')->group(function () {
-            Route::get('records', [WalletController::class, 'records']);
-            // 取钱包信息
-            Route::get('wallet', [WalletController::class, 'wallet']);
-            // 提现
-            Route::post('withdraw', [WalletController::class, 'withdraw']);
-        });
 
         // 团队管理路由
         Route::prefix('team')->group(function () {
             Route::get('list', [MarketDistTeamController::class, 'index'])->name('team.list');
         });
 
-        // 微信相关路由
-        Route::prefix('wechat')->group(function () {
-            Route::get('auth-url', [WechatController::class, 'getAuthUrl']);
-            Route::post('callback', [WechatController::class, 'handleCallback']);
-            Route::get('js-config', [WechatController::class, 'getJsConfig']);
-        });
-
         // 评价管理
         Route::post('comments', [CommentController::class, 'store'])->name('client.comments.store');
         Route::get('comments', [CommentController::class, 'index'])->name('client.comments.index');

+ 0 - 1
routes/web.php

@@ -124,7 +124,6 @@ Route::group(
         Route::get('shop/{shop_id}/review-records', [ShopInfoController::class, 'reviewRecords']);
         // 店铺余额冻结
         Route::post('shop/freeze-balance', [ShopInfoController::class, 'freezeBalance']);
-
     }
 );
 

+ 1 - 1
script/bin/mylog

@@ -60,7 +60,7 @@ interactive_mode() {
                     errors=$(cat storage/logs/laravel.log | grep "ERROR")
                     if [ -n "$errors" ]; then
                         echo "正在复制错误信息到剪贴板..."
-                        cat storage/logs/laravel.log | grep -m8 "ERROR" | \
+                        cat storage/logs/laravel.log | grep -m1 "ERROR" | \
                         awk '{print $0,"\n\n","上面是错误日志,请帮我修复这个bug,并始终用中文语言回答。"}' | xclip -selection clipboard
                         echo "已复制错误信息到剪贴板,你可以问AI助手,他会给你解决错误。"
                     else