PHP retrieve POST result - php

I'm trying to create an App for 'Exact Online' but i'm having a little bit of a problem with the OAuth security authentication
https://developers.exactonline.com/#OAuth_Tutorial.html%3FTocPath%3DAuthentication%7C_____2
After making my first authentication request and logging in I recieve a code.
With this code I can obtain an Token for making api calls.
if (!empty($_GET["code"])){
$code = $_GET["code"];
getting the code works so far. But when I try to make a new request (for the token) I get no response data.
My Code is as follows:
$data = array(
'code' => $code,
'redirect_uri' => 'http://****/asdf2.php',
'grant_type' => 'authorization_code',
'client_id' => '******-****-****-******-*****',
'client_secret' => '*********'
);
// Create map with request parameters
// Build Http query using params
$query = http_build_query ($data);
// Create Http context details
$contextData = array (
'method' => 'POST',
'header' => "Connection: close\r\n".
"Content-Length: ".strlen($query)."\r\n",
'content'=> $query );
// Create context resource for our request
$context = stream_context_create (array ( 'http' => $contextData ));
// Read page rendered as result of your POST request
$result = file_get_contents (
'https://start.exactonline.nl/api/oauth2/token', // page url
false,
$context);
// Server response is now stored in $result variable so you can process it
if (!empty($result)){
echo "success";
}else{
echo "no result";
}
}else {
echo "error";
}
$result is always empty, what could be the problem. I've checked my client_id and secret multiple times.
After changing it to cUrl it still didn't work:
$result = get_oauth2_token($code);
// Server response is now stored in $result variable so you can process it
if (!empty($result)){
echo "success";
}else{
echo "no result";
}
}else {
echo "error";
}
/*
Function
*/
function get_oauth2_token($code) {
global $client_id;
global $client_secret;
global $redirect_uri;
$oauth2token_url = "https://start.exactonline.nl/api/oauth2/token";
$clienttoken_post = array(
'code' => $code,
'redirect_uri' => 'http://*****/asdf2.php',
'grant_type' => 'authorization_code',
'client_id' => '{*******}',
'client_secret' => '******'
);
$curl = curl_init($oauth2token_url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clienttoken_post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$json_response = curl_exec($curl);
curl_close($curl);
$authObj = json_decode($json_response);
if (isset($authObj->refresh_token)){
//refresh token only granted on first authorization for offline access
//save to db for future use (db saving not included in example)
global $refreshToken;
$refreshToken = $authObj->refresh_token;
}
$accessToken = $authObj->access_token;
return $accessToken;
}

The documentation shows that client_id should be inside curly braces. So I think it should be:
'client_id' => '{******-****-****-******-*****}',

Related

Soundcloud API (PHP) returns "invalid grant"

We are using the code below to try to upload tracks from our WordPress site to SoundCloud through PHP. MP3 tracks are already on our server before running this script.
function upload_soundcloud()
{
//App credentials. Create one at http://soundcloud.com/you/apps
define('API_URL', 'https://api.soundcloud.com');
define('CLIENT_ID', '$client_id');
define('CLIENT_SECRET', '$client_secret');
//User credentials
define('EMAIL', '$email');
define('PASSWORD', '$password');
//Path to MP3 file to upload
define('FILE', ABSPATH . '/wp-content/uploads/path/to/file.mp3');
class SoundcloudAPI {
private $url;
private $clientID;
private $secret;
private $accessToken;
public function __construct($url, $clientID, $secret) {
$this->url = $url;
$this->clientID = $clientID;
$this->secret = $secret;
}
public function auth($username, $password) {
$url = $this->url . '/oauth2/token';
$data = array(
'client_id' => $this->clientID,
'client_secret' => $this->secret,
'grant_type' => 'password',
'username' => $username,
'password' => $password
);
$result = $this->request($url, $data, 'POST');
$this->accessToken = $result->access_token;
return $result;
}
public function upload($title, $path) {
$url = $this->url . '/tracks';
$data = array(
'oauth_token' => $this->accessToken,
'track[title]' => $title,
'track[asset_data]' => new CurlFile(realpath($path), 'audio/mpeg'),
);
$result = $this->request($url, $data, 'POST');
return $result;
}
private function request($url, $data, $method) {
$curl = curl_init();
if ($method === 'POST') {
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
} else {
$url .= '?' . http_build_query($data);
}
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$result = json_decode(curl_exec($curl));
curl_close($curl);
return $result;
}
}
$soundCloud = new SoundcloudAPI(API_URL, CLIENT_ID, CLIENT_SECRET);
$resultAuth = $soundCloud->auth(EMAIL, PASSWORD);
$resultUpload = $soundCloud->upload('Test', FILE);
echo '<pre>';
print_r($resultAuth);
print_r($resultUpload);
echo '</pre>';
}
This is what we are getting as a response:
stdClass Object
(
[error] => invalid_grant
)
Does anyone know why this might be happening? (the strangest part is that it was actually working 2 days ago, but then just stopped working and I feel like I am going crazy).
Try and save the access token and refresh token between requests (for example, in a local file or database) and reusing it. The rate-limit only seems to be on the /oauth2/token endpoint when using a username and password.
Once your access token has expired, you can use the refresh token to get a new one by making a request to /oauth2/token with:
'grant_type': 'refresh_token',
'client_id': <your client id>,
'client_secret': <your client secret>,
'refresh_token': <previous refresh token>

How to get access token Strava Api with PHP

public function auth_callback()
{
if ($this->input->get("code") != null)
{
$this->Strava_model->UpdateProfileStravaToken($this->input->get("code"),$this->session->userdata("athlete_id"));
$url = "http://www.strava.com/oauth/token?client_id=[xxxxx]&client_secret=[xxxxxxxxxxx]&code=".$this->input->get("code")."&grant_type=authorization_code";
$post = array();
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($post)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
echo $result;exit;
$cURLConnection = curl_init($url);
curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $post);
curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
$apiResponse = curl_exec($cURLConnection);
curl_close($cURLConnection);
$jsonArrayResponse = json_decode($apiResponse);
redirect($this->config->item("base_url") . "/activity");
}
}
I manage to get the code, and now proceed to get access token.
I'm using php curl to send post as below:
http://www.strava.com/oauth/token?client_id=[xxxx]&client_secret=[xxxxx]&code=[code retrieve from redirection]&grant_type=authorization_code
Once I executed the code above, I got this "You're being redirect..."
Can anyone advice and help?
Generally requests to the OAuth2 token endpoint require parameters to be passed as form-data, in the request body. Based on your current source, you are sending an empty request body.

