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?
Related
Im trying to connect to the API services of 2ba. Somehow I just can't connect. I get the error: error: "invalid_client"
I dont know what to try, it feels like I need to hash my cliend_secret or complete url but I dont see that in the documentation.
This is my code (PHP):
<?php
// ---- GET TOKEN ----
// Base url for all api calls.
$baseURL = 'https://authorize.2ba.nl';
// Specified url endpoint. This comes after the baseUrl.
$endPoint = '/OAuth/Token';
// Parameters that are required or/and optianal for the endPoint its request.
$parameters = 'grant_type=password&username=abc#abc.com&password=123abc&client_id=myClientID&client_secret=myClientSecret';
// All parts together.
$url = $baseURL . $endPoint . '?' . $parameters;
//Init session for CURL.
$ch = curl_init();
// Options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
// Init headers for access to the binance API signed data.
$headers = array();
$headers[] = 'Content-type: application/x-www-form-urlencoded';
$headers[] = 'Content-Length: 0';
// Setting headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
// Ends the CURL session, frees all resources and deletes the curl (ch).
curl_close($ch);
$result = json_encode($data);
echo($data);
exit();
?>
The authentication is oauth2 and I want to use the "Password Grant" flow since I can login automaticly this way. Also I see in the example code in C# that they encode the url, something im not doing yet but did try. It did not work.
// Using $encodedUrl like this: curl_setopt($ch, CURLOPT_URL, $encodedUrl); but does not work.
$encodedUrl = urlencode($url);
Alright so I fixed it. I now got my access token and am able to recieve data from the API. This is what I did:
// ---- GET TOKEN - FLOW: USER PSW ----
// No changes
$baseURL = 'https://authorize.2ba.nl';
// No changes
$endPoint = '/OAuth/Token';
// $parameters is now an array.
$parameters = array(
'grant_type' => 'password',
'username' => 'myUsername',
'password' => 'myPassword',
'client_id' => 'myClientID',
'client_secret' => 'myClientSecret'
);
// Removed the $parameter part
$url = $baseURL . $endPoint;
//Init session for CURL.
$ch = curl_init();
// Init headers for access to the binance API signed data.
$headers = array();
$headers['Content-Type'] = "application/x-www-form-urlencoded";
// NOTE: http_build_query fixed it.
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters)); // Automaticly encodes parameters like client_secret and id.
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
// Ends the CURL session, frees all resources and deletes the curl (ch).
curl_close($ch);
$result = json_encode($data);
echo($data);
exit();
I have this code in python that do a request to the API of suap passing the values of dados_usuario, that I tested and is working, but I wanna write the same code in php and I dont getting it, all I got was the token with the follow code, so, anyone could help me with the second part using curl in php?
python code - https://imgur.com/a/LpZ7j4S
import requests
# Obtaining the user's token
url = 'https://suap.ifrn.edu.br/api/v2/autenticacao/token/'
#username and password are your data used to access SUAP
dados_usuario = {
'username': '',
'password': ''
}
requisicao = requests.post(url, data=dados_usuario)
if requisicao.status_code == requests.codes.ok:
token_autenticacao = requisicao.json().get('token')
print ('\n--- Token de Autenticação:\n {}\n\n'.format(token_autenticacao))
# Obtaining User Data.
url = 'https://suap.ifrn.edu.br/api/v2/minhas-informacoes/meus-dados/'
headers = {
'Authorization':'JWT {}'.format(token_autenticacao)
}
requisicao = requests.get(url, headers=headers)
if requisicao.status_code == requests.codes.ok:
retorno_json = requisicao.json()
print ('--- Dados do Usuário Logado:\n{}\n\n'.format(retorno_json))
php code - https://imgur.com/a/tkxb9Gm
<?php
$url = 'https://suap.ifrn.edu.br/api/v2/autenticacao/token/';
$user_data = [
'username' => '',
'password' => ''
];
$ch = curl_init();
//Getting the user token
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $user_data);
$result = curl_exec($ch);
//Token variable
$token = json_decode($result, true);
curl_close($ch);
echo $token["token"]."\n\n";
I need get the user date with php, until now I just have the token, and I need get it with curl.
I got the resolver with this code
$token = "token hide";
$ch = curl_init('https://suap.ifrn.edu.br/api/v2/minhas-informacoes/meus-dados/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: JWT ' . $token
));
$data = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
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']
);
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.
I have received "tokenSecret" and "response token".
$apiCred_user = "XXXX.com";
$apiCred_pass = "XXXX";
$accessToken = "XXXXXXXXXXXXXXKl8OlQ";
$tokenSecret = "XXXXXXXXXXXXXsRg6ULs";
$url = "https://api.sandbox.paypal.com/nvp";
$auth = new AuthSignature();
$response = $auth->genSign($apiCred_user ,$apiCred_pass ,$accessToken,$tokenSecret,'POST',$url);
$authString =
"token=".$accessToken.
",signature=".$response['oauth_signature'].
",timestamp=".$response['oauth_timestamp'];
Using this call, the signature is received. My doubt, The given url is used to generate the signautre. The call is correct?
To get result from "GetBasicPersonalData" , I have used this below code
$headers = array(
"X-PAYPAL-REQUEST-DATA-FORMAT:NV",
"X-PAYPAL-APPLICATION-ID: APP-80W284485P519543T",
"X-PP-AUTHORIZATION: " .$authString,
"X-PAYPAL-RESPONSE-DATA-FORMAT:json");
$url_api = "https://svcs.paypal.com/Permissions/GetBasicPersonalData";
$post_array = array(
"attributeList"=>array("attribute"=>"http://axschema.org/contact/email"),
"requestEnvelope.errorLanguage"=>"en_US");
$curl_session = curl_init();
curl_setopt($curl_session, CURLOPT_URL,$url_api );
curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_session, CURLOPT_POST, 1);
curl_setopt($curl_session, CURLOPT_POSTFIELDS, http_build_query($post_array));
curl_setopt($curl_session, CURLOPT_CONNECTTIMEOUT,10);
curl_setopt($curl_session, CURLOPT_TIMEOUT, 10);
//curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, 0);
$response = json_decode(curl_exec($curl_session));
curl_close($curl_session);
The response result is "Error"
{"responseEnvelope":
{"timestamp":"2015-02-05T09:26:53.053-08:00","ack":"Failure","correlationId":
"c74e091e7944e","build":"2210301"},"error":
[{"errorId":"560022","domain":"PLATFORM","subdomain":"Application","severity":"Error","category":"Application","message":"The X-PAYPAL-APPLICATION-ID header contains an invalid value","parameter":["X-PAYPAL-APPLICATION-ID"]}]}
Thanks ! 123456
you forgot to ask for user's permission to get his personal data.
let's suppose you want to ask his permission to issue refunds, your request should look like this:
$data = array(
'scope' => array(
'0' => 'REFUND',
'1' => 'ACCESS_BASIC_PERSONAL_DATA'
),
'callback' => 'http://yoursite.com/page.php', // The success page
'requestEnvelope' => array(
'errorLanguage' => 'en_US' // Language used to display errors
)
);
then you'll get the correct access token and token secret.
if you're still stuck, please ask for the complete code.