/** * Constructor. * * @param string $appId * @param string $secret * @param Cache $cache * @param Http $http */ public function __construct($appId, $secret, Cache $cache, Http $http) { $this->appId = $appId; $this->secret = $secret; $this->cache = $cache; $this->http = $http->setExpectedException(JsHttpException::class); }
/** * Constructor. * * @param string $appId * @param string $secret * @param Cache $cache * @param Http $http */ public function __construct($appId, $secret, Cache $cache, Http $http) { $this->appId = $appId; $this->secret = $secret; $this->cache = $cache; $this->http = $http->setExpectedException('EasyWeChat\\Js\\JsHttpException'); }
/** * 上传媒体文件. * * @param string $path * * @return string * * @throws InvalidArgumentException */ public function upload($path) { if (!file_exists($path) || !is_readable($path)) { throw new InvalidArgumentException("文件不存在或不可读 '{$path}'"); } $options = ['files' => ['media' => $path]]; $contents = $this->http->post(self::API_UPLOAD, [], $options); return $contents['url']; }
/** * 获取颜色列表. * * @return array */ public function lists() { $key = 'overtrue.wechat.colors'; return $this->cache->get($key, function ($key) { $result = $this->http->get(self::API_LIST); $this->cache->set($key, $result['colors'], 86400); // 1 day return $result['colors']; }); }
/** * Get token from WeChat API. * * @return string */ public function getToken() { $cacheKey = $this->prefix . $this->appId; return $this->cache->get($cacheKey, function ($cacheKey) { $params = ['appid' => $this->appId, 'secret' => $this->secret, 'grant_type' => 'client_credential']; $token = $this->http->get(self::API_TOKEN_GET, $params); $this->cache->set($cacheKey, $token['access_token'], $token['expires_in'] - 100); return $token['access_token']; }); }
/** * Test parseJSON(). */ public function testParseJSON() { $http = new Http(); $http->setClient($this->getGuzzleWithResponse('{"foo:"bar"}')); $this->assertEquals(null, $http->parseJSON($http->request('http://overtrue.me', 'GET'))); $http->setClient($this->getGuzzleWithResponse('{"foo":"bar"}')); $this->assertEquals(['foo' => 'bar'], $http->parseJSON($http->request('http://overtrue.me', 'GET'))); $http = new Http(); $http->setClient($this->getGuzzleWithResponse()); $this->assertEquals(null, $http->parseJSON($http->request('http://overtrue.me', 'GET'))); }
/** * Test parseJSON(). */ public function testParseJSON() { $http = new Http(); $http->setClient($this->getGuzzleWithResponse('{"foo:"bar"}')); try { $http->parseJSON($http->request('http://overtrue.me', 'GET')); $this->assertFail('Invalid json body check fail.'); } catch (\Exception $e) { $this->assertInstanceOf("\\EasyWeChat\\Core\\Exceptions\\HttpException", $e); } $http->setClient($this->getGuzzleWithResponse('{"foo":"bar"}')); $this->assertEquals(['foo' => 'bar'], $http->parseJSON($http->request('http://overtrue.me', 'GET'))); $http = new Http(); $http->setClient($this->getGuzzleWithResponse('')); $this->assertEquals(null, $http->parseJSON($http->request('http://overtrue.me', 'GET'))); }
/** * Upload material. * * @param string $type * @param string $path * @param array $form * * @return string * * @throws InvalidArgumentException */ protected function uploadMedia($type, $path, array $form = []) { if (!file_exists($path) || !is_readable($path)) { throw new InvalidArgumentException("File does not exist, or the file is unreadable: '{$path}'"); } $form = array_merge($form, ['type' => $type]); return $this->http->upload($this->getApi($type), ['media' => $path], $form); }
/** * Set request access_token query. */ protected function registerHttpMiddlewares() { // log $this->http->addMiddleware($this->logMiddleware()); // retry $this->http->addMiddleware($this->retryMiddleware()); // access token $this->http->addMiddleware($this->accessTokenMiddleware()); }
/** * Get jsticket. * * @return string */ public function ticket() { $key = self::TICKET_CACHE_PREFIX . $this->appId; return $this->cache->get($key, function ($key) { $result = $this->http->get(self::API_TICKET); $this->cache->set($key, $result['ticket'], $result['expires_in'] - 500); return $result['ticket']; }); }
/** * Send the message. * * @return bool * * @throws RuntimeException */ public function send() { if (empty($this->message)) { throw new RuntimeException('No message to send.'); } $content = $this->transformer->transform($this->message); $message = ['touser' => $this->to, 'msgtype' => $this->message->type, $this->message->type => $content, 'customservice' => ['kf_account' => $this->account]]; return $this->http->json(self::API_MESSAGE_SEND, $message); }
/** * Create a QRCode. * * @param string $actionName * @param array $actionInfo * @param bool $temporary * @param int $expireSeconds * * @return Collection */ protected function create($actionName, $actionInfo, $temporary = true, $expireSeconds = null) { $expireSeconds !== null || ($expireSeconds = 7 * self::DAY); $params = ['action_name' => $actionName, 'action_info' => ['scene' => $actionInfo]]; if ($temporary) { $params['expire_seconds'] = min($expireSeconds, 7 * self::DAY); } return new Collection($this->http->json(self::API_CREATE, $params)); }
/** * Send the message. * * @return bool */ public function send() { if (empty($this->message)) { throw new RuntimeException('No message to send.'); } $this->message->to = $this->to; $this->message->account = $this->account; $message = $this->transformer->transform($this->message); return $this->http->jsonPost(self::API_MESSAGE_SEND, $message); }
/** * Upload temporary material. * * @param string $type * @param string $path * * @return string * * @throws InvalidArgumentException */ public function upload($type, $path) { if (!file_exists($path) || !is_readable($path)) { throw new InvalidArgumentException("File does not exist, or the file is unreadable: '{$path}'"); } if (!in_array($type, $this->allowTypes, true)) { throw new InvalidArgumentException("Unsupported media type: '{$type}'"); } return $this->http->upload(self::API_UPLOAD, ['media' => $path]); }
/** * 发送模板消息. * * @param string $to * @param string $templateId * @param array $data * @param string $url * @param string $color * * @return int * * @throws InvalidArgumentException */ public function send($to = null, $templateId = null, array $data = [], $url = null, $color = '#FF0000') { $params = ['touser' => $to, 'template_id' => $templateId, 'url' => $url, 'topcolor' => $color, 'data' => $data]; $required = ['touser', 'template_id']; foreach ($params as $key => $value) { if (in_array($key, $required) && empty($value) && empty($this->message[$key])) { throw new InvalidArgumentException("消息属性 '{$key}' 不能为空!"); } $params[$key] = empty($value) ? $this->message[$key] : $value; } $params['data'] = $this->formatData($params['data']); $result = $this->http->jsonPost(self::API_SEND_NOTICE, $params); return $result['msgid']; }
/** * Application constructor. * * @param array $config */ public function __construct($config) { parent::__construct(); $this['config'] = function () use($config) { return new Config($config); }; if ($this['config']['debug']) { error_reporting(E_ALL); } $this->registerProviders(); $this->registerBase(); $this->initializeLogger(); Http::setDefaultOptions($this['config']->get('guzzle', ['timeout' => 5.0])); foreach (['app_id', 'secret'] as $key) { !isset($config[$key]) || ($config[$key] = '***' . substr($config[$key], -5)); } Log::debug('Current config:', $config); }
/** * 获取access token. * * @param string $code * * @return string */ public function getAccessPermission($code) { $params = ['appid' => $this->appId, 'secret' => $this->appSecret, 'code' => $code, 'grant_type' => 'authorization_code']; return $this->lastPermission = $this->http->get(self::API_TOKEN_GET, $params); }
/** * Delete a store. * * @param int $storeId * * @return bool */ public function delete($storeId) { $params = ['poi_id' => $storeId]; return $this->http->jsonPost(self::API_DELETE, $params); }
/** * Set staff avatar. * * @param string $email * @param string $path * * @return bool */ public function avatar($email, $path) { $options = ['files' => ['media' => $path]]; $url = self::API_AVATAR_UPLOAD . "?kf_account={$email}"; return $this->http->post($url, [], $options); }
/** * Checkin. * * <pre> * $data: * { * "code": "198374613512", * "card_id":"p1Pj9jr90_SQRaVqYI239Ka1erkI", * "passenger_name": "乘客姓名", * "class": "舱等", * "seat": "座位号", * "etkt_bnr": "电子客票号", "qrcode_data": "二维码数据", "is_cancel ": false * } * </pre> * * @param string $cardId * @param array $data * * @return bool */ public function checkin($cardId, array $data) { $params = array_merge(['card_id' => $cardId], $data); return $this->http->json(self::API_BOARDING_PASS_CHECKIN, $params); }
/** * Get the semantic content of giving string. * * @param string $keyword * @param array|string $categories * @param array $other * * @return Collection */ public function query($keyword, $categories, array $other = []) { $params = ['query' => $keyword, 'category' => implode(',', (array) $categories), 'appid' => $this->appId]; return new Collection($this->http->jsonPost(self::API_CREATE, array_merge($params, $other))); }
/** * 查询数据. * * @param string $api * @param string $from * @param string $to * * @return array */ protected function query($api, $from, $to) { $params = ['begin_date' => $from, 'end_date' => $to]; $result = $this->http->json($api, $params); return $result['list']; }
/** * Batch move users to a group. * * @param array $openIds * @param int $groupId * * @return bool */ public function moveUsers(array $openIds, $groupId) { $params = ['openid_list' => $openIds, 'to_groupid' => $groupId]; $this->http->jsonPost(self::API_MEMBER_BATCH_UPDATE, $params); return true; }
/** * Get current menus setting. * * @return array */ public function current() { return $this->http->get(self::API_QUERY); }
/** * Get user's group id. * * @param string $openId * * @return int */ public function getGroup($openId) { $params = ['openid' => $openId]; $response = $this->http->jsonPost(self::API_GROUP, $params); return $response['groupid']; }
/** * Shorten the url. * * @param string $url * * @return string */ public function shorten($url) { $params = ['action' => 'long2short', 'long_url' => $url]; $response = $this->http->json(self::API_SHORTEN_URL, $params); return $response['short_url']; }
/** * Get User by access token. * * @param string $openId * @param string $accessToken * * @return Collection */ public function getUserByAccessToken($openId, $accessToken) { $queries = $this->getUserFields($openId, $accessToken); return $this->http->get(self::USER_URL, $queries); }
/** * 获取永久素材列表. * * example: * * { * "total_count": TOTAL_COUNT, * "item_count": ITEM_COUNT, * "item": [{ * "media_id": MEDIA_ID, * "name": NAME, * "update_time": UPDATE_TIME * }, * //可能会有多个素材 * ] * } * * @param string $type * @param int $offset * @param int $count * * @return array */ public function lists($type, $offset = 0, $count = 20) { $params = ['type' => $type, 'offset' => intval($offset), 'count' => min(20, $count)]; return $this->http->jsonPost(self::API_FOREVER_LIST, $params); }
public function json($url, $options = [], $encodeOption = JSON_UNESCAPED_UNICODE) { $url .= (stripos($url, '?') ? '&' : '?') . 'component_access_token=' . $this->component_access_token; return parent::parseJSON(parent::json($url, $options, $encodeOption)); }
/** * Set staff avatar. * * @param string $email * @param string $path * * @return bool */ public function avatar($email, $path) { return $this->http->upload(self::API_AVATAR_UPLOAD, ['media' => $path], ['kf_account' => $email]); }