问题描述:

I am creating a loyalty discount for a client, and they have api that will return JSON with discount data.

Now I know how I need to generate api link, and when I output it in my error log, and then paste it to browser or postman I get the JSON just fine. But when I try to fetch the JSON using curl I get 400 error

Status 400: Request authentication failed

The curl part looks like this:

$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' ) );

}

When I look at error log I can see the url that works when I paste it to postman or browser.

Now, the postman is set to GET, and when I tried to switch it to POST I got the same error. Postman returns headers

CONTENT-LENGTH → 238

I tried setting

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

before geting curl_exec, but I still get the same error.

Any way to see what could be wrong here?

Oh and I am generating the request using ajax. So user inputs their ID, and submit it to ajax and then I should check and return the json.

EDIT:

I've outputted the headers in my error log

[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: */*

)

And when I look in the inspector of pasted link I have

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

相关阅读:
Top