Unable to make CURL post request using PHP - php

I read some Q&As but still struggling with this one. I need to post a specific array to an API and get another array as an answer.
UPDATE
I used :
<?php
echo 'Testing cURL<br>';
// Get cURL resource
$curl = curl_init();
$data=array(array("UserId"=>"xxxx-10100","Password"=>"pass"));
$sendpostdata = json_encode( array( "postdata"=> $data ) );
echo $sendpostdata;
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://cloud.servicebridge.com/api/v1/Login',
CURLOPT_HTTPHEADER => array('Accept: application/json','Content-Type: application/json'),
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $sendpostdata
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
echo $resp;
// Close request to clear up some resources
curl_close($curl);
?>
This results in
Testing cURL
{"postdata":[{"UserId":"xxxxx-10100","Password":"pass"}]}
{ "Data": null, "Success": false, "Error": { "Message": "Invalid UserId: ", "Value": "InvalidUserId", "Code": 9001 } }
No console logs, no other messages or clues
I am trying to implement this API https://cloud.servicebridge.com/developer/index#/
to Worpdress.
The API requires a
{
"UserId": "string",
"Password": "string"
}
Can you help me out? What am I doing wrong
Really appreciate this,
Giannis

I have checked the given API and it's REQUEST Parameters to access them and I think your initial data (username and password) is not going correctly. Please use this code:-
<?php
error_reporting(E_ALL); // check all type of errors
ini_set('display_errors',1); // display those errors
// Get cURL resource
$curl = curl_init();
$sendpostdata = json_encode(array("UserId"=>"xxxx-10100","Password"=>"pass"));
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://cloud.servicebridge.com/api/v1/Login',
CURLOPT_HTTPHEADER => array('Accept: application/json','Content-Type: application/json'),
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $sendpostdata
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
echo $resp;
// Close request to clear up some resources
curl_close($curl);
?>
Note:- change UserId & Passwordvalues to your real values.Thanks

This might help you in generating proper json. Hope this will work.
use this
$data=array(array("UserId"=>"xxxxx-10100","Password"=>"pass"));
instead of
$data ='[{"UserId":"xxxxx-10100","Password": "pass"}]';

Related

First time with PHP and an API - can you help me with a basic example?

I'm very new to PHP and API, and my company was asked for a job of incorporating API calls on a PHP website.
This is the info about the API that the client gave to us:
API Manual
General Notes:
API URL: https://www.somedomain.com/api/
apiKey: 123qwe456rty678yui
HTTP Verb: POST
Content-Type: application/x-www-form-urlencoded
1. {EMPLOYEES category}
POST /en/1001/cat/10
POST /en/1001/cat/10/page/[999]
Observations:
• the list returns 20 records
• to get the reamining records: /en/1001/cat/10/page/2; /en/1001/cat/10/page/3; ...
• the information is returned in JSON format
• all the requests should be made by the POST method and the api key should be sent on the request body
Input variables:
• apiKey => App key
Return parameters:
retCode = “error”
retCode = “ok”
(...)
2. {NEWS category}
POST /en/2002/cat/20
POST /en/2002/cat/20/page/[999]
Observations:
• the list returns 20 records
• to get the reamining records: /en/2002/cat/20/page/2; /en/2002/cat/20/page/3; ...
• the information is returned in JSON format
Input variables:
• apiKey => App key
Return parameters:
retCode = “error”
retCode = “ok”
(...)
And I've made a simple PHP script but I'm getting an empty return value:
<?php
//API URL: https://www.somedomain.com/api/
//This is to test the Employees category - /en/1001/cat/10
$curl = curl_init();
$apiKey = urlencode("123qwe456rty678yui");
//$apiKey = "123qwe456rty678yui";
//it doesn't matter if this variable is urlencoded or not, as the result is always empty...
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.somedomain.com/api/en/1001/cat/10",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_SSL_VERIFYPEER => "false",
CURLOPT_POSTFIELDS => "apiKey=$apiKey",
CURLOPT_HTTPHEADER => array(
"content-type: application/x-www-form-urlencoded"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo "Response: " . $response;
}
?>
Like I said, I'm very new to this, PHP and API's, and the client isn't very helpful.
Based on the Manual API I have, what I'm doing wrong? $response is always empty, it gives no error even if I enter a wrong API Key, and I don't even know if I'm calling this the correct way...
Thanks in advance!
Here is a function that should work from the manual: https://www.php.net/manual/en/function.curl-setopt-array.php#89850
<?php
function get_web_page($url, $curl_data )
{
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
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
CURLOPT_POST => 1, // i am sending post data
CURLOPT_POSTFIELDS => $curl_data, // this are my post vars
CURLOPT_SSL_VERIFYHOST => 0, // don't verify ssl
CURLOPT_SSL_VERIFYPEER => false, //
CURLOPT_VERBOSE => 1 //
);
$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_data = "var1=60&var2=test";
$url = "https://www.example.com";
$response = get_web_page($url,$curl_data);
print '<pre>';
print_r($response);
?>
You can also try the file_get_contents function to get this JSON data.
Something like this could do the job:
// API URL
$apiUrl = 'https://www.somedomain.com/api/en/2002/cat/20';
// Request options
$opts = [
"http" => [
'method' => 'POST',
'header' => [
'Content-Type: application/x-www-form-urlencoded',
'apiKey: 123qwe456rty678yui'
]
]
];
// Request context
$context = stream_context_create($opts);
// Get JSON
$json = file_get_contents($apiUrl, false, $context);
Try and see if you can adapt it.

