Is impossible to connect with webmaster tools using OAuth 2.0? - php

I managed to connect via Oauth 2 with Analytics but can not find the way to do it with webmaster tools.
I got the "scope" of webmaster tools at: https://developers.google.com/oauthplayground/
and I'm using the code here:
https://code.google.com/p/google-api-php-client/
but I can not work me. If anyone can guide me would be grateful.
PS: May this year XD

following code will help to get access token and refresh token for webmaster tools API access through Oauth Flow
Make sure that the Redirect Uri that you have mentioned in your API console should be same as the filename in which you will place the following code.
For eg. If the redirect uri is:-somesitename.com/google_oauth.php(with http:// or https://) then following script should be placed in :- google_oauth.php (path:somesitename.com/google_oauth.php (with http:// or https://))
<?php
$OAuth = array(
'oauth_uri' => 'https://accounts.google.com/o/oauth2/auth',
'client_id' => '#clientId',
'client_secret' => '#clientSecret',
'access_type' => 'offline',
'redirect_uri' => 'http://somesite.com/google_oauth.php', //this url should be same as you had registered in your api console as redirect uri()
'oauth_token_uri' => 'https://accounts.google.com/o/oauth2/token'
);
$token = array(
'access_token' => '',
'token_type' => '',
'expires_in' => '',
'refresh_token' => ''
);
$title = 'No Code';
$AuthCode = 'Null';
// see if error parameter exisits
$error = _get_url_param($_SERVER['REQUEST_URI'], 'error');
if ($error != NULL)
{ // this means the user denied api access to GWMTs
$title = $error;
}
else
{ // does the code parameter exist?
$AuthCode = _get_url_param($_SERVER['REQUEST_URI'], 'code');
if ($AuthCode == NULL)
{ // get authorization code
$OAuth_request = _formatOAuthReq($OAuth, "https://www.google.com/webmasters/tools/feeds/");
header('Location: ' . $OAuth_request);
exit; // the redirect will come back to this page and $code will have a value
}
else
{
$title = 'Got Authorization Code';
// now exchange Authorization code for access token and refresh token
$token_response = _get_auth_token($OAuth, $AuthCode);
$json_obj = json_decode($token_response);
$token['access_token'] = $json_obj->access_token;
$token['token_type'] = $json_obj->token_type;
$token['expires_in'] = $json_obj->expires_in;
$token['refresh_token'] = $json_obj->refresh_token;
echo 'access_token = ' . $json_obj->access_token;
}
}
function _get_auth_token($params, $code)
{
$url = $params['oauth_token_uri'];
$fields = array(
'code' => $code,
'client_id' => $params['client_id'],
'client_secret' => $params['client_secret'],
'redirect_uri' => $params['redirect_uri'],
'grant_type' => 'authorization_code'
);
$response = _do_post($url, $fields);
return $response;
}
function _do_post($url, $fields)
{
$fields_string = '';
foreach ($fields as $key => $value)
{
$fields_string .= $key . '=' . $value . '&';
}
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function _formatOAuthReq($OAuthParams, $scope)
{
$uri = $OAuthParams['oauth_uri'];
$uri .= "?client_id=" . $OAuthParams['client_id'];
$uri .= "&redirect_uri=" . $OAuthParams['redirect_uri'];
$uri .= "&scope=" . $scope;
$uri .= "&response_type=code";
$uri .= "&access_type=offline";
return $uri;
}
function _get_url_param($url, $name)
{
parse_str(parse_url($url, PHP_URL_QUERY), $params);
return isset($params[$name]) ? $params[$name] : null;
}
function _get_refresh_token($params, $code)
{
$url = $params['oauth_token_uri'];
$fields = array(
'code' => $code,
'client_id' => $params['client_id'],
'client_secret' => $params['client_secret'],
'refresh_token' => $token['refresh_token'],
'grant_type' => 'refresh_token'
);
$response = _do_post($url, $fields);
return $response;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><?= $title; ?></title>
</head>
<body>
<h1>OAuth2 Authorization Code</h1>
<p>Authorization Code: <?= $AuthCode; ?></p>
<p>access token: <?= $token['access_token']; ?></p>
<p>expires in: <?= $token['expires_in']; ?></p>
<p>refresh token: <?= $token['refresh_token']; ?></p>
<p></p>
</body>
</html>
You can then use this token to query webmaster tools API for data.
Also you can use the same code that you have used for your Oauth analytics access,just replace this url:https://www.googleapis.com/auth/analytics.readonly with https://www.google.com/webmasters/tools/feeds/ in your oauth code that you are using for analytics while querying webmaster tools API data.

Related

snapchat login kit web: invalid grant, invalid code verifier

I am using Snapchat login kit web in my PHP project. I successfully connected the user-authorization page. After giving authorization I am getting code and state GET variables in my redirect_uri page. I need an access token, but when I proceed next step, I got an error in response,
1.invalid_grant
2.invalid code_verifier
here are my login page and redirect page code:
--Login page---
<?php
if(isset($_POST['login']))
{
$url="https://accounts.snapchat.com/accounts/oauth2/auth";
$clientId="my_client_id_get_from_snapchat_app_setting";
$client_secret="my_client_secrect_get_from_snapchat_app_setting";
$redirectUri="https://Snapreport.org/Redirect.php";
$method= "GET";
$str = 'arifusingsnapchat';
$state= base64_encode($str);
$code_verifier = "arifusingsnapchat225678909fghh8df777634567890";
$code_verifier_hash = hash("sha256",$code_verifier);
$code_challenge = base64_encode($code_verifier_hash);
$scopeList= array("https://auth.snapchat.com/oauth2/api/user.display_name",
"https://auth.snapchat.com/oauth2/api/user.bitmoji.avatar",
"https://auth.snapchat.com/oauth2/api/user.external_id"
);
$scope = implode($scopeList," ");
$stringArr = array(
"client_id" => $clientId,
"client_secret" => $client_secret,
"redirect_uri" => $redirectUri,
"code_challenge" => $code_challenge,
"code_challenge_method"=> "S256",
"response_type" => "code",
"scope" => $scope,
"state" => $state );
$query= http_build_query($stringArr, '', '&');
$request = $url."?".$query;
header("Location:".$request);
}
?>
--Redirect_uri page--
<?php
if(isset($_GET['code']) && isset($_GET['state']))
{
$code= $_GET['code'];
$state=$_GET['state'];
$url="https://accounts.snapchat.com/accounts/oauth2/token";
$clientId="my_client_id_get_from_snapchat_app_setting";
$client_secret="my_client_secrect_get_from_snapchat_app_setting";
$redirect_uri="https://Snapreport.org/Redirect.php";
$header = base64_encode($clientId.":".$client_secret);
$code_verifier = "arifusingsnapchat225678909fghh8df777634567890";
$payloaded_url=$url."?client_id=".$clientId."&client_secret=".$client_secret."&grant_type=authorization_code&redirect_uri=".$redirect_uri."&code=".$code."&code_verifier=".$code_verifier;
$ch = curl_init($payloaded_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type' => 'application/json',
'Authorization'=> 'Basic '.$header
));
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
$res= json_decode($response);
// do anything you want with your response
echo "<pre>";
var_dump($res);
echo "</pre>";
}
Snapchat Login Kit Web Documentation
Snapchat Login Kit Web Documentationhttps://kit.snapchat.com/docs/login-kit-web
On your login page:
$code_verifier_hash = urlencode(pack('H*', hash('sha256', $code_verifier)))
You should probably also use a B64 safe url encoder like the one here:
https://github.com/F21/jwt/blob/master/JWT/JWT.php#L120

PHP Discord OAUTH2 code sample not working

So this code I found below doesn't work I get to the authenticate screen then when t redirects me it just says Not logged in, Login in again. Does anyone know what I have to do to fix this? I am not very good at OATH2 and would like someone to walk me through.
I used the code from this gist.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('max_execution_time', 300); //300 seconds = 5 minutes. In case if your CURL is slow and is loading too much (Can be IPv6 problem)
error_reporting(E_ALL);
define('OAUTH2_CLIENT_ID', '1234567890');
define('OAUTH2_CLIENT_SECRET', 'verysecretclientcode');
$authorizeURL = 'https://discord.com/api/oauth2/authorize';
$tokenURL = 'https://discord.com/api/oauth2/token';
$apiURLBase = 'https://discord.com/api/users/#me';
session_start();
// Start the login process by sending the user to Discord's authorization page
if(get('action') == 'login') {
$params = array(
'client_id' => OAUTH2_CLIENT_ID,
'redirect_uri' => 'https://yoursite.location/ifyouneedit',
'response_type' => 'code',
'scope' => 'identify guilds'
);
// Redirect the user to Discord's authorization page
header('Location: https://discordapp.com/api/oauth2/authorize' . '?' . http_build_query($params));
die();
}
// When Discord redirects the user back here, there will be a "code" and "state" parameter in the query string
if(get('code')) {
// Exchange the auth code for a token
$token = apiRequest($tokenURL, array(
"grant_type" => "authorization_code",
'client_id' => OAUTH2_CLIENT_ID,
'client_secret' => OAUTH2_CLIENT_SECRET,
'redirect_uri' => 'https://yoursite.location/ifyouneedit',
'code' => get('code')
));
$logout_token = $token->access_token;
$_SESSION['access_token'] = $token->access_token;
header('Location: ' . $_SERVER['PHP_SELF']);
}
if(session('access_token')) {
$user = apiRequest($apiURLBase);
echo '<h3>Logged In</h3>';
echo '<h4>Welcome, ' . $user->username . '</h4>';
echo '<pre>';
print_r($user);
echo '</pre>';
} else {
echo '<h3>Not logged in</h3>';
echo '<p>Log In</p>';
}
if(get('action') == 'logout') {
// This must to logout you, but it didn't worked(
$params = array(
'access_token' => $logout_token
);
// Redirect the user to Discord's revoke page
header('Location: https://discordapp.com/api/oauth2/token/revoke' . '?' . http_build_query($params));
die();
}
function apiRequest($url, $post=FALSE, $headers=array()) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
if($post)
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$headers[] = 'Accept: application/json';
if(session('access_token'))
$headers[] = 'Authorization: Bearer ' . session('access_token');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
return json_decode($response);
}
function get($key, $default=NULL) {
return array_key_exists($key, $_GET) ? $_GET[$key] : $default;
}
function session($key, $default=NULL) {
return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;
}
?>
EDIT: Basically in the if statement it doesn't go into the logged-in part.
Here is a working solution
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
$SecretHERE = "";
$IDHERE = "";
if (isset($_GET["error"])) {
echo json_encode(array("message" => "Authorization Error"));
} elseif (isset($_GET["code"])) {
$redirect_uri = "https://www.devtest.net/v4/login.php";
$token_request = "https://discordapp.com/api/oauth2/token";
$token = curl_init();
curl_setopt_array($token, array(
CURLOPT_URL => $token_request,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
"grant_type" => "authorization_code",
"client_id" => $IDHERE,
"client_secret" => $SecretHERE,
"redirect_uri" => $redirect_uri,
"code" => $_GET["code"]
)
));
curl_setopt($token, CURLOPT_RETURNTRANSFER, true);
$resp = json_decode(curl_exec($token));
curl_close($token);
if (!isset($_SESSION['user']) || !isset($_SESSION['userguilds'])) {
if (isset($resp->access_token)) {
$access_token = $resp->access_token;
$info_request = "https://discordapp.com/api/users/#me";
$info_request_guilds = "https://discord.com/api/users/#me/guilds";
$info = curl_init();
curl_setopt_array($info, array(
CURLOPT_URL => $info_request,
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer {$access_token}"
),
CURLOPT_RETURNTRANSFER => true
));
$user = json_decode(curl_exec($info));
curl_close($info);
// GUILDS REQUEST
$info_guilds = curl_init();
curl_setopt_array($info_guilds, array(
CURLOPT_URL => $info_request_guilds,
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer {$access_token}"
),
CURLOPT_RETURNTRANSFER => true
));
$guilds = json_decode(curl_exec($info_guilds));
curl_close($info_guilds);
$_SESSION['user'] = $user;
if ($_SESSION['user']->verified == 1) {
$_SESSION['userguilds'] = $guilds;
$_SESSION['avatar'] = "https://cdn.discordapp.com/avatars/" . $user->id . "/" . $user->avatar . ".png";
header("Location: https://www.devtest.net/v4/fork.php");
die();
}else{
print_r("Please verify your Discord Account.");
session_destroy();
die();
}
} else {
echo json_encode(array("message" => "Authentication Error"));
}
} else{
// They are already logged in so redirect them to fork.php
header("Location: https://www.devtest.net/v4/fork.php");
die();
}
} else {
// Redirect to Discord Oauth2 URL (CAN BE FOUND IN DISCORD DEV PORTAL)
header('location: https://discord.com/api/oauth2/authorize?client_id=CLIENTIDHERE&redirect_uri=https%3A%2F%2Fwww.devtest.net%2Fv4%2Flogin.php&response_type=code&scope=identify%20email%20connections%20guilds%20guilds.join');
die();
}
?>

