custom http request header in php - 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 ;
?>

Related

Unable to make CURL post request using 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"}]';

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>

POST using cURL and x-www-form-urlencoded in PHP returning Access Denied

I have been able to use the Advanced Rest Client Extension for chrome to send POST queries to an specific HTTPS server and I get Status Code: 200 - OK with the same body fields as the ones I used in this code, but when I run the following code I get this response: 403 - Access Denied.
<?php
$postData = array(
'type' => 'credentials',
'id' => 'exampleid',
'secret_key' => 'gsdDe32dKa'
);
// Setup cURL
$ch = curl_init('https://www.mywebsite.com/oauth/token');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));
// Send the request
$response = curl_exec($ch);
var_dump($response);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
echo $responseData['published'];
?>
I've noticed as well that when I use Advanced Rest Client Extension for chrome and if I set the Content-Type to application/json I have to enter a login and a password that I don't know what are those because even if I enter the id and secret key that I have in the code it returns 401 Unauthorized. So I'm guessing this code that I wrote is not forcing it to the content-type: application/x-www-form-urlencoded, but I'm not sure. Thank you for any help on this issue!
Can you try like that and see if it helps:
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_COOKIEFILE => 'cookie.txt',
CURLOPT_COOKIEJAR => 'cookie.txt',
CURLOPT_USERPWD => 'username:password', //Your credentials goes here
CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded'),
CURLOPT_POSTFIELDS => http_build_query($postData),
));
I guess the site expect simple authentication on top of the secret_key that you already provided.
Also it is possible to send a Cookie, so just in case it is good idea to store it and use it again in the next Curl calls.

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();

Categories