PFinal\Wechat\Support\Curl::execute PHP Method

execute() public static method

public static execute ( $url, string $method, null $postData = null, array $options = [], &$errors = [] ) : mixed
$url
$method string 'post' or 'get'
$postData null 类似'para1=val1¶2=val2&...', 也可以使用一个以字段名为键值,字段数据为值的数组。 如果value是一个数组,Content-Type头将会被设置成multipart/form-data 从 PHP 5.2.0 开始,使用 @ 前缀传递文件时,value 必须是个数组。 从 PHP 5.5.0 开始, @ 前缀已被废弃,文件可通过 \CURLFile 发送。
$options array
return mixed
    public static function execute($url, $method, $postData = null, $options = array(), &$errors = array())
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 150);
        //设置cURL允许执行的最长秒数
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if (strtolower($method) === 'post') {
            curl_setopt($ch, CURLOPT_POST, true);
            if ($postData !== null) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            }
        }
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        if (!($output = curl_exec($ch))) {
            $errors = array('errno' => curl_errno($ch), 'error' => curl_error($ch)) + curl_getinfo($ch);
        }
        curl_close($ch);
        return $output;
    }

Usage Example

Beispiel #1
0
 /**
  * 请求微信平台服务器,并解析返回的json字符串为数组,失败抛异常
  * @param $url
  * @param $data
  * @return array
  * @throws \PFinal\Wechat\WechatException
  */
 protected static function request($url, $data = null, $jsonEncode = true)
 {
     $executeUrl = str_replace('ACCESS_TOKEN', self::getApi()->getAccessToken(), $url);
     if ($jsonEncode) {
         $data = Json::encode($data);
     }
     try {
         return Json::parseOrFail(Curl::execute($executeUrl, is_null($data) ? 'get' : 'post', $data));
     } catch (WechatException $ex) {
         //更新AccessToken再次请求
         if ($ex->getCode() == 40001) {
             $executeUrl = str_replace('ACCESS_TOKEN', self::getApi()->getAccessToken(false), $url);
             return Json::parseOrFail(Curl::execute($executeUrl, is_null($data) ? 'get' : 'post', $data));
         }
         throw $ex;
     }
 }