Twitch get access token - php

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.

Related

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']
);

Error in getting access token for Mailchimp. Returns {"error":"invalid_grant"} [duplicate]

This question already has answers here:
MailChimp oauth2 in ASP.NET keeps returning invalid_grant
(3 answers)
Closed 5 years ago.
Got a code and I tried to get access token for it. I made a Curl request and executed it but only got error response as {"error":"invalid_grant"}. Here is my code:
$url = 'https://login.mailchimp.com/oauth2/token';
$grant_type = 'authorization_code';
$client_id = 'MY CLIENT ID';
$client_secret = 'SECRET KEY';
$redirect_url = urlencode('REDIREDT_URL');
$code = $_GET['code'];;
$post_field = array(
'grant_type' => 'authorization_code',
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_url,
'code' => $code,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POST, true);
$value = http_build_query($post_field);
//echo $value; exit;
curl_setopt($ch, CURLOPT_POSTFIELDS, $value);
//echo $post_field;
$result = curl_exec($ch);
curl_close( $ch );
print_r($result); exit;
[From the documentation:][1]
invalid_grant
The provided authorization grant (e.g., authorization
code, resource owner credentials) or refresh token is
invalid, expired, revoked, does not match the redirection
URI used in the authorization request, or was issued to
another client.
I would obtain a new authorization token.
[1]: https://www.rfc-editor.org/rfc/rfc6749#section-5.2

Facebook messenger chatbot response issue

Currently I am developing a simple facebook messenger chatbot. I am using localhost url to tunnel via ngrok. I have also created a facebook app and a page on which bot should run. I also created a webhook for it. Everything was done successfully without any issue. But the problem is I can not get the reply from bot to work. I am receiving user's message but I can not get the bot to reply. So the user is not getting anything as a reply. Although in ngrok web interface I can see that the string which I want the bot to reply is there, but somehow it doesn't get send to the user as a reply. Here is the code for it. Can anyone point out the mistake? here is the ngrok inspect
Here is the code of my php file that is being called.
<?php
if (isset($_GET['hub_verify_token'])) {
if ($_GET['hub_verify_token'] === 'verify_token') {
echo $_GET['hub_challenge'];
return;
} else {
echo 'Invalid Verify Token';
return;
}}$input = json_decode(file_get_contents('php://input'), true);if (isset($input['entry'][0]['messaging'][0]['sender']['id'])) {
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
$jsonData = [
'recipient' => [ 'id' => $sender],
'message' => [ 'text' => $message]
];
$url = "https://graph.facebook.com/v2.8/me/messages?access_token=EAAQlAQ9iGz8BABZATCZAN0hd5eyJ2mCFZBR9rDuZARkEmeqh8obC0yZBpiGxFuNbAyi6HHFI2lZCCiILeFNFDuiy2Sb9OHpLfDSIBhCsv7FgglOrzZAqy9yDFlUTZCEHfRfXBYjZCQOj42Vhl4muvyGIqqqsGDP1a0FYcGo9on3QlzgKp5JL8XbZBx";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($jsonData));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_exec($ch);
curl_close($ch);}?>
I finally get it to work. Here is the code for it.
<?php if (isset($_GET['hub_verify_token'])) {
if ($_GET['hub_verify_token'] === 'new_verify_token') {
echo $_GET['hub_challenge'];
return;
} else {
echo 'Invalid Verify Token';
return;
}}$input = json_decode(file_get_contents('php://input'), true);if(isset($input['entry'][0]['messaging'][0]['sender']['id'])){
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
$jsonData = [
'recipient' => [ 'id' => $sender],
'message' => [ 'text' => $message]
];
$url = "https://graph.facebook.com/v2.8/me/messages?access_token=EAAQlAQ9iGz8BAI5woul1IjMJFVcLW21ZBoZBbeBNaF80wvaPzdZBuDfEJ8NK7PPozUiVNfEjfhZAoWRJAqYHc7yiTA4J1wFOHZCs6DJYcMoPtEBuz6Icw22gNZCSjunjBcUMssXXnkmPEde4J5nU2AarXTUVxsujYPRS7ew97tCiYPDUY4tJSh";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($jsonData));
curl_exec($ch);
curl_close($ch);}?>

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 :)

Google Calendar API with refresh token

My question relates to my previous question where I thought I had solved the issue. I've been able to obtain a refresh_token using scripts I found - including the ones in my previous question.
However now armed with this refresh token I am now trying to do some simple things in the first instance list the events in my test calendar
My problem is that trying to list the events using this URL returns an error - trying to get property of non object. This relates to this line of code:
$cAccessToken = $oToken->access_token;
So I assume there's something wrong in getting the access token.
In the part of my script where I obtained the code I needed to add this code:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
This produced the token- so I added this line to the code getting the access token again but it simply produced a blank page.
I must admit to be very confused with the google API. I tried using the google-client-api code but don't quite get this either - I keep running into brick walls.
Here's my code:
<?php
$cPublisherID = '';
$cScope = 'https://www.google.com/calendar/feeds/';
$cClientID = 'XXXXXX.apps.googleusercontent.com';
$cClientSecret = 'XXXXXX';
$cRedirectURI = 'XXXXXX';
$cAuthCode = 'XXXXXX';
$cRefreshToken = 'XXXXXX';
$bRefresh = true;
if (empty($cAuthCode)) {
$rsParams = array(
'response_type' => 'code',
'client_id' => $cClientID,
'redirect_uri' => $cRedirectURI,
'scope' => $cScope
);
$cOauthURL = 'https://accounts.google.com/o/oauth2/auth?' . http_build_query($rsParams);
echo("Go to\n$cOauthURL\nand enter the given value into \$cAuthCode\n");
exit();
} // ends if (empty($cAuthCode))
elseif (empty($cRefreshToken)) {
$cTokenURL = 'https://accounts.google.com/o/oauth2/token';
$rsPostData = array(
'code' => $cAuthCode,
'client_id' => $cClientID,
'client_secret' => $cClientSecret,
'redirect_uri' => $cRedirectURI,
'grant_type' => 'authorization_code',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $cTokenURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $rsPostData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$cTokenReturn = curl_exec($ch);
$oToken = json_decode($cTokenReturn);
echo("Enter the following values:\n\n");
echo("\$cRefreshToken = '" . $oToken->refresh_token . "';\n");
} // ends
else {
// Get a new Access Token
$cTokenURL = 'https://accounts.google.com/o/oauth2/token';
$rsPostData = array(
'client_secret' => $cClientSecret,
'grant_type' => 'refresh_token',
'refresh_token' => $cRefreshToken,
'client_id' => $cClientID
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $cTokenURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $rsPostData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$cTokenReturn = curl_exec($ch);
$oToken = json_decode($cTokenReturn);
$cAccessToken = $oToken->access_token;
// Get the results
//$cGANURL = 'https://www.googleapis.com/gan/v1beta1/publishers/' . $cPublisherID . '/events';
$rest_url = 'https://www.googleapis.com/calendar/v3/calendars/primary/events';
$cAuthHeader = "Authorization: OAuth " . $cAccessToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array($cAuthHeader));
curl_setopt($ch, CURLOPT_URL, $rest_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$cJsonReturn = curl_exec($ch);
print_r(json_decode($cJsonReturn));
} // ends else from <all authenticated>
?>
I really don't know enough to resolve this - so basically I think I'm getting the tokens I need including the refresh token but not sure how to test and understand what's going on.
I've used the oauth playground and can get results there but not with my own code. I used different codes by the way as I assumed they should be different?

Categories