API call with Curl - php

I need to call this command using curl.
http -a $CLIENT_ID:$CLIENT_SECRET --form POST https://api-sandbox.com/auth/token grant_type=client_credentials scope=access_token_only
I have tried following, but not getting through
$URL = "https://api-sandbox.com/auth/token";
$data = array(
'grant_type' => "client_credentials",
'scope' => "access_token_only"
);
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_APPEND, "$CLIENT_ID:$CLIENT_SECRET");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$data=curl_exec($ch);
curl_close($ch);
I am getting following error
{"error":"invalid_request","error_description":"Missing form parameter: grant_type"}
How can I do it?
Thx
----------------Additional Information -----------------
oAuth2.0 is being used for authentication

This code should work for you
<?php
$URL = "https://api-sandbox.com/auth/token";
$data = [
'grant_type' => "client_credentials",
'scope' => "access_token_only",
];
$client_id = getenv('CLIENT_ID');
$client_secret = getenv('CLIENT_SECRET');
try {
$ch = curl_init();
// Check if initialization had gone wrong*
if ( $ch === false ) {
throw new RuntimeException( 'failed to initialize' );
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api-sandbox.com/auth/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials&scope=access_token_only");
curl_setopt($ch, CURLOPT_USERPWD, $client_id . ':' . $client_secret);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
$content = curl_exec( $ch );
curl_close( $ch );
if ( $content === false ) {
throw new RuntimeException( curl_error( $ch ), curl_errno( $ch ) );
}
/* Process $content here */
// Close curl handle
curl_close( $ch );
} catch ( RuntimeException $e ) {
trigger_error(
sprintf(
'Curl failed with error #%d: %s',
$e->getCode(),
$e->getMessage()
),
E_USER_ERROR
);
}

It worked in a following way:
$content = "grant_type=client_credentials&scope=access_token_only&client_id=".$client_id."&client_secret=".$client_secret;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api-sandbox.com/auth/token');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);

Related

How to post image using curl in php

I want to change profile image another application curl request i am trying below code can anyone help me please
$viewer = Engine_Api::_()->user()->getViewer();
$apiData = array(
"email" => $viewer->email,
"profile_image_file" => $_FILES['Filedata']['name'],
);
$apiHost = "https://tenant.thetenantsnet.co.uk/api/api/save_profile_image";
$response = $this->callRiseAPI2($apiData,$apiHost);
private function callRiseAPI2($apiData,$apiHost){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiHost);
curl_setopt($ch, CURLOPT_POST, count($apiData));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($apiData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$jsonData = curl_exec($ch);
if (false === $jsonData) {
throw new \Exception("Error: _makeOAuthCall() - cURL error: " . curl_error($ch));
}
curl_close($ch);
//return the API response
return json_decode($jsonData);
}
As Anoxy said, you need to put in the header the Content-Type :
$viewer = Engine_Api::_()->user()->getViewer();
$apiData = array(
"email" => $viewer->email,
"profile_image_file" => $_FILES['Filedata']['name'],
);
$apiHost = "https://tenant.thetenantsnet.co.uk/api/api/save_profile_image";
$response = $this->callRiseAPI2($apiData,$apiHost);
private function callRiseAPI2($apiData,$apiHost){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiHost);
curl_setopt($ch, CURLOPT_POST, count($apiData));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($apiData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-Type: multipart/form-data');
$jsonData = curl_exec($ch);
if (false === $jsonData) {
throw new \Exception("Error: _makeOAuthCall() - cURL error: " . curl_error($ch));
}
curl_close($ch);
//return the API response
return json_decode($jsonData);
}

Don't show logs with PHP command and cURL

I developed a script with PHP which I use with the console, with the command php index.php.
In this script, I use cURL to query a server.
The problem is my script shows logs on the console, and I just want the result of the echo.
Do you have an idea to hide these logs?
// GET TOKEN
// /////////////////////////////////////////////////////////////////////////////
$url = "some/url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$user:$pwd");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$data = curl_exec($ch);
$location = "";
preg_match_all('/^Location:(.*)$/mi', $data, $location);
$location = trim($location[1][0]);
$location = parse_url($location);
parse_str($location['query'], $attrs);
$token = $attrs['code'];
if( isset($token) ) {
// GET CONNEXION
// /////////////////////////////////////////////////////////////////////////
$url = "some/url";
$post_data = ['code' => $token, 'grant_type' => 'authorization_code'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$client_id:$client_secret");
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = json_decode(curl_exec($ch));
$connexion = isset($data->access_token) ? $data->access_token : $data->error_description;
// GET LOGIN
// /////////////////////////////////////////////////////////////////////////
$url = "some/url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
$data = json_decode($data);
// $login = json_encode(['public' => $data->api_keys[1]->public, 'secret' => $data->api_keys->secret]);
// REQUEST
// /////////////////////////////////////////////////////////////////////////
$url = $request . "?externalId=".$external_id."&externalSource=".$external_source;
date_default_timezone_set("Europe/Paris");
$nonce = generateRandomString();
file_put_contents('php://stderr', print_r("Set random nonce to " . $nonce . "\n", TRUE));
$created = date("Y-m-dTH:i:sP");
$created = date("Y-m-dTH:i:sP");
$username = $data->api->public;
$secret = $data->api->secret;
$pwd_digest = base64_encode(sha1($nonce.$created.$secret));
$auth_header = "X-WSSE: UsernameToken Username=\"$username\", PasswordDigest=\"$pwd_digest\", Nonce=\"$nonce\", Created=\"$created\"";
$header = array($auth_header, 'Accept: something', 'Accept-Language: en');
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$data = curl_exec($ch);
$data = json_decode($data);
echo $data->nbNqPoints;
} else {
echo "0";
}
Answer found at this address: managing curl output in php
I add this line for every cURL instance :
curl_setopt($ch, CURLOPT_VERBOSE, 0);

Make a wp_remote_post when not logged in

Hi i'm developing a plugin which adds a new field to the order (WooCommerce). The field needs to make an ajax request to a file in my plugin, that file then needs to make a cURL request to another website (or wp_remote_post). But i'm experiencing difficulties when making the request.
I can't get the ordinary cURL to work nor the wp_remote_post function.
Here's a snippet of the cURL in my file which the ajax requests to.
<?php
$shipping_place = array(
'country_code' => $country_code,
'postcode' => $postcode,
'street' => $street,
'number_of_droppoints' => $number_of_droppoints
);
$auth = array(
'Content-Type: application/json',
'Authorization: Basic '. base64_encode('user:password')
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $auth);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $shipping_place);
$result = curl_exec($ch);
if(curl_errno($ch)){
$msg = 'Curl error: ' . curl_error($ch);
} else {
$result = json_decode($result['body']);
if ( $result->status == 'error' ) {
echo $result;
}
pred($result);
echo $result->result;
}
curl_close ($ch);
?>
Solved: I had to localize the wp-admin script.
That would use the wp function like this
<?php wp_localize_script( $handle, $name, $data ); ?>
Reference here.