salesforce rest api invalid session id error when using access token

I am trying to retrieve data from salesforce using the REST api and CURL in PHP.
I perform the authentication request and recieve an 'instance_url' and 'access_token' but after performing a query request using those, i receive an "INVALID_SESSION_ID" error.
my authentication request code:
function get_sf_auth_data() {
$post_data = array(
'grant_type' => 'password',
'client_id' => 'xxxxxxxxxxxxxxxxxxxxxx', //My client id (xxx... for this example)
'client_secret' => '111111111111', // My client secret (111... for this example)
'username' => 'my_user_name',
'password' => 'my_user_password'
);
$headers = array(
'Content-type' => 'application/x-www-form-urlencoded;charset=UTF-8'
);
$curl = curl_init('https://login.salesforce.com/services/oauth2/token');
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
$response = curl_exec($curl);
curl_close($curl);
// Retrieve and parse response body
$sf_access_data = json_decode($response, true);
echo '*********' . $sf_response_data['instance_url'] . '********';
echo '*********' . $sf_response_data['access_token'] . '********';
return $sf_access_data;
}
My query request code:
function get_user_sfid($sf_access_data, $user_id_number){
$sql = "SELECT Id, Name
FROM Account
WHERE ID__c = '$user_id_number'";
$url = $sf_access_data['instance_url'] . '/services/data/v20.0/query/?q=' . urlencode($sql);
$headers = array(
'Authorization' => 'OAuth ' . $sf_access_data['access_token']
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$json_response = curl_exec($curl);
curl_close($curl);
var_dump($json_response); // This prints out the response where i got the error
$response = json_decode($json_response);
return $response['id'];
}
The response to the query request as is:
[{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]
I have also tried using this guide (http://developer.force.com/cookbook/recipe/interact-with-the-forcecom-rest-api-from-php) as reference but it uses an "authorization_code" authentication and not a password one.
EDIT
The app has full access in salesforce and both api version and authentication data are correct
I found the solution.
I defined my headers array as:
$headers = array(
"Authorization" => "OAuth " . $sf_access_data['access_token']
);
When i should have defined it as:
$headers = array(
"Authorization: OAuth " . $sf_access_data['access_token']
);

Twitch get access token

I'm using the following PHP class which I found on GitHub: Twitch oauth class
So I've been creating the Authentification site, which will let you authentificate your twitch account and redirect you to another site using the following url:
http://website.com/twitch/dashboard.php?code=xxxxxxx&scope=user_read+channel_read+chat_login+user_follows_edit+channel_editor+channel_commercial+channel_check_subscription
Now I've used the following code to receive the access_token:
<?php
$ttv_code = $_GET['code'];
$access_token = $twitchtv->get_access_token($ttv_code);
$user_name = $twitchtv->authenticated_user($access_token);
if(isset($user_name)) {
echo 'Thank you ' . $user_name . '! Authentication Completed!';
}else{
echo 'Authentification failed!';
}
?>
But sadly there's no response coming back from the function. The function looks like the following:
function get_access_token($code) {
$ch = curl_init($this->base_url . "oauth2/token");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, 1);
$fields = array(
'client_id' => $this->client_id,
'client_secret' => $this->client_secret,
'grant_type' => 'authorization_code',
'redirect_uri' => $this->redirect_url,
'code' => $code
);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
$data = curl_exec($ch);
$response = json_decode($data, true);
return $response["access_token"];
}
Does anyone have a idea what causes this mistake? I would appreciate any kind of help.

PHP - Stripe Connect return null

I'm starting with Stripe Payment and need to connect the user to my Stripe app. I follow the guildance in Stripe to get the accesss_token with the PHP code:
// See full code example here: https://gist.github.com/3507366
if (isset($_GET['code'])) { // Redirect w/ code
$code = $_GET['code'];
$token_request_body = array(
'grant_type' => 'authorization_code',
'client_id' => 'ca_*************************',
'code' => $code,
'client_secret' => 'sk_test_************************'
);
$req = curl_init(TOKEN_URI);
curl_setopt($req, CURLOPT_RETURNTRANSFER, true);
curl_setopt($req, CURLOPT_POST, true );
curl_setopt($req, CURLOPT_POSTFIELDS, http_build_query($token_request_body));
// TODO: Additional error handling
$respCode = curl_getinfo($req, CURLINFO_HTTP_CODE);
$resp = json_decode(curl_exec($req), true);
curl_close($req);
echo $resp['access_token'];
} else if (isset($_GET['error'])) { // Error
echo $_GET['error_description'];
} else { // Show OAuth link
$authorize_request_body = array(
'response_type' => 'code',
'scope' => 'read_write',
'client_id' => 'ca_************************'
);
$url = AUTHORIZE_URI . '?' . http_build_query($authorize_request_body);
echo "<a href='$url'>Connect with Stripe</a>";
}
But the response from Stripe is always null. Has anyone experienced the same problem like this before. Any help would be very valuable for me this time.
Thank you very much.
After a while of debugging, I found out the problem is with the cURL library of my PHP server. It seem cURL not work with HTTPS. And base on this thread: PHP cURL Not Working with HTTPS
I find the solution to make it run by bypassing the verification:
...
curl_setopt($req, CURLOPT_POSTFIELDS, http_build_query($token_request_body));
curl_setopt($req, CURLOPT_SSL_VERIFYPEER, false); // Bypass the verification
$resp = json_decode(curl_exec($req), true); // Now has response well.
...
P/s: This is not a good solution, better do more research (here)
I hope this help some beginner like me :)

Categories