validate([ 'code' => 'required' ], [ 'code.required' => '授权码必填' ]); $app = $this->getWechatApp(); $result = $app->auth->session($request->input('code')); if (data_get($result, 'errcode')) { throw new BizException(data_get($result, 'errmsg')); } $openid = data_get($result, 'openid'); $type = SocialiteType::WechatMiniProgram->value; if (!$openid) { throw new BizException('授权失败, 未找到 openid'); } try { DB::beginTransaction(); $user_social = SocialiteUser::firstOrCreate(['socialite_id' => $openid, 'socialite_type' => $type]); $user = $user_social->user; $token = ''; if ($user) { $token = $user->createToken($type)->plainTextToken; } DB::commit(); return response()->json([ 'openid' => $openid, 'token' => $token ]); } catch (Throwable $e) { DB::rollBack(); report($e); throw new BizException($e->getMessage()); } } public function bindPhone(Request $request) { $request->validate([ 'code' => 'required' ], [ 'code.required' => '授权码必填' ]); $app = $this->getWechatApp(); $result = $app->phone_number->getUserPhoneNumber($request->input('code')); if (data_get($result, 'errcode')) { throw new BizException(data_get($result, 'errmsg')); } $phone = data_get($result, 'phone_info.purePhoneNumber'); $openid = $request->input('openid'); try { DB::beginTransaction(); $user = User::where('phone', $phone)->first(); if (!$user) { $time = now(); $ip = $request->realIp(); $inviter = $this->findUserByCode($request->input('invite_code', '')); $user = User::create([ 'phone' => $phone, 'register_ip' => $ip, 'last_login_at' => $time, 'last_login_ip' => $ip, ], $inviter); } if ($openid) { SocialiteUser::updateOrCreate( ['socialite_id' => $openid, 'socialite_type' => SocialiteType::WechatMiniProgram->value], ['user_id' => $user->id] ); } $token = $user->createToken(SocialiteType::WechatMiniProgram->value); DB::commit(); return response()->json([ 'token' => $token->plainTextToken ]); } catch (Throwable $e) { DB::rollBack(); report($e); throw new BizException($e->getMessage()); } } /** * 通过邀请码搜索用户 * * @param string $code * @return \App\Models\User|null * * @throws \App\Exceptions\BizException */ protected function findUserByCode($code): ?User { if (!$code) { return null; } $user = User::when(PhoneNumber::validate($code), function ($query) use ($code) { $query->where('phone', $code); }, function ($query) use ($code) { $query->whereRelation('userInfo', 'code', $code); })->first(); if ($user === null) { throw new BizException(__('Inviter does not exist')); } return $user; } protected function getWechatApp($getway = 'default') { return Factory::miniProgram(config('wechat.mini_program.' . $getway)); } }