I am trying to make a php curl request to my laravel api
Here’s the curl function
function CallAPI($method, $url, $data = false) { $curl = curl_init(); switch ($method) { case "POST": curl_setopt($curl, CURLOPT_POST, 1); if ($data) curl_setopt($curl, CURLOPT_POSTFIELDS, $data); break; case "PUT": curl_setopt($curl, CURLOPT_PUT, 1); break; default: if ($data) $url = sprintf("%s?%s", $url, http_build_query($data)); } curl_setopt($curl, CURLOPT_HEADER, array('Accept:application/json', 'X-Requested-With:XMLHttpRequest' ) ); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); print curl_error($curl); $result = curl_exec($curl); curl_close($curl); return $result; }
Here’s where I call it :
require_once ADJEMINPAY_PLUGIN_DIR.'includes/class-adjeminpay-functions.php'; $url = "https://api.adjeminpay.net/v1/auth/getToken/"; $postData = array( 'firstName' => 'Lady', 'lastName' => 'Gaga', 'submit' => 'ok' ); $result = CallAPI("POST", $url, $postData); var_dump($result);
Here’s the result :
string(454) "HTTP/2 301 date: Fri, 04 Dec 2020 12:12:03 GMT server: Apache location: https://api.adjeminpay.net/public/v1/auth/getToken content-length: 258 content-type: text/html; charset=iso-8859-1 Moved Permanently The document has moved here. "
Looks like laravel doesn’t get that it’s an api request and keeps changing the url to https://api.adjeminpay.net/ public/ v1/auth/getToken/ ; it also tries to redirect to https://api.adjeminpay.net/
Help kudasai TT
Advertisement
Answer
Sooo, turns out the syntax/version of curl I was using was defective/uncomplete.
Went over to PostMan and executed the same request then copipasted the php -curl code which looks like this :
<?php $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'yourUrl', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS =>'{ "apikey": "qsmdlfjqs", "application_id": "qsdlfqsmlj", "grant-type": "qmdsfqsdf" }', CURLOPT_HTTPHEADER => array( 'Accept: application/json', 'Content-Type: application/json', ': ', ), )); $response = curl_exec($curl); curl_close($curl); echo $response;
And it works fine now. Arigathanks (^^)/
By the way How to generate PHP -curl code from POSTMAN.