How to get access token using refresh token in DocuSign and PHP? - php

I want to update my access token using the previous refresh token in DocuSign? I am getting
{
"error": "invalid_grant",
"error_description": "unsupported_grant_type"
}
Below is how I made the request.
$client_id = env('DOCUSIGN_CLIENT_ID');
$client_secret = env('DOCUSIGN_CLIENT_SECRET');
$encoded_client_id = utf8_decode(base64_encode($client_id));
$encoded_client_secret = utf8_decode(base64_encode($client_secret));
$integrator_and_secret_key = "Basic " . "{$encoded_client_id}:{$encoded_client_secret}";
// $integrator_and_secret_key = "Basic " . utf8_decode(base64_encode("{$client_id}:{$client_secret}"));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://account-d.docusign.com/oauth/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$data = array(
'refresh_token' => "My refresh token from previous successful request",
'grant_type' => 'refresh_token',
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$headers = array();
$headers[] = "Authorization: Basic " . "{$encoded_client_id}:{$encoded_client_secret}";
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$headers[] = 'Cache-Control: no-cache';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
Log::info($result);

So, not confident that's the only issue, but the way you encode the clientId and clientSecret is different, you encode each part separately, instead of the whole thing with the colon.
https://www.docusign.com/blog/developers/authorization-code-grant-refresh-tokens shows that it's done like this:
string codeAuth = (clientId ?? "") + ":" + (clientSecret ?? "");
byte[] codeAuthBytes = Encoding.UTF8.GetBytes(codeAuth);
string codeAuthBase64 = Convert.ToBase64String(codeAuthBytes);
Note that the string that's encoded already had them combined, not each of them encoded separately.
Now, the error can also be because the Integration Key (IK or clientID) is not configured correctly, you use a bad refreshToken, it expired, you use the wrong environment (developer vs. production) and maybe a couple more reasons I forgot. Need to triple check all the values to ensure this if still not working.

For those who stuck on this issue:
The solution was just to change the content-type from application/x-www-form-urlencoded to application/json

Related

ConstantContact V3 400 Error when getting access token

If anyone is familiar with the Constant Contact V3 API perhaps you can be of help.
We are following the docs here: https://developer.constantcontact.com/api_guide/server_flow.html
I have even copy and pasted the PHP code but am Still receiving a 400 error and can't figure out what to do to fix it.
1st we use this for the auth url
$baseURL = "https://authz.constantcontact.com/oauth2/default/v1/authorize";
$authURL = $baseURL . "?client_id=" . $this->_clientID . "&response_type=code&scope=".urlencode('offline_access')."&state=" . $this->user->info['id'] . "&redirect_uri=" . urlencode(DOMAIN.'connect/constantcontact/');
This works and we do receive a code from constant contact.
Next we use the following code to ask for an access token
// Use cURL to get access token and refresh token
$ch = curl_init();
// Define base URL
$base = 'https://authz.constantcontact.com/oauth2/default/v1/token';
// Create full request URL
$url = $base . '?code=' . $_GET['code'] . '&redirect_uri=' . urlencode(DOMAIN.'connect/constantcontact/') . '&grant_type=authorization_code';
//echo $url;
curl_setopt($ch, CURLOPT_URL, $url);
// Set authorization header
// Make string of "API_KEY:SECRET"
$auth = $this->_clientID . ':' . $this->_clientSecret;
//echo $auth;
// Base64 encode it
$credentials = base64_encode($auth);
// Create and set the Authorization header to use the encoded credentials, and set the Content-Type header
$authorization = 'Authorization: Basic ' . $credentials;
curl_setopt($ch, CURLOPT_HTTPHEADER, array($authorization, 'Accept: application/json', 'Content-Type: application/x-www-form-urlencoded'));
// Set method and to expect response
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Make the call
$result = curl_exec($ch);
curl_close($ch);
The response we receive is just a 400 error every time.
<html>
<head><title>400 Bad Request</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
<hr><center>cloudflare</center>
</body>
</html>
Any help or insight on how to fix this would be greatly appreciated. In a bit of a time pinch.
Solved. The following fields were also needed in the post body.
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['client_id' => $this->_clientID, 'client_secret' => $this->_clientSecret, 'code' => $_GET['code']]) );