Trouble with API based on JSON-RPC 2.0

I am trying to connect to an API which is based on JSON-RPC 2.0. As i am new to this im not sure if im coding this correctly because all I am recieving is an error.
Can anyone give me a brief explanation on how to connect to API in PHP?
<?php
header('Content-Type: application/json');
//check if you have curl loaded
if(!function_exists("curl_init")) die("cURL extension is not installed");
$url = 'xxxxxxxxx';
$data = array(
"operator_id" => "xxxx",
"login" => "xxxx",
"password" => "xxxx",
);
$curl_options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => 0,
CURLOPT_NOBODY => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_ENCODING => 'gzip,deflate',
CURLINFO_HEADER_OUT => true,
);
$ch = curl_init();
curl_setopt_array($ch, $curl_options);
$output = curl_exec($ch);
curl_close($ch);
$arr = json_decode($output,true);
echo ($output);
?>
The response i am recieving is this: {"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid request"},"id":null}
The response i should be recieving if successful login is: {"jsonrpc":"2.0","result":true,"error":null,"id":1,"ts":1368533487}
You're not sending a JSON-RPC request at all.
The request must be a JSON body, so you must json_encode the data before passing it to CURLOPT_POSTFIELDS.
The posted json must have the keys method, params, id, and jsonrpc (the last should be set to "2.0"). Your data would go into params. The id can be set to whatever, but without it you shouldn't get a response at all.
It is a quite simple format. See the specification at http://www.jsonrpc.org/specification

Twitter API using curl in PHP "direct_messages/new.json"

I am using the oauth library to use twitter API for sending the Direct Message to user using curl,but getting the "{"errors":[{"code":215,"message":"Bad Authentication data."}]}".
If i use terminal for curl then it works fine, but getting error while sending through PHP.
<pre>
<?php
error_reporting(1);
require("twitterOauth/autoload.php");
use Abraham\TwitterOAuth\TwitterOAuth;
$text = "Hello, How Are U?";
$headers = array(
'Authorization: OAuth oauth_consumer_key="OAuth oauth_consumer_key",
oauth_nonce="oauth_nonce",
oauth_signature="oauth_signature",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1439978004",
oauth_token="oauth_token",
oauth_version="1.0"'
);
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://api.twitter.com/1.1/direct_messages/new.json',
CURLOPT_POST => 1,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_POSTFIELDS => array(
'text' => urlencode($text),
'screen_name' => 'screen_name'
),$headers
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
print_r('Curl error: ' . curl_error($resp));
echo '<pre>'; print_r($resp); die;
// Close request to clear up some resources
curl_close($curl);
?>
</pre>

Error to call Tinypass response in Restapi

I am new in Tinypass api integration.
I try to integrate Tinypass API using PHP. Code below:
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://sandbox.tinypass.com/r2/access?rid=portfolio_id&user_ref=badashah26',
// CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_HTTPHEADER => array(
'AID: xxxxxxxx', // PUT your AID
'signature: xxxxxxxxxxxxxxxxxx', // PUT your signature
'sandbox: true'
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
print_r($resp); exit();
Response get but error display.
"error":{"message":"Access denied: invalid AID or signature","code":401}}
Any one can find solutions.
Thanks
Our REST API documentation has been updated to provide a few steps on how to generate your own API header. Check out the documentation at http://developer.tinypass.com/main/restapi.
Best,
Tinypass Support
Something like this..? (untested)
$aid = 'YOUR AID';
$action = '/r2/access?rid='.$rid.'&user_ref='.$userref;
$request = 'GET '.$action;
$url = 'http://sandbox.tinypass.com'.$action;
$signature = hash_hmac('sha256',$request,$aid);
$auth = $aid.':'.$signature;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => array('Authorization: '.$auth);
));
$resp = curl_exec($curl);
curl_close($curl);
print_r($resp); exit();

custom http request header in php

I have a rest api made using philsturgeon/codeigniter-restserver.I have set the authentication
api key for the rest api.So that all request will be authenticated usingthe api key.
The request parameter for apikey is X-API-KEY and the key should be sent as request parameter in the header.
But I cant get itworking using curl.But in rest console and post man,I can properly set the request parameter in the header.But i cant do it with curl.
<?php
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'www.exampleapi.come',
CURLOPT_USERPWD => 'martinbean:4eefab4111b2a',
CURLOPT_HTTPHEADER => 'X-API-KEY:123456789'
));
$response = curl_exec($ch) ;
echo $response ;
?>
I have tried this,but itsnot working,its showing invalid api key
How to do this part using curl?
The php curl wrapper documentation says that you need to pass an array to this option.
See : http://php.net/manual/en/function.curl-setopt.php
So this may work :
<?php
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'www.exampleapi.come',
CURLOPT_USERPWD => 'martinbean:4eefab4111b2a',
CURLOPT_HTTPHEADER => array('X-API-KEY:123456789')
));
$response = curl_exec($ch) ;
echo $response ;
?>

Categories