config = config("easy_we_chat"); try { // 获取WeChat客户端 $this->app = new Application($this->config); // 替换缓存 $this->app->setCache(ApplicationContext::getContainer()->get(CacheInterface::class)); $this->client = $this->app->getClient(); } catch (InvalidArgumentException $e) { throw new BusinessException('实例化EasyWeChat类失败:' . $e->getMessage(), HttpEnumCode::SERVER_ERROR); } } /** * 根据 jsCode 获取用户 session 信息 * @param string $code code * @return array * @throws ClientExceptionInterface * @throws DecodingExceptionInterface * @throws RedirectionExceptionInterface * @throws ServerExceptionInterface * @throws TransportExceptionInterface * @throws \Exception */ public function codeToSession(string $code): array { try { $utils = $this->app->getUtils(); return $utils->codeToSession($code); } catch (\Exception $e) { throw new BusinessException($e->getMessage(), HttpEnumCode::SERVER_ERROR); } } /** * 解密微信会话信息 * @param string $sessionKey 会话密钥 * @param string $iv 加密算法的初始向量 * @param string $encryptedData 用户信息的加密数据 * @return array */ public function decryptSession(string $sessionKey, string $iv, string $encryptedData): array { try { $utils = $this->app->getUtils(); return $utils->decryptSession($sessionKey, $iv, $encryptedData); } catch (\Exception $e) { throw new BusinessException($e->getMessage(), HttpEnumCode::SERVER_ERROR); } } /** * 获取 access_token * @return string */ public function getAccessToken(): string { try { $accessToken = $this->app->getAccessToken(); return $accessToken->getToken(); } catch (\Exception $e) { throw new BusinessException($e->getMessage(), HttpEnumCode::SERVER_ERROR); } } /** * 获取手机号 * @param string $code * @return array * @throws ClientExceptionInterface * @throws DecodingExceptionInterface * @throws RedirectionExceptionInterface * @throws ServerExceptionInterface * @throws TransportExceptionInterface|BadResponseException */ public function getPhone(string $code): array { $options = [ "code" => $code, ]; $response = $this->client->postJson('wxa/business/getuserphonenumber', $options); if ($response->isFailed()) { // 出错了,处理异常 $result = $response->toArray(); if(empty($result)){ throw new BusinessException( $response->toJson(false),HttpEnumCode::GET_WX_ERROR); } if (isset($result['errcode'])){ if ($result['errcode'] == "40029"){ // code过期 throw new BusinessException( HttpEnumCode::getMessage(HttpEnumCode::GET_WX_ERROR),HttpEnumCode::WX_CODE_ERROR); } } throw new BusinessException( $response->toJson(false),HttpEnumCode::GET_WX_ERROR); } return $response->toArray(false); } }