getPhoneNumber($code); $worker = $this->getWorkerService()->getByTel($phone); $this->tryBindPhoneNumber($worker); $tokenData = Token::get($vendorToken); if (!$tokenData) { $this->apiError('vendor_token 无效'); } $workerVendor = $this->getWorkerVendorModel()->find($tokenData['user_id']); if ($workerVendor->worker_id) { $this->apiError('绑定失败,该微信已绑定手机号'); } //绑定手机号 $workerVendor->worker_id = $worker->id; $workerVendor->save(); Token::delete($vendorToken); return $worker->id; } /** * 微信登录 * @param string $code * @return array */ public function login(string $code) { $app = $this->getMiniProgramApp(); try { $info = $app->auth->session($code); } catch (InvalidConfigException $e) { $this->apiError('登录失败', $e); } if (isset($info['errcode']) && $info['errcode'] !== 0) { $this->apiError('登录失败', 0, $info); } $workerVendor = $this->getWorkerVendorService()->getVendorByOpenid($info['openid']); //创建 if (empty($workerVendor)) { try { $this->getWorkerVendorService()->createWechatMpVendor($info['openid']); } catch (\Exception $e) { $this->apiError('登录失败', $e, $info); } $workerVendor = $this->getWorkerVendorService()->getVendorByOpenid($info['openid']); } return $workerVendor->toArray(); } /** * 获取小程序 App * @return Application */ private function getMiniProgramApp(): Application { $config = [ 'app_id' => config('mini_program.app_id'), 'secret' => config('mini_program.secret'), ]; return Factory::miniProgram($config); } /** * 解密微信手机号 * @param string $code * @return mixed */ public function getPhoneNumber(string $code) { //getPhoneNumber 方法通过魔术方法 __call 获取 $phoneInfo = $this->getMiniProgramApp()->getPhoneNumber($code); if (empty($phoneInfo)) { $this->apiError('获取手机号失败', 0, $phoneInfo); } if ($phoneInfo['errcode'] !== 0) { $this->apiError('获取手机号失败', 0, $phoneInfo); } return $phoneInfo['phone_info']['phoneNumber']; } /** * 通过手机号查询师傅信息 * @param string $phone */ private function getByTel(string $phone) { return $this->getWorkerModel()->where('tel', $phone)->find(); } /** * 尝试绑定手机号 * @param $worker * @return true */ private function tryBindPhoneNumber($worker) { if (empty($worker)) { $this->apiError('绑定失败,该手机号未注册'); } if ($worker->status === 0) { $this->apiError('绑定失败,您的账号不可用'); } $workerVendor = $this->getWorkerVendorService()->getByWorkerIdAndPlatform($worker->id, 'WechatMp'); if ($workerVendor) { $this->apiError('绑定失败,当前手机号已被其他微信绑定'); } return true; } }