appId = $tool->get('smtp'); $this->apiKey = $tool->get('smtp_account'); $this->templateId = $tool->get('smtp_password'); $this->initClient(); } public function sendCode($mobile, $code, $activeMinute = 10) { $data = [ 'appid' => $this->appId, 'apikey' => $this->apiKey, 'templateid' => $this->templateId, 'phone' => $mobile, 'param' => $code . ',' . $activeMinute, ]; $result = $this->post('/sms/send_sms', $this->parseData($data)); $this->parseResult($result); } public function send($mobile, $content) { throw new BusinessException('该短信服务不可用'); } public function sendBatch(array $mobiles, $content) { throw new BusinessException('该短信服务不可用'); } protected function parseData($data) { return http_build_query($data); } protected function parseResult($result) { $result = json_decode($result, true); if (!$result) { throw new BusinessException('系统异常'); } if ($result['code'] != 200) { throw new BusinessException($result['msg']); } } protected function post($uri, $data) { $response = $this->client->post($uri, [ 'verify' => false, 'body' => $data ]); return (string)$response->getBody(); } protected function initClient() { $this->client = new Client([ 'base_uri' => $this->baseUrl, 'handler' => HandlerStack::create(new CoroutineHandler()), 'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded', ], 'swoole' => [ 'timeout' => 10, 'socket_buffer_size' => 1024 * 1024 * 2, ], ]); } }