2ba web API post request with php curl

Im using 2ba its API to receive product information which I later on want to store inside my database. I am trying to create a post request for receiving the data I need. This is the request I want to get to working. And this is my code:
postApiData.php
<?php
/**
* Posts API data based on given parameters at index.php.
*/
// Base url for all api calls.
$baseURL = 'https://api.2ba.nl';
// Version number and protocol.
$versionAndProtocol = '/1/json/';
// All parts together.
$url = $baseURL . $versionAndProtocol . $endPoint;
// Init session for CURL.
$ch = curl_init();
// Init headers. Security for acces data.
$headers = array();
$headers[] = "Authorization: Bearer " . $token->access_token;
// Options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
echo "<br>";
echo "Error location: postApiData";
exit();
}
// Ends the CURL session, frees all resources that belongs to the curl (ch).
curl_close($ch);
// String to array.
$data = json_decode($data);
?>
index.php
// Specified url endpoint. This comes after the baseUrl.
$endPoint = 'Product/forGLNAndProductcodes';
// Parameters that are required or/and optional for the endPoint its request.
$parameters = [
'gln' => '2220000075756',
'productcodes' => ['84622270']
];
// Get Supplier info
include("postApiData.php");
print_r($data);
exit();
My API key does for sure work since I have done alot of different GET requests already, also im not getting an access denied error.
The error I get with this code is: The requested URL returned error: 500 Internal Server Error
I also receive a "Bad request" 400 error when I remove the curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters)); part
Is there anyone who knows what im doing wrong?
PS: It's not really possible to try this code yourself unless you have a 2ba account with working key's etc.
Okey I fixed it already...
I had to add some extra headers and change the $parameters values like this:
postApiData.php
// Added this above the authorization.
$headers[] = "Connection: close";
$headers[] = "Accept-Encoding: gzip,deflate";
$headers[] = "Content-Type: application/json";
// Removed the http_build_query part.
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
index.php
// Encoded in a json way as asked by 2ba request.
$parameters = json_encode($parameters);

How to connect with 2ba it's API using PHP

Im trying to connect to the API services of 2ba. Somehow I just can't connect. I get the error: error: "invalid_client"
I dont know what to try, it feels like I need to hash my cliend_secret or complete url but I dont see that in the documentation.
This is my code (PHP):
<?php
// ---- GET TOKEN ----
// Base url for all api calls.
$baseURL = 'https://authorize.2ba.nl';
// Specified url endpoint. This comes after the baseUrl.
$endPoint = '/OAuth/Token';
// Parameters that are required or/and optianal for the endPoint its request.
$parameters = 'grant_type=password&username=abc#abc.com&password=123abc&client_id=myClientID&client_secret=myClientSecret';
// All parts together.
$url = $baseURL . $endPoint . '?' . $parameters;
//Init session for CURL.
$ch = curl_init();
// Options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
// Init headers for access to the binance API signed data.
$headers = array();
$headers[] = 'Content-type: application/x-www-form-urlencoded';
$headers[] = 'Content-Length: 0';
// Setting headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
// Ends the CURL session, frees all resources and deletes the curl (ch).
curl_close($ch);
$result = json_encode($data);
echo($data);
exit();
?>
The authentication is oauth2 and I want to use the "Password Grant" flow since I can login automaticly this way. Also I see in the example code in C# that they encode the url, something im not doing yet but did try. It did not work.
// Using $encodedUrl like this: curl_setopt($ch, CURLOPT_URL, $encodedUrl); but does not work.
$encodedUrl = urlencode($url);
Alright so I fixed it. I now got my access token and am able to recieve data from the API. This is what I did:
// ---- GET TOKEN - FLOW: USER PSW ----
// No changes
$baseURL = 'https://authorize.2ba.nl';
// No changes
$endPoint = '/OAuth/Token';
// $parameters is now an array.
$parameters = array(
'grant_type' => 'password',
'username' => 'myUsername',
'password' => 'myPassword',
'client_id' => 'myClientID',
'client_secret' => 'myClientSecret'
);
// Removed the $parameter part
$url = $baseURL . $endPoint;
//Init session for CURL.
$ch = curl_init();
// Init headers for access to the binance API signed data.
$headers = array();
$headers['Content-Type'] = "application/x-www-form-urlencoded";
// NOTE: http_build_query fixed it.
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters)); // Automaticly encodes parameters like client_secret and id.
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
// Ends the CURL session, frees all resources and deletes the curl (ch).
curl_close($ch);
$result = json_encode($data);
echo($data);
exit();

