BlueSnap - Hosted Payment Fields Token - php

Receiving 401 Authentication Access error when trying to request Hosted Payment Field access token via PHP. I have followed this tutorial -> Easy start with BlueSnap hosted payment fields; read about these similar issues -> 1. BlueSnap integration with node js and angular 2. Error getting payment_field_token in Bluesnap API as well as read through the basic auth info http://developers.bluesnap.com/docs/authentication with no luck. Can anyone figure this out?
<?php
$TokenRequest=curl_init();
curl_setopt($TokenRequest, CURLOPT_URL, "https://sandbox.bluesnap.com/services/2/payment-fields-tokens");
curl_setopt($TokenRequest, CURLOPT_HEADER, 1);
curl_setopt($TokenRequest, CURLOPT_HTTPHEADER, array("Authorization: Basic CREDENTIALS_HERE", "Content-type: application/json"));
curl_setopt($TokenRequest, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($TokenRequest, CURLOPT_RETURNTRANSFER, true);
$TokenResponse=curl_exec($TokenRequest);
list($Headers, $Response)=explode("\r\n\r\n", $TokenResponse, 2);
$Headers=explode("\n", $Headers);
foreach($Headers as $Header)
{
if (stripos($Header, "Location")!==false)
{
$Token=trim(str_replace("Location: ", "", $Header));
}
}
?>

I work for BlueSnap.
A 401 error usually means a permission issue. Did you white list your IP in the BlueSnap console. Docs on how to do that can be found here: https://developers.bluesnap.com/docs/api-credentials . If you can provide me the actual JSON object (or XML) you are sending I can try to trace the exact error and try to determine root cause.
I found your API calls and you are doing a GET instead of a POST. The create a token you need to call a POST.

In the following URL you will find how to create the credentials to be able to generate the token: https://developers.bluesnap.com/docs/api-credentials
once you have the username and password, substitute the data of the variables: $username, $password:
the following code works for me
$host = 'https://sandbox.bluesnap.com/services/2/payment-fields-tokens';
$username = 'API_1644786117605226907536';
$password = '654321Pm!';
$TokenRequest=curl_init();
curl_setopt($TokenRequest, CURLOPT_URL, $host);
curl_setopt($TokenRequest, CURLOPT_HEADER, 1);
curl_setopt($TokenRequest, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($TokenRequest, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($TokenRequest, CURLOPT_RETURNTRANSFER, true);
$TokenResponse=curl_exec($TokenRequest);
list($Headers, $Response)=explode("\r\n\r\n", $TokenResponse, 2);
$Headers=explode("\n", $Headers);
foreach($Headers as $Header)
{
if (stripos($Header, "Location")!==false)
{
$Token=trim(str_replace("Location: ", "", $Header));
}
}
print_r($Token);
$HOSTEDFIELDTOKENID = str_replace("https://sandbox.bluesnap.com/services/2/payment-fields-tokens/", "", $Token);
echo '<br><br><br><br>';
print_r($HOSTEDFIELDTOKENID);

Related

Shopify REST API Pagination Link Empty

Situation
I am trying to make a call to the Shopify REST API where I have more than 50-250 results but I am not able to get the Link Header from the cURL Response which contains the Pagination Links.
Sample of Link Headers from the API Documentation for Cursor-Pagination (https://shopify.dev/tutorials/make-paginated-requests-to-rest-admin-api)
#...
Link: "<https://{shop}.myshopify.com/admin/api/{version}/products.json?page_info={page_info}&limit={limit}>; rel={next}, <https://{shop}.myshopify.com/admin/api/{version}/products.json?page_info={page_info}&limit={limit}>; rel={previous}"
#...
The link rel parameter does show up, but the Link is empty as below.
My Shopify Call function
function shopify_call($token, $shop, $api_endpoint, $query = array(), $method = 'GET', $request_headers = array()) {
// Build URL
$url = "https://" . $shop . ".myshopify.com" . $api_endpoint;
if (!is_null($query) && in_array($method, array('GET', 'DELETE'))) $url = $url . "?" . http_build_query($query);
$headers = [];
// Configure cURL
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
// this function is called by curl for each header received
curl_setopt($curl, CURLOPT_HEADERFUNCTION,
function($ch, $header) use (&$headers)
{
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) // ignore invalid headers
return $len;
$headers[trim($header[0])] = trim($header[1]);
return $len;
}
);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 3);
// curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_USERAGENT, 'Sphyx App v.1');
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl,CURLOPT_ENCODING,'');
// Setup headers
$request_headers[] = "";
if (!is_null($token)) $request_headers[] = "X-Shopify-Access-Token: " . $token;
$request_headers[] = 'Accept: */*'; // Copied from POSTMAN
$request_headers[] = 'Accept-Encoding: gzip, deflate, br'; // Copied from POSTMAN
curl_setopt($curl, CURLOPT_HTTPHEADER, $request_headers);
if ($method !== 'GET' && in_array($method, array('POST', 'PUT'))) {
if (is_array($query)) $query = http_build_query($query);
curl_setopt ($curl, CURLOPT_POSTFIELDS, $query);
}
// Send request to Shopify and capture any errors
$result = curl_exec($curl);
$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $result, 2);
$error_number = curl_errno($curl);
$error_message = curl_error($curl);
// Close cURL to be nice
curl_close($curl);
// Return an error is cURL has a problem
if ($error_number) {
return $error_message;
} else {
// Return headers and Shopify's response
return array('headers' => $headers, 'response' => json_decode($response[1],true));
}
}
But when I use a POSTMAN Collection, I get a proper formatted response without the Link getting truncated/processed.
I have tried a lot of things here available via the StackOverflow Forums as well as Shopify Community, but I'm unable to parse the Response Header the same way as shown by API Examples or POSTMAN
My issue does seem to be with the PHP Code, but I'm not a pro with cURL. Thus, I'm not able to make it further :(
Also, I'm not able to understand why POSTMAN's Headers are in Proper Case whereas mine are in Lower Case
Thanks in Advance!
Found my answer :
https://community.shopify.com/c/Shopify-APIs-SDKs/Help-with-cursor-based-paging/m-p/579640#M38946
I was using a browser to view my log files. So the data is there but it's hidden because of your use of '<'s around the data. I had to use the browser inspector to see the data. Not sure who decided this syntax was a good idea. Preference would be two headers that one can see and more easily parse since using link syntax is not relative to using an API.
My suggestion would be 2 headers:
X-Shopify-Page-Next: page_info_value (empty if no more pages)
X-Shopify-Page-Perv: page_info_value (empty on first page or if there is no previous page).
Easy to parse and use.
But having this buried as an invalid xml tag, having them both in the same header and using 'rel=' syntax makes no sense at all from an API perspective.

Laravel OAuth Authorization Header for FitBit API

I have been struggling for days now to find a decent solution for Laravel but to no avail.
There are many libraries out there that at one point may have worked to provide a Laravel - FitBit API OAuth integration however after trying over 15 different ones and none of them working I am stuck.
Reading the FitBit Documentation I see that once you receive a token you must swap the authorization code with an access token. To do this you need to send an authorization header like this:
POST https://api.fitbit.com/oauth2/token
Authorization: Basic Y2xpZW50X2lkOmNsaWVudCBzZWNyZXQ=
Content-Type: application/x-www-form-urlencoded
client_id=22942C&grant_type=authorization_code&redirect_uri=http%3A%2F%2Fexample.com%2Fcallback&code=1234567890
I have tried using guzzle and a few other libraries for sending the requests but none of them support the format that FitBit require.
I've seen sites with FitBit API integrated so there must be a solution for this.
If anyone has managed to integrate the FitBit API please let me know where I am going wrong.
Thanks.
I don't have a fitbit account, so I can't test this and it will probably need some tweaking, but I would start with something like:
class FitbitConnection{
public function getToken($request_url, $client_id, $client_secret, $code, $redirect_uri){
// base64 encode the client_id and client_secret
$auth = base64_encode("{$client_id}:{$client_secret}");
// urlencode the redirect_url
$redirect_uri = urlencode($redirect_uri);
$request_url .= "?client_id={$client_id}&grant_type=authorization_code&redirect_uri={$redirect_uri}&code={$code}";
// Set the headers
$headers = [
"Authorization: Basic {$auth}",
"Content-Type: application/x-www-form-urlencoded",
];
// Initiate curl session
$ch = curl_init();
// Set headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Options (see: http://php.net/manual/en/function.curl-setopt.php)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_POST, 1);
// Execute the curl request and get the response
$response = curl_exec($ch);
// Throw an exception if there was an error with curl
if($response === false){
throw new Exception(curl_error($ch), curl_errno($ch));
}
// Get the body of the response
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$responseBody = substr($response, $header_size);
// Close curl session
curl_close($ch);
// Return response body
return $responseBody;
}
}
You should note that I've commented out
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
You can put this option back in if you get an SSL certificate problem on your localhost, but you shouldn't use it in production .
You can then just do something like:
try{
$fitbitConnection = new FitbitConnection();
$token_response = $fitbitConnection->getToken("https://api.fitbit.com/oauth2/token","22942C","client_secret","1234567890","http://www.example.com");
echo $token_response;
}catch(Exception $e){
// curl error
echo $e->getMessage();
}

Does Marketo API block curl on a per account basis?

I am trying to connect to the Marketo.com REST API using curl.
I can't get a response from the identity service. I only get an error message
"[curl] 6: Couldn't resolve host 'MY_CLIENT_ENDPOINT.mktorest.com'
,
but I can print the constructed url and paste it into a browser address bar and this will provide the expected response with the access_token element.
I can use curl in php and in a terminal to access my gmail account so curl is able to access an https service.
I have tried sending the parameters in the curl url as a get request and also by declaring them with curl's -F option as a post request
My application uses dchesterton/marketo-rest-api available on github, but I have also tried a simple php curl request just to get the access token.
private function getToken() {
$url = "$this->client_url/identity/oauth/token?grant_type=client_credentials&client_id=$this->client_id&client_secret=$this->client_secret";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$errors = curl_error($ch);
curl_close($ch);
file_put_contents($this->logDir . 'access_token_response' . date('Y-m-d') . '.txt', $url . "\n" . $response . "\n", FILE_APPEND);
if ($errors) {
file_put_contents($this->logDir . 'access_token_errors' . date('Y-m-d') . '.txt', $errors . "\n", FILE_APPEND);
}
return $response['access_token'];
}
Again, this fails with the same error but produces a perfectly formed url that I can paste into the browser and get a valid response.
I have also tried this using post instead of get as I have for every other test mentioned, and these have been tried on my localhost and on a test server.
Can anyone explain to me why this would fail?
Does Marketo block curl on a per account basis?
I was trying to implement something similar but my code wasn't working. I'm not sure exactly what is failing but I tried your code and it seems to work perfectly after some slight modifications:
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($request_data));
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($curl);
$errors = curl_error($curl);
curl_close($curl);
I hope this helps.

