Пример #1
0
 /**
  * 下载一个素材
  * @param string $mediaId 媒体id,通过上传获得
  * @param string $toFile 可选,下载到文件的绝对路径,不填则默认路径为RES_ROOT/$mediaId
  * @return integer 下载到的文件大小(失败时返回false)
  * @throws ApiException
  */
 public function download($mediaId, $toFile = null)
 {
     //使用http协议
     // $this->url = str_replace('https', 'http', $this->url);
     $url = $this->url . '/get?access_token=' . $this->accessToken . '&media_id=' . $mediaId;
     $httpClient = new HttpClient($url);
     $httpClient->get(30);
     if ($httpClient->getStatus() != 200 || $httpClient->getResponse() == '') {
         throw ApiException::throws(ApiException::HTTP_ERROR_CODE, 'status code: ' . $httpClient->getStatus());
         return false;
     }
     $header = $httpClient->getHeader();
     $contentType = $header['Content-Type'][0];
     //Content-Type为text/时表示带有errcode错误信息
     if (!isset($header['Content-Type']) || stripos($contentType, 'text') !== false) {
         $result = json_decode($httpClient->getResponse(), true);
         if (!$result) {
             throw ApiException::throws(ApiException::JSON_DECODE_ERROR_CODE, 'response: ' . $httpClient->getResponse());
         }
         if (isset($result['errcode']) && $result['errcode'] != 0) {
             throw new ApiException($result['errmsg'], $result['errcode']);
             //非0状态码
         }
         return false;
     }
     //写入文件
     if (empty($toFile)) {
         if (!is_dir(RES_ROOT . '/media')) {
             mkdir(RES_ROOT . '/media');
             chmod(RES_ROOT . '/media', 0775);
         }
         $toFile = RES_ROOT . "/media/{$mediaId}" . $this->parseExtension($contentType);
     }
     file_put_contents($toFile, $httpClient->getResponse());
     return filesize($toFile);
 }
Пример #2
0
 /**
  * 测试个性化菜单
  * @param string $userId 用户openId或微信号
  * @param boolean $assocArray 可选,false则直接返回API的结果(默认true返回解析后的数组)
  * @return string/array 查询后的结果
  */
 public function test($userId, $assocArray = true)
 {
     $url = $this->url . '/trymatch?access_token=' . $this->accessToken;
     $httpClient = new HttpClient($url);
     $httpClient->setBody(json_encode(array('user_id' => $userId)));
     $httpClient->post();
     if ($httpClient->getStatus() != 200 || $httpClient->getResponse() == '') {
         throw ApiException::throws(ApiException::HTTP_ERROR_CODE, 'status code: ' . $httpClient->getStatus());
         return false;
     }
     if (!$assocArray) {
         //直接返回API接口的结果
         return $httpClient->getResponse();
     }
     $result = $httpClient->jsonToArray();
     return $result;
 }