I am trying to make a simple CURL call to GetReponse using PHP and I must be doing something wrong. Each time I try to use my clients access token it bombs out. If I hard code my company API key into the place where I've put the xxxxx's it works fine. I'm using their docs, but I can't get it to work, any help? Btw, their docs are HORRIBLE - so bad I can't even begin to fully explain! They're filled with a billion typos... Their Docs
$url = "https://api.getresponse.com/v3/campaigns";
$headers = array();
$headers[] = "X-Auth-Token: api-key xxxxxxxxx";
$state_ch = curl_init();
curl_setopt($state_ch, CURLOPT_URL, $url);
curl_setopt($state_ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($state_ch, CURLOPT_HTTPHEADER, $headers);
$state_result = curl_exec ($state_ch);
$state_result = json_decode($state_result);
$debug = 1;
print_r($state_result);
I always get the same response:
stdClass Object
(
[httpStatus] => 401
[code] => 1014
[codeDescription] => Problem during authentication process, check headers!
[message] => Unable to authenticate request. Check credentials or authentication method details
[moreInfo] => https://apidocs.getresponse.com/en/v3/errors/1014
[context] => stdClass Object
(
[authenticationType] => auth_token
)
[uuid] => xxxxxxxxxxxxxxxxxxxxxxxxx
)
Again, if I put my company API key in the place of the xxxxxx's (which I have to get inside of their control panel) it works. Access tokens do not.
Solution:
Looks like the header needs to change to this...
$headers[] = "Authorization: Bearer xxxxxxxxxxxxxxx"
As I can see:
[httpStatus]401 = unauthorized
Check your API token permission
I'm using next code:
$headers = [];
$headers[] = "X-Auth-Token: api-key MY_API_KEY";
$ch = curl_init('https://api.getresponse.com/v3/campaigns');
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$result = curl_exec($ch);
if($result)
{
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($result, 0, $header_size);
$body = substr($result, $header_size);
}
curl_close($ch);
Related
I am using paytm refund api in php.
here is my code:
$checkSum = "";
$paramList = array();
// Create an array having all required parameters for creating checksum.
$paramList["MID"] = '**********';
$paramList["ORDERID"] = '*******'; //get during paytm transaction response
$paramList["TXNTYPE"] = 'REFUND';
$paramList["REFUNDAMOUNT"] = '50';
$paramList["TXNID"] = '***********'; // get during paytm transaction response
$paramList["REFID"] = 'REFID'.time();
//Here checksum string will return by getChecksumFromArray() function.
$checkSum = getRefundChecksumFromArray($paramList,PAYTM_MERCHANT_KEY);
$paramList["CHECKSUM"] = urlencode($checkSum);
$data_string = 'JsonData='.json_encode($paramList);
// initiate curl
$ch = curl_init();
$url = 'https://securegw-stage.paytm.in/refund/HANDLER_INTERNAL/REFUND';
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true); // tell curl you want to post something
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string); // define what you want to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return the output in string format
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$output = curl_exec ($ch); // execute
$info = curl_getinfo($ch);
$data = json_decode($output, true);
print_r($data);
Here is the response, i am getting:
Array ( [RESPCODE] => 501 [RESPMSG] => System Error. [STATUS] => PENDING )
I am not getting that what this system error means. What is the solution for this. Any help would be much appreciated.
Thanks in advance..
According to the error doc error 501 is an system error inside payTm.
https://developer.paytm.com/docs/refund-status-api/
I guess you are using payTm staging server. There is nothing wrong from your side, I suggest you to wait a few hours and try again. it will automatically work
I was facing the same issue because i had not declared the value of PAYTM_MERCHANT_KEY
before passing it to getRefundChecksumFromArray
$checkSum = getRefundChecksumFromArray($paramList,PAYTM_MERCHANT_KEY);
This line of code solved it
define("PAYTM_MERCHANT_KEY", "your_key_goes_here");
I have to write to an API, and nothing seems to work. When I use apitester.com it works though. When I use my app, it doesn't. I output the headers and payload and they look the same between the two, so I am assuming I'm doing something wrong. Here is my PHP to send data to the API
<?php
$email = $_POST['email'];
$expired = NULL;
$funded = TRUE;
$data = array(
"email" => $email,
"expired" => $expired,
"funded" => $funded
);
$url = 'https://my.rest.api';
$json_string = json_encode($data);
$headers = array (
"Content-Type: application/json",
"Authorization: Bearer xxx"
);
$channel = curl_init($url);
curl_setopt($channel, CURLOPT_RETURNTRANSFER, true);
curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($channel, CURLOPT_HTTPHEADER, $headers);
curl_setopt($channel, CURLOPT_POSTFIELDS, $json_string);
curl_setopt($channel, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($channel, CURLOPT_CONNECTTIMEOUT, 10);
$statusCode = curl_getInfo($channel, CURLINFO_HTTP_CODE);
curl_exec($channel);
http_response_code($statusCode);
if ( $statusCode != 200 ){
echo "Data submitted was ".$json_string." Returned status code: {$statusCode} \n".curl_error($channel);
} else {
echo $response;
}
//I turn the below 2 lines on and off to see what I am actually sending
// print_r($headers);
// echo $json_string;
curl_close($channel);
?>
I get the returned status code of "0" on my app, but "200" using the tester. Is there something obviously wrong with the curl options I am sending?
If you got status 0, it means that the HTTP request didn't complete at all. You can use the following functions to find out what error happened:
curl_errno
curl_errstr
Sidesnotes:
You're echoing $response, but that variable doesn't exist.
Using CURLOPT_SSL_VERIFYPEER is a really bad idea. Make sure you remove it before you go to production.
I couldn't fetch user's email address through linkedin v2 api. I added r_emailaddress permission in app settings and also in access token request as well. But it says.
{
"serviceErrorCode": 100,
"message": "Not enough permissions to access: GET-members /clientAwareMemberHandles",
"status": 403
}
My request url is:
https://api.linkedin.com/v2/clientAwareMemberHandles?q=members&projection=(elements*(primary,type,handle~))&oauth2_access_token=".$token
Anyone please help me to solve this.
You can access the linkedin user email address with below EP:
`https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))`
Make sure that you have defined the scope 'r_emailaddress' in your library.
You can use below curl request to fetch the data:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '. $token,
'X-Restli-Protocol-Version: 2.0.0',
'Accept: application/json',
'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$response = curl_exec($ch);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$body = substr($response, $headerSize);
$response_body = json_decode($body,true);
$response_body will return the following response:
Array (
[elements] => Array
(
[0] => Array
(
[handle] => urn:li:emailAddress:123456
[handle~] => Array
(
[emailAddress] => your#email.in
)
)
)
)
With this type of response "handle~" value is not easy to get the next step should be :
$email = [];
$response_body = json_decode($res->getBody());
$object = $response_data->elements[0];
foreach ($object as $value){
$email[] = $value->emailAddress;
}
print_r($email[0]);
In my mobile app, I have configured payumoney perfectly and its working great. Its just a case of refund. Below is the code in the php file which I call from the app:
include('../connection.php');
$orderid="AMD197";
$view_rs =$conn->prepare("SELECT * from tbl_payumoney_order WHERE orderid=:orderid");
$view_rs->execute(array(':orderid'=>$orderid));
$vfetch=$view_rs->fetch();
$merchantId="393463";
$paymentId= $vfetch['paymentId'];
$refundAmount= $vfetch['amount'];
$merchantAmount= $vfetch['amount'];
$aggregatorAmount= "0";
$refundType="1";
$data_string="paymentId=".$paymentId."&refundAmount=".$refundAmount."&refundType=".$refundType."&merchantId=".$merchantId."&merchantAmount=".$merchantAmount."&aggregatorAmount=".$aggregatorAmount;
//paymentId=123456&refundAmount=56&refundType=1&merchantId=765433&merchantAmount=6&aggregatorAmount=50
$ch = curl_init();
$url = "https://test.payumoney.com/payment/refund/refundPayment";
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true); /* tell curl you want to post something*/
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string); /* define what you want to post*/
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); /* return the output in string format*/
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$output = curl_exec ($ch);
$info = curl_getinfo($ch);
$data = json_decode($output, true);
print_r($data);
$status= $data['status'];
$message= $data['message'];
$result= $data['result'];
I am getting this response:
Array ( [status] => -1 [rows] => 0 [message] => Something went Wrong
guid 3k4pcbv6kdqf405g0lut7id32m sessionId null [result] => [guid] =>
3k4pcbv6kdqf405g0lut7id32m [sessionId] => null [errorCode] => )
Can anyone suggest if I am doing anything wrong here?
Refund API doesn't work in test/sandbox environment.
Please find the Refund API below for live environment:
https://www.payumoney.com/treasury/merchant/refundPayment?merchantKey=merchantkeyvalue&paymentId=1234&refundAmount=10
Please pass the Merchant Key, Payment ID and Amount in Params and Authorization Header in Headers.
Something went wrong... error comes at PayUmoney's end due to 500, 502, 503 or 504
Server error in your App or Website according to PayUmoney API Documentation.
To know more about these HTTP Response Codes, you need to follow below link:
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Also update your Curl to get more info in case of malfunction like below:
$output = curl_exec($ch);
if ($output === false){
// throw new Exception('Curl error: ' . curl_error($output));
print_r('Curl error: ' . curl_error($output));
}
If you still not sure about your issue, then its better to contact PayUmoney Support Team.
I've written a basic API script in PHP using cURL - and successfully used a version of it on another API, this one is specifically to handle domain DNS management on DigitalOcean - and I can't send data?
Prelude...
I understand there is a PHP library available, I'm not after something that full featured or bloated with dependencies - just something small to use locally and primarily to help me understand how RESTful API's work a little better in practice - an educational exercise
The offending Code...
function basic_api_handle($key, $method, $URI, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$key,
'Content-Type: application/json')
);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_URL, $URI);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
if($result === false) error_log("API ERROR: Connection failure: $URI", 0);
curl_close($ch);
return json_decode($result, true);
}
var_dump(basic_api_handle($api_key, 'POST', 'https://api.digitalocean.com/v2/domains', array('name' => 'my-domain.tld', 'ip_address' => '1.2.3.4')));
This works with a GET request, such as listing the domains on the account but seems to fail at posting/sending data... this results in "unprocessable_entity" and "Name can't be blank" - as the name is not blank and is correctly formatted (as far as I can tell) it suggests to me the data is not being sent correctly?
Solution Attempts so far...
I've tried json encoding the data (seen in code), not json encoding, url encoding with and without json encoding and various other options with no luck.
I've seen a few posts online about this exact same issue specifically with DigitalOcean's API (and a another) but no one had an explanation (other than give up and use the library or something to that affect).
Using cURL directly from a terminal does work etc so there is nothing wrong with the API for creating a domain.
As far as I understand, the authentication is working, and the general setup works as I can list domains within the account, I just cant POST or PUT new data. I've been though the API's documentation and can't see what I'm doing wrong, maybe some sort of wrong encoding?
Any help would be much appreciated! :)
Edit:
After much work and research even other simple API handlers do not work with Digital Ocean (such as https://github.com/ledfusion/php-rest-curl) - is there something this API in particular needs or am I missing something fundamental about API's in general?
Technically this is not an fix but a work around. Thank you everyone for your comments and ideas, unfortunately nothing worked/fixed the code and the bounty expired :(
Although I have no idea why the PHP cURL option didn't work (the HTTP works, just Digital Ocean spitting errors for unknown reason linked to validation of the post data)...
I do have a new method that DOES WORK finally... (thanks to jtittle post on the Digital Ocean Community forum)
Just incase that link dies in the future... he's the working function using streams and file_get_contents and not curl...
<?php
function doapi( $key, $method, $uri, array $data = [] )
{
/**
* DigitalOcean API URI
*/
$api = 'https://api.digitalocean.com/v2';
/**
* Merge DigitalOcean API URI and Endpoint URI
*
* i.e if $uri is set to 'domains', then $api ends up as
* $api = 'https://api.digitalocean.com/v2/domains'
*/
$uri = $api . DIRECTORY_SEPARATOR . $uri;
/**
* Define Authorization and Content-Type Header.
*/
$headers = "Authorization: Bearer $key \r\n" .
"Content-Type: application/json";
/**
* If $data array is not empty, assume we're passing data, so we'll encode
* it and pass it to 'content'. If $data is empty, assume we're not passing
* data, so we won't sent 'content'.
*/
if ( ! empty( $data ) )
{
$data = [
'http' => [
'method' => strtoupper( $method ),
'header' => $headers,
'content' => json_encode( $data )
]
];
}
else
{
$data = [
'http' => [
'method' => strtoupper( $method ),
'header' => $headers
]
];
}
/**
* Create Stream Context
* http://php.net/manual/en/function.stream-context-create.php
*/
$context = stream_context_create( $data );
/**
* Send Request and Store to $response.
*/
$response = file_get_contents( $uri, false, $context );
/**
* Return as decoded JSON (i.e. an array)
*/
return json_decode( $response, true );
}
/**
* Example Usage
*/
var_dump(doapi(
'do-api-key',
'get',
'domains'
));
I used this to actually post the data successfully...
var_dump(doapi(
$api_key,
'post',
'domains',
array("name" => (string) $newDomain, "ip_address" => "1.2.3.4")
));
Add the Content-Length header and use CURLOPT_POST option for POST requests
function basic_api_handle($key, $method, $URI, $data) {
$json = json_encode($data)
$headers = array(
'Authorization: Bearer '.$key,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $URI);
if ( $method === 'POST' ) {
curl_setopt($curl, CURLOPT_POST, 1);
} else {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
array_push($headers, 'Content-Length: ' . strlen($json) );
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers)
curl_setopt($ch, CURLOPT_POSTFIELDS, $json );
$result = curl_exec($ch);
if($result === false) error_log("API ERROR: Connection failure: $URI", 0);
curl_close($ch);
return json_decode($result, true);
}
Maybe this will work for you:
function basic_api_handle($key, $method, $URI, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); // <-- Should be set to "GET" or "POST"
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // <-- Maybe the SSL is the problem
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"); // <-- I am not familiar with this API, but maybe it needs a user agent?
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$key,
'Content-Type: application/json')
);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_URL, $URI);
curl_setopt($ch, CURLOPT_POST, count($data)); // <-- Add this line which counts the inputs you send
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
if($result === false) error_log("API ERROR: Connection failure: $URI", 0);
curl_close($ch);
return json_decode($result, true);
}
It can also be a problem of a header you should sent and your missing it.
It could be a 307 or 308 http redirect.
Maybe "https://api.digitalocean.com/v2/domains" redirects to another url.
If this is the case, try adding:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
to make curl follow the redirection and keep the parameters.
It is suggested that you also use:
curl_setopt($curl, CURLOPT_POSTREDIR, 3);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
to keep the request body.
Hope it helps.
You can also try use CURLOPT_POST