Trying to make an API request using PHP with AWS Route53

I need to make one API request to AWS Route53 to create a reusable delegation set. You can't do this through the console web interface, it has to be through the API.
Here is the documentation for making this API request: http://docs.aws.amazon.com/Route53/latest/APIReference/api-create-reusable-delegation-set.html
<?php
$baseurl = "route53.amazonaws.com/2013-04-01/delegationset";
$body = '<?xml version="1.0" encoding="UTF-8"?>
<CreateReusableDelegationSetRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<CallerReference>whitelabel DNS</CallerReference>
</CreateReusableDelegationSetRequest>';
$ch = curl_init();
// Set query data here with the URL
curl_setopt($ch, CURLOPT_URL, $baseurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $body );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: route53.amazonaws.com','X-Amzn-Authorization: '));
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$rest = curl_exec($ch);
if ($rest === false)
{
// throw new Exception('Curl error: ' . curl_error($crl));
print_r('Curl error: ' . curl_error($ch));
}
curl_close($ch);
print_r($rest);
?>
I know the request isn't signed/authenticated, but I'm not even able to connect to the server. I would at least like to get an error message that says I'm not authenticated before I continue. Instead all I get is "connection refused".
I'm sure I'm doing something completely wrong here. But Google has been of no use.
scrowler was right. I changed:
$baseurl = "route53.amazonaws.com/2013-04-01/delegationset";
to
$baseurl = "https://route53.amazonaws.com/2013-04-01/delegationset";
I got the error message I was expecting and now I can work on the next step.