Apple Sign In used retails

I've implemented the Apple Sign In on the website, but I can't retrieve user's full name. It's added to scope but is not being posted (it's being sent only the first time). Is there a way to get it somehow?
Frontend:
<div class="login-btn" id="appleid-signin" data-color="black" data-border="true" data-type="sign in"></div>
<script type="text/javascript"
src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js"></script>
<script type="text/javascript">
AppleID.auth.init({
clientId: 'net.exmample.oauth',
scope: 'email name',
response_type: 'code',
response_mode: 'form_post',
redirectURI: 'https://example.net/appletest',
usePopup : false
});
const buttonElement = document.getElementById('appleid-signin');
buttonElement.addEventListener('click', () => {
AppleID.auth.signIn();
});
</script>
Backend:
$identityToken = Input::post('id_token');
$appleSignInPayload = ASDecoder::getAppleSignInPayload($identityToken);
$email = $appleSignInPayload->getEmail();
var_dump('email: ' . $email);
echo '<br>';
$user = $appleSignInPayload->getUser();
var_dump('userid: ' . $user);
echo '<br>';
$isValid = $appleSignInPayload->verifyUser($user);
echo 'is valid : ';
var_dump($isValid);
echo '<br>';
$clientId = 'net.example.oauth';
$teamId = 'TT123';
$keyId = 'KK123';
$code = Input::post('code');
echo 'Code: ' . $code . '<br>';
$claims = [
'iss' => $teamId,
'aud' => 'https://appleid.apple.com',
'sub' => $clientId,
'iat' => time(),
'exp' => time() + 3600,
];
$headers = ['kid' => $keyId, 'alg' => 'ES256'];
$privateKey = <<<EOD-----BEGIN PRIVATE KEY-----key goes here-----END PRIVATE KEY-----EOD;
$publicKey = <<<EOD-----BEGIN PUBLIC KEY-----key goes here-----END PUBLIC KEY-----EOD;
$client_secret = JWT::encode($claims, $privateKey, 'ES256', $keyId, $headers);
// var_dump($client_secret);
$decoded = JWT::decode($client_secret, $publicKey, ['ES256']);
// var_dump($decoded);
$ch = curl_init();
$data = [
'client_id' => $clientId, // app id?
'code' => $code, //from request
'client_secret' => $client_secret,
'grant_type' => 'authorization_code',
'redirect_uri' => 'https://example.net/appletest'
];
curl_setopt($ch, CURLOPT_URL, "https://appleid.apple.com/auth/token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close($ch);
$response = json_decode($server_output, true);
if ($response['access_token']) {
var_dump($response);
$appleSignInPayload = ASDecoder::getAppleSignInPayload($response['id_token']);
}
Stack overflow requires more details to the code. So I can add that it uses AppleSignIn\ASDecoder and \Firebase\JWT\JWT libraries.
Also I've discovered that in the backend you have to supply same redirect_uri as on the frontend, otherwise you get {"invalid_grant"} error. Hope it saves someone a few hours.
If someone in trouble reads this, here is how to extract public key out of .p8 file: openssl ec -in AuthKey_KEY_ID.p8 -pubout -out AuthKey_KEY_ID_Public.p8
UPD: Seems it's true that name can be obtained only the first time. I've tested it with a friend and got a response.
array(3) {
["code"]=> string(64) "c94b9775110randoma918bc357.0.nsqty.covC4GSS1e2O4..."
["id_token"]=> string(766) "eyJraWQiOiJlWGF1bm1MIiwiYWrandomyNTYifQ.eyJpc3MiOiJodHRwczovL2FwcGxlaW..."
["user"]=> string(82) "{"email":"e.g#example.net","name":{"firstName":"Eeee","lastName":"Ggg"}}" }
UPD 2:
It's possible to delete application using the mobile phone in Settings->Passwords & Security->Apps Using Your Apple ID. After the deletion user data will be posted again. But it's only good for testing updating user data on production still requires profile update over time.
UPD 3:
It's possible to unbind the App from your apple account not only by phone, but also on the https://appleid.apple.com/account/manage website in the Security->APPS & WEBSITES USING APPLE ID->Manage section

get user detail from github after authentication

I have a sign-in page that refers a user to GitHub for authentication.
After authenticating GitHub successfully returns the code and status as GET parameters to my sign-in page.
Is there a way to get the GitHub user email, name, and handle after getting the access_token?
if(get('action') == 'login')
{
// Generate a random hash and store in the session for security
$_SESSION['state'] = hash('sha256', microtime(TRUE) . rand() . $_SERVER['REMOTE_ADDR']);
unset($_SESSION['access_token']);
$params = array(
'client_id' => OAUTH2_CLIENT_ID,
'redirect_uri' => 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'],
'scope' => 'user',
'state' => $_SESSION['state']
);
// Redirect the user to Github's authorization page
header('Location: ' . $authorizeURL . '?' . http_build_query($params));
die();
}
// When Github redirects the user back here, there will be a "code" and "state" parameter in the query string
if (get('code'))
{
// Verify the state matches our stored state
if (!get('state') || $_SESSION['state'] != get('state')) {
header('Location: ' . $_SERVER['PHP_SELF']);
die();
}
// Exchange the auth code for a token
$token = apiRequest($tokenURL, array(
'client_id' => OAUTH2_CLIENT_ID,
'client_secret' => OAUTH2_CLIENT_SECRET,
'redirect_uri' => 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'],
'state' => $_SESSION['state'],
'code' => get('code')
));
echo var_dump($token) ."<br>";
echo json_encode($token);
$_SESSION['access_token'] = $token->access_token;
header('Location: ' . $_SERVER['PHP_SELF']);
}
}
function apiRequest($url, $post = FALSE, $headers = array())
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if ($post)
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$headers[] = 'Accept: application/json';
if (session('access_token'))
$headers[] = 'Authorization: Bearer ' . session('access_token');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
return json_decode($response);
}
function get($key, $default = NULL)
{
return array_key_exists($key, $_GET) ? $_GET[$key] : $default;
}
function session($key, $default = NULL)
{
return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;
}
You need to call the Github API with the access token to access the current User
So if you already have the access_token available and it's saved sucessfully in $_SESSION['access_token'] - it will be used automatically for all further requests done by apiRequest() Method Calls
$user = apiRequest("https://api.github.com/user');
var_dump($user);
// $user->name should be available in response
When I tested your code - the apiRequest-Method returned an error (var_dump($response))
Request forbidden by administrative rules. Please make sure your request has a User-Agent header (http://developer.github.com/v3/#user-agent-required). Check https://developer.github.com for other possible causes.
Just add a User-Agent to the headers[] array in the method (e.g. right below the added Accept: Header)
$headers[] = 'User-Agent: PHP Api Call';
... and your API-Call will work ;)
Edit: because you set 'scope' => 'user', in your initial Auth-Request - you requested Access to the User-Data - but nothing more (see OAuth-App-Scopes if you need additional permissions/info)

Cant receive an access token in Stripe

I'm new at Stripe integration. I've read the API documentation for Stripe and here is the OAuth flow. But I still don't receive any OAuth access token. Can someone explain how can I receive an access token? Thanks!
if (isset($_GET['code'])) { // Redirect w/ code
$code = $_GET['code'];
$token_request_body = array(
'grant_type' => 'authorization_code',
'client_id' => 'ca_32D88BD1qLklliziD7gYQvctJIhWBSQ7',
'code' => $code,
'client_secret' => ''
);
$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_32D88BD1qLklliziD7gYQvctJIhWBSQ7'
);
$url = AUTHORIZE_URI . '?' . http_build_query($authorize_request_body);
echo "<a href='$url'>Connect with Stripe</a>";
}
You should use an OAuth 2.0 client library for this instead of attempting to roll this yourself as suggested by Stripe:
https://stripe.com/docs/connect/standalone-accounts#sample-code
There are many of these, but this is a pretty good option:
https://github.com/thephpleague/oauth2-client
You could modify this example and retrieve the account ID like so:
$provider->getResourceOwner($accessToken)->getId();
Once you retrieve the account ID, you'd store and use this to authenticate as the connected account as suggested by Stripe:
https://stripe.com/docs/connect/authentication#authentication-via-the-stripe-account-header
they actually have, what seems like, an official github library
and they have an example for the oauth thing
just missing in the docs for whatever reason...
https://github.com/stripe/stripe-php/blob/master/examples/oauth.php
in case they delete it, i include the file here, note: they make use of their library, so you have to install it prior to this to work
<?php
require('../init.php');
\Stripe\Stripe::setApiKey(getenv('STRIPE_SECRET_KEY'));
\Stripe\Stripe::setClientId(getenv('STRIPE_CLIENT_ID'));
if (isset($_GET['code'])) {
// The user was redirected back from the OAuth form with an authorization code.
$code = $_GET['code'];
try {
$resp = \Stripe\OAuth::token([
'grant_type' => 'authorization_code',
'code' => $code,
]);
} catch (\Stripe\Error\OAuth\OAuthBase $e) {
exit("Error: " . $e->getMessage());
}
$accountId = $resp->stripe_user_id;
echo "<p>Success! Account <code>$accountId</code> is connected.</p>\n";
echo "<p>Click here to disconnect the account.</p>\n";
} elseif (isset($_GET['error'])) {
// The user was redirect back from the OAuth form with an error.
$error = $_GET['error'];
$error_description = $_GET['error_description'];
echo "<p>Error: code=" . htmlspecialchars($error, ENT_QUOTES) . ", description=" . htmlspecialchars($error_description, ENT_QUOTES) . "</p>\n";
echo "<p>Click here to restart the OAuth flow.</p>\n";
} elseif (isset($_GET['deauth'])) {
// Deauthorization request
$accountId = $_GET['deauth'];
try {
\Stripe\OAuth::deauthorize([
'stripe_user_id' => $accountId,
]);
} catch (\Stripe\Error\OAuth\OAuthBase $e) {
exit("Error: " . $e->getMessage());
}
echo "<p>Success! Account <code>" . htmlspecialchars($accountId, ENT_QUOTES) . "</code> is disconnected.</p>\n";
echo "<p>Click here to restart the OAuth flow.</p>\n";
} else {
$url = \Stripe\OAuth::authorizeUrl([
'scope' => 'read_only',
]);
echo "Connect with Stripe\n";
}

Categories