Hi i am using a different account for google analytics and is returning an error:
GDataauthErrorAuthorizationInvalid Credentials
Though for my previous account is working fine. it could be because i missed some things in the registration process, could anyone give me a detailed steps for the registration to work for oauth 2.0 using api_key for google analytics v2.4
thank you
//returns session token for multiple calls to API
function get_session_token($onetimetoken) {
$output = call_api($onetimetoken, "https://www.google.com/accounts/AuthSubSessionToken");
if(preg_match("/Token=(.*)/", $output, $matches)) {
$sessionToken = $matches[1];
} else {
echo "Error authenticating with Google.";
exit;
}
return $sessionToken;
}
//gets the data
function call_api($sessionToken,$url){
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
if ($_SESSION['authSub']==true){
$curlheader[0] = sprintf("Authorization: AuthSub token=\"%s\"/n", $sessionToken);
} else {
$curlheader[0] = "Authorization: GoogleLogin auth=" . $sessionToken;
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $curlheader);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
$requrlvisits = sprintf("https://www.googleapis.com/analytics/v2.4/data?ids=ga:%s&dimensions=ga:date&metrics=ga:visits,ga:pageviews,ga:bounces,ga:timeOnSite&start-date=%s&end-date=%s&sort=ga:date&key=%s",$get_profid[9],$date1,$date2,$api_key);
// echo $requrlvisits;
$visitsxml = call_api($_SESSION['sessionToken'],$requrlvisits);
$visits = parse_data($visitsxml);
print_r($visitsxml);
Related
I am trying to implement a call back method in PHP. I am successfully calling an instagram API to authorise the user but I do not know how to capture the token after the user authorises.
Below is my code:
public function oAuthBasic()
{
$instagramBasic = new InstagramBasicDisplay([
'appId' => 'xxx',
'appSecret' => 'xxx',
'redirectUri' => 'xxx'
]);
session()->forget('instagramErrorMessage');
$faceBookLoginUrl = $instagramBasic->getLoginUrl();
return response()->json(['redirectUrl' => $faceBookLoginUrl]);
}
This successfully brings up the sign in pop up. However after authorisation, how can I capture the user access token?
Any help is greatly appreciated.
I managed to fix the issue with the help of #CBore's comment:
Created a new route in my web.php
Route::get('linkinstagramBasic','InstagramController#linkBasic')->name('instagram.linkBasic');
Included the URL under Valid OAuth Redirect URIs on facebook app settings page.
Finally wrote the callback:
/*
* Function that works as the call back after Instagram basic display api authorisation
* Get the code and call access_token API
* AUTHOR : DON
* DATE : 12/10/2022
*/
public function linkBasic(InstagramLinkRequest $instagramRequest) {
if (isset($_GET['code'])) {
// Get the OAuth callback code
$code = $_GET['code'];
$ig_atu = "https://api.instagram.com/oauth/access_token";
$ig_data = [];
$ig_data['client_id'] = Config::get('instagram_basic.app_id');
$ig_data['client_secret'] = Config::get('instagram_basic.app_secret');
$ig_data['grant_type'] = 'authorization_code';
$ig_data['redirect_uri'] = Config::get('instagram_basic.redirect_uri');
$ig_data['code'] = $code;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $ig_atu);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($ig_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ig_auth_data = curl_exec($ch);
curl_close($ch);
$ig_auth_data = json_decode($ig_auth_data, true);
dd($ig_auth_data);
//$accessTok = $ig_auth_data['access_token'];
//$UID = $ig_auth_data['user_id'];
//echo "<script>window.close();</script>";
}
}
I had working code in my server, that verified in-app purchases.
There are already 2 days, that my verification started give me a bad response.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalid",
"message": "Invalid Value"
}
],
"code": 400,
"message": "Invalid Value"
}
}
Nothing changed on my side.
(P.S. I'm able to get an access token via refresh, so, I assume I have no problems with my credentials).
Here is the code, that worked OK before.
$product_sku = $_REQUEST['product_sku'];
$transaction_id = $_REQUEST['transaction_id'];
$transaction_time = $_REQUEST['transaction_time'];
$purchase_data = #$_REQUEST['purchase_data'];
$market = $_REQUEST['market'];
$verified = false;
$test_purchase = false;
if (isset($product_sku) && isset($transaction_id) && isset($transaction_time) && isset($market)) {
// If it's GOOGLE
if ($market == '2') {
// verifies if the IAB is correct
if (isset($purchase_data) && $purchase_data != "") {
// Getting necessary data for verification
$client_id = file_get_contents('google_play_developer_api_client_id');
$client_secret = file_get_contents('google_play_developer_api_client_secret');
$refresh_token = file_get_contents('google_play_developer_api_refresh_token');
$refresh_token_url = 'https://accounts.google.com/o/oauth2/token';
$verification_url = "https://www.googleapis.com/androidpublisher/v3/applications/mypackage/purchases/products/" . $product_sku . "/tokens/" . $purchase_data;
// Preparing for the REFRESH_TOKEN request. This need to be changed after Memcache enabling.
// Will be needed to store the ACCESS_TOKEN in the Memcache for the expiration time and after expiring get new ACCESS_TOKEN with REFRESH_TOKEN
// constructing the necessary data for Google authentication
$data_array = array(
"grant_type" => "refresh_token",
"client_id" => $client_id,
"client_secret" => $client_secret,
"refresh_token" => $refresh_token
);
// replacing '\/' with '/' as after json_encode() the '/' in the array values will be replaced with '\/'
$data_array = str_replace("\/", "/", json_encode($data_array));
// contracting Headers for the REFRESH_TOKEN request
$headers = array(
'APIKEY: 111111111111111111111',
'Content-Type: application/json'
);
// making REFRESH_TOKEN request and getting the new ACCESS_TOKEN
$make_call = callAPI('POST', $refresh_token_url, $data_array, $headers);
$response = json_decode($make_call, true);
if (array_key_exists("access_token", $response)) {
$accessToken = $response["access_token"];
// preparing for the Verification request
// adding necessary headers
array_push($headers, "Authorization: OAuth " . $accessToken, "Accept: application/json");
// making Verification request and getting the receipt from Google
$make_call = callAPI('GET', $verification_url, false, $headers);
$receipt = json_decode($make_call, true);
if (array_key_exists("purchaseState", $receipt)) {
// checking for the test purchase or for the purchase made using promo code.
// if purchaseType exists in the receipt the it is test purchase or the purchase made using promo code
// purchaseType = 0 -> Test Purchase, purchaseType = 1 -> Purchase made using promo code
if (array_key_exists("purchaseType", $receipt)) {
$purchaseType = $receipt["purchaseType"];
$test_purchase = $purchaseType == 0;
}
// Getting the purchaseState from the receipt.
// purchaseState = 0 -> Successfull purchase, purchaseState = 0 -> Canceled purchase
$purchaseState = $receipt["purchaseState"];
// Getting Order Id from the receipt
$order_id = $receipt["orderId"];
// Getting Purchase Time from the receipt. Time in millis from the Unix Epoch
$purchaseTimeMillis = $receipt["purchaseTimeMillis"];
// Verifying the purchase
// Verification is failed for any of the following reasons
// 1. Test purchase or the purchase made using promo code
// 2. Canceled Purchase
// 3. If the order id from receipt and the transaction id from the mobile app are different
// 4. If the PurchaseTime from the receipt and the Transaction Time from the mobile are different
// If all conditions are true, the purchase is verified.
$verified = ($purchaseState == 0 && $order_id == $transaction_id && $purchaseTimeMillis == $transaction_time);
} elseif(!array_key_exists("error", $receipt)){
// Something went wrong, let's set the verified to true, so we don't know if it is cheating
$verified = true;
}
} else {
// Something went wrong, let's set the verified to true, so we don't know if it is cheat
$verified = true;
}
}
} else {
// Changed this, while adding verification for other platforms
$verified = true;
}
$verified = $verified ? 1 : 0;
$test_purchase = $test_purchase ? 1 : 0;
// Updating verified and test Purchase fields in the payment_transaction table
// The default value is 1, so no need for updating , if the payment is verified
if ($verified == 0 || $test_purchase == 1) {
dbQuery("UPDATE payment_transaction SET verified=$verified, test_purchase=$test_purchase WHERE user_id=$user_id AND txnid='$transaction_id'", $user_id);
}
$output['status'] = 'ok';
$output['verified'] = $verified;
$output['test_purchase'] = $test_purchase;
}
echo json_encode($output);
function callAPI($method, $url, $data = false, $headers = null)
{
$curl = curl_init();
switch ($method) {
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "GET":
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// OPTIONS:
curl_setopt($curl, CURLOPT_URL, $url);
if ($headers) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// EXECUTE:
$result = curl_exec($curl);
if (! $result) {
die("Connection Failure");
}
curl_close($curl);
return $result;
}
?>
Any Ideas what may be the reason for the bad response?
I have tried to generate a new refresh token, but the result is the same. (
Ok. I found the problem. The PurchaseToken was incorrect in my case.
BTW, the Error Code 400 means that the authentication is ok , but some data is invalid. In my case, it was the PurchaseToken.
I have successfully done oauth1.0 authentication for the get methods provided in the api document
http://api.seatseller.travel/docs/interface.html
But I am getting issue in blockticket url in the above document URL : http://api.seatseller.travel/blockTicket. I need to post the parameters along .I have used Oauth1.0 2Leg library in codeigniter.But its giving me the error as :
ExceptionRequest failed with code 401: Error: OAUTH verification
failed.
Take reference of this url for Oauth library. https://github.com/jesstelford/OAuth-PHP
In codeigniter/application/helpers I have created a helper in that I coded
include_once APPPATH . 'libraries/OAuth/OAuthStore.php';
include_once APPPATH . 'libraries/OAuth/OAuthRequester.php';
function getbusUrlPost($url,$data) {
$key = 'key';
$secret = 'secret';
$options = array('consumer_key' => $key, 'consumer_secret' => $secret);
OAuthStore::instance("2Leg", $options);
$method = "POST";
$params =$data;
//var_dump($params);
try
{
// Obtain a request object for the request we want to make
$request = new OAuthRequester($url, $method,$params);
$result = $request->doRequest(0);
// Sign the request, perform a curl request and return the results,
// throws OAuthException2 exception on an error
// $result is an array of the form: array ('code'=>int,
'headers'=>array(), 'body'=>string)
$result = $request->doRequest();
$response = $result['body'];
if ($response !=
'oauth_token=requestkey&oauth_token_secret=requestsecret')
{
echo $response;
}
else
{
ECHO '------';
}
}
catch(OAuthException2 $e)
{
echo "Exception" . $e->getMessage();
}
}
in controller:
<?php
include_once APPPATH . 'libraries/REST_Controller.php';
class BusBooking extends Rest_Controller {
public function get_bus_blockTicket_post() {
if(isset($_REQUEST['availableTripID']) &&
isset($_REQUEST['seatname'])
&& isset($_REQUEST['fare']) &&
isset($_REQUEST['ladiesSeat'])
&& isset($_REQUEST['name']) && isset($_REQUEST['mobile'])
&& isset($_REQUEST['title'])
&& isset($_REQUEST['email']) && isset($_REQUEST['age']) &&
isset($_REQUEST['gender'])){
$url="http://api.seatseller.travel/blockTicket";
$data=array(
'availableTripID'=>$_REQUEST['availableTripID'],
'seatname'=>$_REQUEST['seatname'],
'fare'=>$_REQUEST['fare'],
'ladiesSeat'=>$_REQUEST['ladiesSeat'],
'name'=>$_REQUEST['name'],
'mobile'=>$_REQUEST['mobile'],
'title'=>$_REQUEST['title'],
'email'=>$_REQUEST['email'],
'age'=>$_REQUEST['age'],
'gender'=>$_REQUEST['gender']
);
$sources= getbusUrlPost($url, $data);
}
}
I have also tried with curl. But getting same error.Check the following code with curl.
function getBusblock($data) {
$url="http://api.seatseller.travel/blockTicket";
$header[]= 'Content-Type: application/x-www-form-urlencoded';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS,
array('oauth_consumer_key'=>"key",'oauth_signature_method'=>"HMAC-
SHA1",'oauth_timestamp'=>'1557752217','oauth_nonce'=>'5cd969995be23','oauth_version'=>'1.0','oauth_signature'=>'DsMdvOOUI57VTkx5VQokUmi9rvw%3D&'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
if(curl_error($ch))
{
echo 'error:' . curl_error($ch);
}
echo "<pre>";
echo json_encode($result);
echo "</pre>";
exit;
}
Please help me.I have tried much but I am getting Oauth verification failed issue.
I am expecting response in json format with all the ticket details .But getting this output :
ExceptionRequest failed with code 401: Error: OAUTH verification failed.
when hitted webservice with postman.
Use
CURLOPT_HTTPHEADER
instead of
CURLOPT_POSTFIELDS
I m trying to get access to the linkedin api but like a lot of people, fail everytime and have this following message of error :
missing required parameters, includes an invalid parameter value, parameter more then once. : Unable to retrieve access token : appId or redirect uri does not match authorization code or authorization code expired
I've cheked the hosting server's timestamp and i revoke and create the token on the app admin before i launch the code (the faster i can due to the short life time of the authorization code given).
Here's my index file and just after the functions i use :
<?php
// VARS
define('API_KEY', 'xxxxxxxxxx');
define('API_SECRET', 'xxxxxxxxxx');
define('REDIRECT_URI', 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME']);
define('SCOPE', 'r_basicprofile');
session_name('linkedin');
session_start();
include('lib/functions.php');
// OAuth 2 Control Flow
if (isset($_GET['error'])) {
// LinkedIn returned an error
print $_GET['error'] . ': ' . $_GET['error_description'];
exit;
}
elseif (isset($_GET['code'])) {
// User authorized your application
getAccessToken();
}
else {
if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
// Token has expired, clear the state
$_SESSION = array();
}
if (empty($_SESSION['access_token'])) {
// Start authorization process
getAuthorizationCode();
}
}
// Congratulations! You have a valid token. Now fetch your profile
$user = fetch('GET', '/v1/people/~:(firstName,lastName)');
print "Hello $user->firstName $user->lastName.";
?>
And the functions :
<?php
function getAuthorizationCode() {
$params = array('response_type' => 'code',
'client_id' => API_KEY,
'scope' => SCOPE,
'state' => uniqid('', true), // unique long string
'redirect_uri' => REDIRECT_URI
);
// Authentication request
$url = 'https://www.linkedin.com/uas/oauth2/authorization?'.http_build_query($params);
// Needed to identify request when it returns to us
$_SESSION['state'] = $params['state'];
// Redirect user to authenticate
header("Location: $url");
exit;
}
function getAccessToken() {
$params = array('grant_type' => 'authorization_code',
'client_id' => API_KEY,
'client_secret' => API_SECRET,
'code' => $_GET['code'],
'redirect_uri' => REDIRECT_URI
);
var_dump($params);
// Access Token request
//$url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
$url = 'https://www.linkedin.com/uas/oauth2/accessToken';
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_HEADER, false);
curl_setopt($c, CURLOPT_POST,true);
curl_setopt($c, CURLOPT_POSTFIELDS, http_build_query($params));
$response = curl_exec($c); // on execute la requete
curl_close($c);
// Native PHP object, please
$token = json_decode($response);
// Store access token and expiration time
$_SESSION['access_token'] = $token->access_token; // guard this!
$_SESSION['expires_in'] = $token->expires_in; // relative time (in seconds)
$_SESSION['expires_at'] = time() + $_SESSION['expires_in']; // absolute time
// DEBUG //
echo 'Retour get access token : </br>';
var_dump($token);
echo '</br>--------------------------</br></br>';
// ! DEBUG //
return true;
}
function fetch($method, $resource, $body = '') {
$params = array('oauth2_access_token' => $_SESSION['access_token'], 'format' => 'json');
// Need to use HTTPS
//$url = 'https://api.linkedin.com' . $resource . '?' . http_build_query($params);
// Tell streams to make a (GET, POST, PUT, or DELETE) request
$url = 'https://api.linkedin.com' . $resource;
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_HEADER, false);
curl_setopt($c, CURLOPT_POSTFIELDS,http_build_query($params));
$response = curl_exec($c);
curl_close($c);
// DEBUG //
echo 'Retour fetch : </br>';
var_dump($response);
echo '</br>--------------------------</br></br>';
// ! DEBUG //
// Native PHP object, please
return json_decode($response);
}
?>
I tried many things but it never works. If someone see the issue tnaks a lot in advance.
Thanks
I have faced the same problem and my issue was caused by http_build_query() function, http://www.php.net/manual/en/function.http-build-query.php
for some reason it tries to encode the parameters to build a query string that will be used by the Linkedin services, if you try to construct the string manually it will pass and it will work.
and actually I reached this page while searching to figure out if its a PHP version issue or maybe the function http_build_query() take in account some environment variables like encoding and locale settings.
not sure but this fixed my issue.
i want to get user's inbox of youtube and send a video messsage. below is the code i am using to retrieve inbox. inbox comes shows that inbox of user XXXX but inbox is empty, no messages comes. while i have four video messages in my inbox.
$developer_key='REPLACE_ME';
$client_id= 'REPLACE_ME';
$client_secret='REPLACE_ME';
// error checking; user might have denied access
if (isset($_GET['error'])) {
if ($_GET['error'] == 'access_denied') {
echo('You have denied access. Click here to retry…');
} else {
echo("An error has occurred: ". $_GET['error']);
}
exit;
}
// Step 1: redirect to google account login if necessary
if(!isset($_GET['code']) || $_GET['code'] === '') {
Header('Location: https://accounts.google.com/o/oauth2/auth?client_id='. $client_id .
'&redirect_uri=http://localhost:8080/Test/sendMessage.php' .
'&scope=https://gdata.youtube.com&response_type=code&access_type=offline',
true, 307);
exit;
}
$authorization_code= $_GET['code'];
// Step 2: use authorization code to get access token
$url = "https://accounts.google.com/o/oauth2/token";
$message_post= 'code='. $authorization_code .
'&client_id='. $client_id .
'&client_secret='. $client_secret .
'&redirect_uri=http://localhost:8080/Test/sendMessage.php' .
'&grant_type=authorization_code';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message_post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
echo "<pre>";
echo "<br><br> message_post : ";
print_r($result);
if ($cur_error= curl_error($ch)) {
echo($cur_error);
curl_close($ch);
exit;
}
curl_close($ch);
$jsonArray= json_decode($result, true);
if ($jsonArray === null) {
echo("Could not decode JSON.");
exit;
}
if (isset($jsonArray['error'])) {
echo("An error has occurred: ". $jsonArray['error']);
exit;
}
if (!isset($jsonArray['access_token'])) {
echo("Access token not found.");
exit;
}
//The user's authentication token
$access_token= $jsonArray['access_token'];
$title ='krishna'; //The title of the caption track
$lang = 'en'; //The languageof the caption track
//$transcript = $_REQUEST['transcript']; //The caption file data
$inboxUrl ='https://gdata.youtube.com/feeds/api/users/default/inbox?alt=json&&key=AIzaSyBeh0Aevex7q3iRIY5bV3N9gx0WAkNBMi4&access_token=' . $access_token;
echo $inboxUrl . "<br />";
$homepage = file_get_contents($inboxUrl);
echo "file content : <pre>";
print_r($homepage);
YouTube's video responses feature has been retired as explained in
this announcement. While existing video responses are still available,
YouTube no longer supports the ability to retrieve a list of video
responses for a video, to upload new video responses, or to delete
video responses, though you can delete the video that was used in a
video response. Consequently, these functions are also no longer
supported in the API.
https://developers.google.com/youtube/2.0/developers_guide_protocol_video_responses