PHP - Stripe Connect return null - php

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

Related

curl not working but not giving any error either

I'm working on Globe Labs API to send an SMS. But before I can send an SMS, the mobile number I want to send message to needs to be subscribed so I can get the access_token which will be used in sending SMS.
There are 2 options to subscribe - via SMS or via Web Form. I was able to use first option without any problem. But I can't make the second option work.
According to the documentation, after the subscriber keyed-in the received confirmation pin on the page and clicked the Confirm button to authorize the subscriber, the page will then be redirected to the redirect_uri of my application, and a Code parameter will be passed(via GET) to it.
Here's the part where I fail to make it work:
To get the access token, you need to do a POST request via https://developer.globelabs.com.ph/oauth/access_token with your ‘app_id’, ‘app_secret’ and ‘code’ as the parameters. The parameters ‘access_token’ and ‘subscriber_number’ will then be returned to your Redirect URI as a response.
Here's my code:
$app_id = '<my_app_id>';
$app_secret = '<my_app_secret>';
$content = array(
'app_id' => $app_id,
'app_secret' => $app_secret,
'code' => $this->input->get('code')
);
$url = 'http://developer.globelabs.com.ph/oauth/access_token';
$this->post_to_url($url, $content);
function post_to_url($url, $data) {
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, count($data));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
curl_close($post);
if(!$result){
die('Error: "' . curl_error($post) . '" - Code: ' . curl_errno($post));
} else {
$this->Sms_Api_model->save_subscriber_data();
}
}
This is my redirect URL: http://api.forexcargo.us/sms_api/globelabs_api?code=[code]
And the result I get:
Error: "" - Code:
EDIT:
I tried to use a form and send my data via method POST and it worked. So it really might be my curl setup.
What am I doing wrong?
Any help is highly appreciated. Thank you!
Apologies for being a newbie regarding curl. Apparently, I had to add the following code to see the errors on my code because the URL I'm using has its error checking disabled:
error_reporting(-1);
ini_set('display_errors', 1);
set_time_limit(0);
And my new code:
function do_post_request($post_data)
{
error_reporting(-1);
ini_set('display_errors', 1);
set_time_limit(0);
$url = 'https://developer.globelabs.com.ph/oauth/access_token';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
if($this->json_validator($response) == 1){
$decode_data = json_decode($response, true);
$post_data_arr = array('access_token' => $decode_data['access_token'], 'subscriber_number' => $decode_data['subscriber_number']);
$this->Sms_Api_model->save_subscriber_data($post_data_arr);
//var_dump(http_response_code(200));
}
}
$content = [
'app_id' => $app_id,
'app_secret' => $app_secret,
'code' => $this->input->get('code')
];
$post_request = $this->do_post_request($content);
Now it's working and I was able to save the data I received in my database. Thank you everyone for your help!

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.

on curl "connect.stripe.com/oauth/token" it will get no response

https://connect.stripe.com/oauth/authorize?response_type=code&client_id=ca_XXXXXXXXXXXXXXXXXXXXXX&scope=read_write
from the above mentioned api I get the code.
$code = $_GET['code'];
from this code I curl this http://connect.stripe.com/oauth/token but the problem is that it is not getting any response
echo $code;
$token_request_body = array(
'grant_type' => 'authorization_code',
'client_id' => 'ca_xxxxxxxxxxxxxxxxxxxxx',
'code' => $code,
'client_secret' => 'XXXXXXXXXXXXXXXXXXX'
);
define("TOKEN_URI", "http://connect.stripe.com/oauth/token");
$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);
echo $respCode;
$resp = json_decode(curl_exec($req), true);
echo $resp;
curl_close($req);
echo $resp['access_token'];
Your code sends the code to the endpoint over plain HTTP which is something that is forbidden by spec and the server should not return the tokens. The example code at stripe.com also shows an HTTPs URL. Switch:
define("TOKEN_URI", "http://connect.stripe.com/oauth/token");
to:
define("TOKEN_URI", "https://connect.stripe.com/oauth/token");
FWIW: the plain HTTP URL actually redirects to HTTPs which is something your client doesn't handle, and it shouldn't since it would be insecure and a violation of the spec.

Access Token still valid for 2 months but API response says #2500