curl PUT request with discord API resulting bad request

I'm using php, oauth2, and curl to connect to the Discord API and add a member to a server (guild).
I have successfully authenticated the user using Oath2 with the identify, guilds, and guilds.join scope.
I have the access_token & the bot token needed.
From my understanding in the Discord API docs:
https://discord.com/developers/docs/resources/guild#add-guild-member
I need to use a PUT request with the access_token (with guilds.join scope) and headers with Authentication: Bot Token to the endpoint: https://discordapp.com/api/guilds/GUILDID/members/USERID
I have done this but receive a 400 Bad Request error.
I am not sure what the problem could be.
Config
define('OAUTH2_CLIENT_ID', 'REDACTED');
define('OAUTH2_CLIENT_SECRET', 'REDACTED');
$guildid = REDACTED
$authorizeURL = 'https://discord.com/api/oauth2/authorize?client_id=REDACTED&permissions=0&redirect_uri=https%3A%2F%2FREDACTED%2Findex.php%3Faction%3Ddiscord&response_type=code&scope=identify%20guilds%20guilds.join%20bot';
$tokenURL = 'https://discordapp.com/api/oauth2/token';
$apiURLBase = 'https://discordapp.com/api/users/#me';
$apiURLGuilds = 'https://discordapp.com/api/users/#me/guilds';
$apiURLJoin = 'https://discordapp.com/api/guilds/'. $guildid . '/members/';
join function
function joinapiRequest($url,$userid) {
$url = $url.$userid;
$params = 'access_token='.session('access_token');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$bottoken = redacted;
$headers[] = 'Authorization: Bot ' . $bottoken;
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-Length: '.strlen($params);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$response = curl_exec($ch);
echo 'join guild response <br />';
var_dump($response);
if($http == 201){
return true;
} else {
return false;
}
}
response
string(42) "{"message": "400: Bad Request", "code": 0}"
Any help would be much appreciated.
For anyone looking for an answer, I fixed this by changing the syntax on sending the access_token to:
$params = '{"access_token" : "'.session('access_token').'"}';

Can i store static API Key in php file safely

i want to use FCM in my android application , and i was wondering what is the best practice to store a static API such as Server Key API of FCM .
And after a lot o reading i found that even using ProGard doesn't save the API securely, so the conclusion is to never store keys in the app source code .
My solution is to save the key in a .php file like this, so that every time a device send a notification it sends data ( Notification title , message .. ) to my server that contain the server key and redirect the request to https://fcm.googleapis.com/fcm/send
My php file :
<?php
require_once __DIR__ . '/notification.php';
$notification = new Notification();
$title = "Notification Title";
$message = "Notification Message";
$notification->setTitle($title);
$notification->setMessage($message);
$firebase_api = "API_STATIC_SERVER_CODE_THAT_I_NEED_TO_HIDE";
$requestData = $notification->getNotificatin();
$fields = array(
'to' => '/topics/Test_Topic',
'data' => $requestData,
);
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=' . $firebase_api,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarily
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if($result === FALSE){
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo '<h2>Result</h2><hr/><h3>Request </h3><p><pre>';
echo json_encode($fields,JSON_PRETTY_PRINT);
echo '</pre></p><h3>Response </h3><p><pre>';
echo $result;
echo '</pre></p>';
?>
But, is that safe ? Could hackers some how download my php content ( without hacking my server ) , or the fact that i am using HTTPS connections keeps my data safe .
And what else can i do if it's not safe enough
Thank you

Categories