Issue in adcash api curl code

All,
I have written a curl to get the details from Adcash API. Output of this API is to get the token number after login.
Below code is working good but it is not getting the token as output. It is null. Any suggestions.
<?php
try{
Echo "Executing started";
$url = "https://www.adcash.com/console/login_proxy.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERPWD, "userid:password");
$output = curl_exec($ch);
$info = curl_getinfo($ch);
var_dump($info) ;
echo $output;
if (FALSE === $output)
throw new Exception(curl_error($ch), curl_errno($ch));
Echo "Executing Completed";
curl_close($ch);
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
?>
I have updated the code to get the subid report. please check and let me know what is the issue.
<?php
try{
Echo "Executing started";
$url = "https://www.adcash.com/console/login_proxy.php";
$ch = curl_init();
$logindata = array (
'login' => 'xxx',
'password' => 'xxx'
);
$logindata1 = http_build_query($logindata);
curl_setopt($ch, CURLOPT_POSTFIELDS, $logindata1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
$json_a=json_decode($output,true);
$token= $json_a["token"];
curl_close($ch);
$url = "https://www.adcash.com/console/login_proxy.php";
$ch = curl_init();
$logindata1 = http_build_query($logindata);
curl_setopt($ch, CURLOPT_POSTFIELDS, $logindata1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "token=". $token . "&call=get_publisher_detailed_statistics");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
var_dump($output);
curl_close($ch);
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
?>
I'm part of Adcash IT team. First of all, thanks for using our API. The problem in your code is that you're using HTTP authentication. Our API is using POST.
This part of your code:
curl_setopt($ch, CURLOPT_USERPWD, "userid:password");
Can be replaced by:
$logindata = array (
'login' => YOUR_LOGIN_HERE,
'password' => YOUR_PASSWORD_HERE
);
$logindata = http_build_query($logindata);
curl_setopt($c, CURLOPT_POSTFIELDS, $data);
curl_setopt($c, CURLOPT_URL, 'https://www.adcash.com/console/login_proxy.php');
Let me know if it works.

CURL Script - POST

I'm new to curl. Just I try to post the value using curl script but I'm getting empty response. Help me is there any mistake in my code? How do I post a value using curl
$params = array('name' => 'karthick', 'type' => 'data');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php?action=create');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_POST, true );
// curl_setopt($ch, CURLOPT_USERPWD,$authentication);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// curl_setopt($ch, CURLOPT_REFERER,'http://www.example.com.au');
curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result = curl_exec($ch);
curl_close($ch);
var_dump($result);
You can try this code
public function getDataThroughCurlPost($param)
{
$ch = curl_init("$url");
error_reporting(E_ALL);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, "$param");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_NOBODY, 0);
$response = curl_exec($ch);
$ch = curl_close("$url");
return $response;
}
Been using this for quite a few of my websites. Hope this helps.
$sPost .= "<Username>".$username."</Username>";
$sPost .= "<Password>".$password."</Password>";
$url = "YOUR_POST_URL";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$sPost);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$logindetails = curl_exec($ch);
curl_close($ch);
$xmlarray = xml2array($details);
echo "<pre>";
print_r($xmlarray);
echo "</pre>";
xml2array class found here: http://www.bin-co.com/php/scripts/xml2array/
// curl function starts
function get_web_page( $url )
{
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
return $header;
}
// curl function end
$cont = get_web_page("http://website.com/filename.php");
$handle = explode("<br>",$cont['content']);
print_r($handle);

Categories