I am trying to upload a photo to user's album with current script:
$this->facebook->api('/me/photos?access_token='.$user->access_token, 'post', $args);
$user->access_token is the user's access token and I check via Facebook Graph API Explorer tool it says still valid (until 2 months).
However if I create API request with script above, my console always returned:
Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user.
What I've been doing is:
deauthorize app
re-authorize app
request permission (publish_stream,photo_upload,user_photos)
update FB SDK to latest version
Here is the full code:
$user = $this->User_model->get_access_token($this->input->post('fb_id'));
foreach($this->input->post('media') as $media_id)
{
$media = $this->Media_model->get_media($media_id);
$args = array('message' => 'Photo Caption');
$args['image'] = '#' . realpath(FCPATH.'uploads/booth_1/'.$media->file);
$data = $this->facebook->api('/me/photos?access_token='.$user->access_token, 'post', $args);
print_r($data);
}
Any help?
FYI I am using codeigniter. And actually I was trying hours ago (it worked), however, now is not, because of access_token.
Thanks.
I solved it manually by NOT using built-in $facebook->api() but I am using curl instead.
$filename = '#' . realpath(FCPATH.'uploads/'.$media);
$url = "https://graph.facebook.com/".$user->fb_id."/photos";
$ch = curl_init($url);
$attachment = array('access_token' => $user->access_token,
'app_id' => APP_ID,
'name' => "Upload",
'fileUpload' => true,
'message' => "Message",
'image' => $filename,
);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_CAINFO, PATH TO FB SDK CERT FOR SSL);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$result = curl_exec($ch);
if ($result === FALSE) {
die("Curl failed: " . curl_error($ch));
}
curl_close ($ch);

PHP. How to get the access token. Authenticating with OAuth 2.0 for Google API

I found this function that supposedly gets the accessToken, but I get nothing.
I do have the $_REQUEST['code'], and the other information needed in this function.
Any ideas what is wrong here?
Thanks.
//Oauth 2.0: exchange token for session token so multiple calls can be made to api
if(isset($_REQUEST['code'])){
$_SESSION['accessToken'] = get_oauth2_token($_REQUEST['code']);
}
//returns session token for calls to API using oauth 2.0
function get_oauth2_token($code) {
global $client_id;
global $client_secret;
global $redirect_uri;
$oauth2token_url = "https://accounts.google.com/o/oauth2/token";
$clienttoken_post = array(
"code" => $code,
"client_id" => $client_id,
"client_secret" => $client_secret,
"redirect_uri" => $redirect_uri,
"grant_type" => "authorization_code"
);
$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;
}
This is what I did to get my access token and refresh token.
Create a file that contains the following code :
<?php
if (isset($_GET['code'])) {
// try to get an access token
$code = $_GET['code'];
$url = 'https://accounts.google.com/o/oauth2/token';
$params = array(
"code" => $code,
"client_id" => YOUR_CLIENT_ID,
"client_secret" => YOUR_CLIENT_SECRET,
"redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
"grant_type" => "authorization_code"
);
$ch = curl_init();
curl_setopt($ch, constant("CURLOPT_" . 'URL'), $url);
curl_setopt($ch, constant("CURLOPT_" . 'POST'), true);
curl_setopt($ch, constant("CURLOPT_" . 'POSTFIELDS'), $params);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] === 200) {
header('Content-Type: ' . $info['content_type']);
return $output;
} else {
return 'An error happened';
}
} else {
$url = "https://accounts.google.com/o/oauth2/auth";
$params = array(
"response_type" => "code",
"client_id" => YOUR_CLIENT_ID,
"redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
"scope" => "https://www.googleapis.com/auth/plus.me"
);
$request_to = $url . '?' . http_build_query($params);
header("Location: " . $request_to);
}
Now, replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with your client ID and client secret.
Make sure your scope is correct. For example, it should be https://www.googleapis.com/auth/analytics if you want to get access to Analytics.
If you run the file, you should get an OAuth2 approval screen.
If you now press Accept, you should get a result that looks like this:
{
"access_token" : YOUR_ACCESS_TOKEN,
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : YOUR_REFRESH_TOKEN
}
The result may contain additional fields, depending on which scope you're applying for.
I don't see anything wrong with your code, but you may want to try refreshing the client secret and see if that helps. Additionally, I would suggest you see exactly what the response is coming back from your curl command, I suspect it's "invalid_grant".
A much better way to do this is to use google's php api client:
https://code.google.com/p/google-api-php-client/
which handles most of the communication for you. The examples there are very easy to use. It mostly depends on which google service you are trying to access.
that code looks familiar - I'm using roughly the same code - there are two things you can try.
Use echo to echo the response to the Browser
echo $json_response;
Get hold of Fiddler and use the following line before the call to curl_exec
curl_setopt($curl, CURLOPT_PROXY, '127.0.0.1:8888');
'fraid I've not got it working either - the response I am getting is
{
"error" : "invalid_request"
}
Now if anyone knows how what is wrong with this ;)
From section 4.4.2 of "The OAuth 2.0 Authorization Protocol draft-ietf-oauth-v2-20"
The client makes a request to the token endpoint by adding the
following parameters using the "application/x-www-form-urlencoded"
format in the HTTP request entity-body:
So the POSTed parameters should be submitted in the form of a string, not an array. This is mentioned in the PHP manual for curl_setopt too.
So instead of posting $clienttoken_post, you might want to post http_build_query($clienttoken_post,'','&').
This might not solve all your problems, but it's probably a step in the right direction.
I had the same error, and I found that adding
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
to allow the request follow a redirect solved it quickly. I hope that helps someone else!

Categories