在浏览器中粘贴url返回json,curl返回400错误

时间:2016-10-25 11:56:49

标签: php json curl

我正在为客户创建忠诚度折扣,他们有api会返回带有折扣数据的JSON。

现在我知道我需要如何生成api链接,当我在错误日志中输出它,然后将其粘贴到浏览器或邮递员时我得到了JSON就好了。但是当我尝试使用curl获取JSON时,我得到400错误

  

状态400:请求身份验证失败

卷曲部分看起来像这样:

$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $api_url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
$json = json_decode( curl_exec( $ch ), true );

error_log(print_r($api_url, true));
error_log(print_r($json, true));

if ( curl_errno( $ch ) ) {
    wp_die( curl_error( $ch ) );
}

$httpcode = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
curl_close( $ch );

if ( $httpcode >= 200 && $httpcode < 300) {
    wp_die( $json );
} else {
    wp_die( 'httpcode: ' . $httpcode . ' ' . __( 'Probably entered the wrong data on option menu, or REST API not responsive' ) );
}

当我查看错误日志时,我可以看到将其粘贴到邮递员或浏览器时有效的网址。

现在,邮递员设置为GET,当我尝试将其切换为POST时,我得到了同样的错误。邮递员返回标题

CONTENT-LENGTH → 238

我尝试过设置

curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'GET');

在确定curl_exec之前,但我仍然遇到同样的错误。

任何方式可以看到这里可能出现的问题?

哦,我正在使用ajax生成请求。所以用户输入他们的ID,并将其提交给ajax然后我应该检查并返回json。

编辑:

我已在错误日志中输出标题

[25-Oct-2016 12:07:53 UTC] Array
(
    [url] => this is the url
    [content_type] => 
    [http_code] => 400
    [header_size] => 48
    [request_size] => 248
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 0.564651
    [namelookup_time] => 0.510374
    [connect_time] => 0.520541
    [pretransfer_time] => 0.52061
    [size_upload] => 0
    [size_download] => 41
    [speed_download] => 72
    [speed_upload] => 0
    [download_content_length] => 41
    [upload_content_length] => -1
    [starttransfer_time] => 0.564589
    [redirect_time] => 0
    [redirect_url] => 
    [primary_ip] => 213.191.137.78
    [certinfo] => Array
        (
        )

    [primary_port] => 80
    [local_ip] => xxx.xxx.xxx.xxx
    [local_port] => 60192
    [request_header] => GET /rest/api/v1/webshop/loycard/customer/the endpoint goes here HTTP/1.1
Host: the client host
Accept: */*


)

当我查看粘贴链接的检查员时,我有

GET /rest/api/v1/webshop/loycard/customer/the endpoint goes here HTTP/1.1
Host: the client host
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.59 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, sdch
Accept-Language: hr-HR,hr;q=0.8,en-US;q=0.6,en;q=0.4

0 个答案:

没有答案