PAYPAL - Invalid Test API Credentials

Hi,
I have setup a business account at Paypal, and it seems that I already have my Test API Credentials, since I can successfully retrieve them from my Sandbox accounts.
Now I am trying to make the "first call" to get an authorization token.
Here's my PHP code:
$ch = curl_init();
$clientId = "myid"; //not the actual one
$secret = "mypass"; //not the actual one
curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/oauth2/token");
curl_setopt($ch, CURLOPT_HEADER, "Accept: application/json");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $clientId.":".$secret);
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
$result = curl_exec($ch);
$json = json_decode($result);
print_r($json);
curl_close($ch);
And here's the response:
stdClass Object ( [error] => invalid_client [error_description] => Invalid client credentials )
Does anybody have a clue?
Thanks
EDIT: This login is working (I found it elsewhere):
clientId: ASF6RRBP0uTq7FnC90tpFx7vfA-Pliw8uQDjv5RZ10Y_NVspuc88pUPLN6yM
Secret: EAdx7BDKzWczDomYG2QDHu8jhaAXj4xDZLHadvL5aRfesjwo5c81zbSpRxuE
Strangely the format looks very different from mine.
I'm stuck here, cannot go any further without a token.
You could pass it as a header similar as follows:
"Authorization" => "Basic " . base64_encode($clientId . ":" . $clientSecret)
This should act the same as above.
You could write it on curl_setopt like this:
curl_setopt($ch, CURLOPT_HEADER, "Authorization: Basic " . base64_encode($clientId . ":" . $clientSecret));
Also, just out of curiosity, you might want to try out PayPal-PHP-SDK. They have all these bells and whistles, that would keep you away from manually getting this code. It has documentations, and samples, that would help you get started with any API fairly quickly.
finally i managed to get it to work
the correct credentials are a hash of 60-digit, not 16 as first seen
i had to create an app to get them
nobody told me that at paypal, not even the "merchant technical support"
hope this helps someone in the future
thanks for your answers

Categories