php facebook sdk want to create subscription for real-time updates - facebook-php-sdk

got this error every time if I change verify_token value or server request method.
{"error":{"message":"(#2201) response does not match challenge, expected value = '1383165001', received=''","type":"OAuthException","code":2201}}{"data":[]}

Your script just needs to return the challenge back to Facebook, so it can verify the response. I do the following in my script:
// return hub.challenge to facebook
echo isset( $_GET['hub_challenge'] ) ? $_GET['hub_challenge'] : false;
It basically just echos the challenge sent by Facebook back to it.

Related

Detect if requested page is PWA on server side WordPress

I'm trying to determine if the user is browsing PWA on server side. On client side I can check if the browser mode is standalone via JavaScript and detect PWA, but on server side this is not an option. So I'm using simple query parameter for that. Start URL in manifest has query param isPwa appended and every time user opens PWA, it goes to https://example.com/?isPwa. What I need now is to keep that parameter while user browses PWA, so I need to set isPwa parameter to next URL that user opens if the referer URL already had isPwa parameter, but my code goes to redirection loop and I'm unable to identify the cause of this. Here's my code:
function addIsPwaQueryArg() {
$referer = wp_get_referer();
if (strpos($referer, 'isPwa') !== false) {
$location = remove_query_arg('isPwa');
wp_redirect(add_query_arg('isPwa', '', $location));
exit;
}
}
add_action('template_redirect', 'addIsPwaQueryArg');
Can someone tell me what's wrong with my code and why is it not working?
Thanks!

Response Code From Google comes in wrong format upon on first sign in using Oauth 2.0 Authentication

Response Code received after signing on to google for first time.
[http://localhost:8080/?state=trueprompt%3Dconsent&code=4%2FjlCxJC7rg57nOG7w-0MP4M1BuQ7cbI4GLCNofMzPeQQ#][1]
Below given is the code i am using
GoogleConnectionFactory connectionFactory = new GoogleConnectionFactory("CLIENT_ID","CLIENT_SECRET");
System.out.println(connectionFactory.getScope());
connectionFactory.generateState();
OAuth2Operations oauthoperations =connectionFactory.getOAuthOperations();
OAuth2Parameters params = new OAuth2Parameters();
params.setRedirectUri("http://localhost:8080");
params.setScope("https://www.googleapis.com/auth/userinfo.profile");
params.setState("true");
String authorizeUrl = oauthoperations.buildAuthenticateUrl(GrantType.AUTHORIZATION_CODE,params);
After receving the authorizeUrl i am pasting that directly on to the browser, then it takes me to google signin page. After signing in it redirects back to call-back url with the code parameter value, which is mentioned at the very first link.
But that response code is not working for getting the Access Token. when i again copy paste the same login url on to brwoser it responds with a different response code which is mentioned below. This time as i am already logged i don't have to login in again and it responds with a different responds code which is working fine and i am able to get the AccessToken. The difference between first and second response code is that in first it responds with 4% where as in second it comes with 4/.
http://localhost:8080/?state=true&code=4/0Y9NMh9fYAr3kfy3r1por3Py1LCdbOsIUz3fwdv78gc#
AccessGrant accessGrant = oauthoperations.exchangeForAccess("AUTHORIZATION_CODE", "http://localhost:8080",null );
Connection<Google> connection = connectionFactory.createConnection(accessGrant);
System.out.println(connection.getDisplayName());
Please help me to resolve this issue.

PHP and REST API - Retrieving Company Updates

I'm actually working on displaying my company updates as a feed on my website.
I've created an App on LinkedIn and I'm able to get my security token and list info related to my profile by using the : "https://api.linkedin.com/v1/people/ME".
However, when I'm trying to retrieve my company updates using a GET call on : "https://api.linkedin.com/v1/companies/".$company_id."/updates". I'm getting a :
"Member does not have permission to get company." in the HTTP response message.
Configuration set :
I'm correctly listed as Admin on my company's page
"rw_company_admin" is enabled on my LinkedIn App
My App status is set to "Live"
My company ID is the correct one (I've double checked already)
My token is properly issued and I'm correctly identified by the app
Here is the code I'm using in the PHP method to get the updates :
public function getCompanyUpdates($company_id, $start=0,$count = 20){
if(!$company_id)return false;
$params['url'] = "https://api.linkedin.com/v1/companies/".$company_id."/updates";
$params['method']='get';
$params['args']['format']='json';
if($start != 0 )$params['args']['start']=$start;
if($count != 0 )$params['args']['count']=$count;
$params['args']['event-type']='status-update';
$result = $this->makeRequest($params);
return json_decode($result,true);
}
I'm probably missing a step somewhere, but I've no idea where..
In advance, thanks a lot for your help!!
I fixed the error some weeks ago, but forgot to post the answer that fixes the issue.
My errors :
- At first, I forgot to pass the scope while requesting the Token
- After fixing this, I forgot to re-issue a new Token to get the scope applied
To conclude, it was just an oversight from me.
However, the LinkedIn API is a bit shitty, as it requires to refresh the Token periodically. It should be simplified when we only want to list Public updates that everyone can access.
Cheers

Google Analytics API V3 / OAuth 2

I've desperately tried to figure this out on my own, and did not want to come to SO with this question, but I'm at my wits end (no thanks to the api / oauth docs).
I'm working in PHP and I'm trying to avoid using the Google_Client and AnalyticsService classes, by using REST on the analytics.data.ga.get method.
STEP #1: Create an API Project for a Web Application
I go to the api console and create a project with analytics services and get an OAuth Client ID and Secret.
I'm under the impression that I can create a Client ID for an Installed Application or a Web Application because I'm doing the initial token handshaking manually. Please correct me if I'm wrong.
I create a Client ID for web applications and get my Client ID xxxxxxxxxxxxxx.apps.googleusercontent.com, Client secret yyyyyyyyyyyyyyy, and my Redirect URI is http://localhost:9002
STEP #2: Request initial API access
I enter this link; https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=xxxxxxxxxxxxxx.apps.googleusercontent.com&redirect_uri=http://localhost:9002&scope=https://www.googleapis.com/auth/analytics.readonly&access_type=offline
The access_type=offline is because I'm using REST, and do not expect "the user" (myself) to manually deal with redirects / popups every time I need a refreshed token.
The above request returns http://localhost:9002?code=4/KModH0K_xxxxxxxxxxxxxxxxxxx9Iw.gikOaYRDWywTshQV0ieZDArCOX8XdwI
Code 4/KModH0K_xxxxxxxxxxxxxxxxxxx9Iw.gikOaYRDWywTshQV0ieZDArCOX8XdwI is my permission to request the API Token.
STEP #3: Request First Token
Because of my company’s IT issues, I’m forced to use PHP 5.2.17 and I do not have access to PHP cURL, so I’m using file_get_contents and stream_context_create.
The first token is requested with a PHP file_get_contents();
$opts = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => 'code=4/KModH0K_xxxxxxxxxxxxxxxxxxx9Iw.gikOaYRDWywTshQV0ieZDArCOX8XdwI&client_id=xxxxxxxxxxxxxx.apps.googleusercontent.com&client_secret=yyyyyyyyyyyyyyy&redirect_uri=http://localhost:9002&grant_type=authorization_code'
)
);
$context = stream_context_create($opts);
$result = file_get_contents('https://accounts.google.com/o/oauth2/token', false, $context);
var_dump($result);
The content parameters must be in a single line.
The above code returns my access_token and refresh_token in json format
string(195) "{ "access_token" : "ya29.AHES6wwwwwwwwwwwwwwwVEBXE6XRbC-Q-pP0wZWdoIm9H804ro", "token_type" : "Bearer", "expires_in" : 3600, "refresh_token" : "1/8tXvdUKcSEcaaxVqqqqqqqqqqqqqoYpj2KSS9qwWI" }"
The refresh token I must store in a safe place, like a DB or protected txt file, which is called upon when my access_token has timed out.
STEP #4: Request Analytics Data
Now from what I understand, I’m ready to roll and should be able to use my access_token to make requests to https://www.googleapis.com/analytics/v3/data/ga.
I do this by sending this request;
$request = 'https://www.googleapis.com/analytics/v3/data/ga' .
'?ids=ga%3Aaaaaaaaa' .
'&start-date=2012-12-07' .
'&end-date=2012-12-09' .
'&metrics=ga%3Avisits';
$opts = array(
'http' => array(
'method' => 'GET',
'header' => 'Content-Type: application/x-www-form-urlencoded\r\n' .
'Authorization: Bearer ya29.AHES6wwwwwwwwwwwwwwwVEBXE6XRbC-Q-pP0wZWdoIm9H804ro \r\n'
)
);
$context = stream_context_create($opts);
$result = file_get_contents($request, FALSE, $context);
var_dump($result);
This request returns a 401 Unauthorized error. I take this as meaning my request is properly formed and making the connection to https://www.googleapis.com/analytics/v3/data/ga.
Also, according to this doc Getting Full Quota, I can make the request with the access_token in the URL like this;
$request = 'https://www.googleapis.com/analytics/v3/data/ga' .
'?ids=ga%3A48564799' .
'&access_token=ya29.AHES6wwwwwwwwwwwwwwwVEBXE6XRbC-Q-pP0wZWdoIm9H804ro' .
'&start-date=2012-12-07' .
'&end-date=2012-12-09' .
'&metrics=ga%3Avisits';
$result = file_get_contents($request, FALSE);
$result = json_decode($result);
var_dump($result);
This time I receive 403 error, in which google includes the response User does not have sufficient permissions for this profile.
QUESTION #1
Am I’m missing something in the API console or a process in the token acquisition? I’m assuming I’m not, because I’m ultimately acquiring the access_token=ya29 and refresh token.
QUESTION #2
Maybe I’m completely off basis in assuming I can do this with simple https reqests? Do I have to use the Google_Client and AnalyticsService classes? I don’t think this is the case, but maybe I’m wrong.
QUESTION #3
Do I need to use a ‘key’ in my request?
&key=bbbbbbbbbbbbbbbb
QUESTION #4
By using PHP 5.2.17 am I missing something? (besides 5.3 or 5.4 themselves)
For example, in some versions of PHP, in stream_context_create, the header should be in an array and not a string, like this;
$opts = array(
'http' => array(
'method' => 'GET',
'header' => array(
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Bearer ya29.AHES6wwwwwwwwwwwwwwwVEBXE6XRbC-Q-pP0wZWdoIm9H804ro '
)
)
);
But I don’t think that it’s an issue in my case. I’m just curious if these HTTP request need to be formed a different way (without using curl).
Any insights and thoughts would be greatly appreciated
Here’s my dim witted mistake that nearly gave me a heart attack.
I typically do my development work in Chrome. And my Chrome browser was signed into my gmail account personal#gmail.com. However, my analytics account, which is under my work#gmail.com was open in FireFox (try not to laugh to hard).
I’m not 100% sure this is correct, but I think this is the general flow. When I did STEP #2: Request initial API access, I did this in my Chrome browser. The endpoint https://accounts.google.com/o/oauth2/auth was authorizing my personal#gmail.com account. And my STEP #4 API request https://www.googleapis.com/analytics/v3/data/ga was looking for an analytics profile under my personal#gmail.com account. Which of course doesn’t exist.
I literally wasted 15 hours on this. This is dumber than trying to troubleshoot an update… and forgetting to flush the cache.
Sorry for wasting your time.
EDIT REFRESH TOKENS
I've once again run into issues with this API and found out the hard way that GA will revoke Refresh Tokens if too many different clients use the token, at least I think that was the problem.
Further reading can be found here.
I got a 403 today and found the cause: in the get function I was using the account ID instead of the profile ID. Switching to the profile ID fixed it for me.
It could be a problem with CURL request. In the GoogleAnalyticsAPI.class.php > class Http > function curl (around line 720) add one more option to stop CURL from verifying the peer's certificate:
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

Get refresh token google api

I can't get my refresh token with my code. I can only get my access token, token type etc.,
I have followed some tutorials like putting access_type=offline on my login URL:
echo "<a href='https://accounts.google.com/o/oauth2/auth?"
. "access_type=offline&client_id=123345555.apps.googleusercontent.com& "
. "scope=https://www.googleapis.com/auth/calendar+https://www.googleapis.com/auth/plus.me&response_type=code& "
. "redirect_uri=http://www.sample.com/sample.php&state=/profile'>Google</a>";
and my fields in getting the access token:
$fields=array(
'code'=> urlencode($authcode),
'client_id'=> urlencode($clientid),
'client_secret'=> urlencode($clientsecret),
'redirect_uri'=> urlencode($redirecturi),
'grant_type'=> 'authorization_code',
);
but I can't get refresh_token, just the access_token, token_type, id_token and expires_in.
Found out by adding this to your url parameters
approval_prompt=force
Update:
Use access_type=offline&prompt=consent instead.
approval_prompt=force no longer works
https://github.com/googleapis/oauth2client/issues/453
If I may expand on user987361's answer:
From the offline access portion of the OAuth2.0 docs:
When your application receives a refresh token, it is
important to store that refresh token for future use. If your
application loses the refresh token, it will have to re-prompt the
user for consent before obtaining another refresh token. If you need
to re-prompt the user for consent, include the approval_prompt
parameter in the authorization code request, and set the value to
force.
So, when you have already granted access, subsequent requests for a grant_type of authorization_code will not return the refresh_token, even if access_type was set to offline in the query string of the consent page.
As stated in the quote above, in order to obtain a new refresh_token after already receiving one, you will need to send your user back through the prompt, which you can do by setting approval_prompt to force.
Cheers,
PS This change was announced in a blog post as well.
It is access_type=offline that you want.
This will return the refresh token the first time the user authorises the app. Subsequent calls do not force you to re-approve the app (approval_prompt=force).
See further detail:
https://developers.google.com/accounts/docs/OAuth2WebServer#offline
This is complete code in PHP using google official SDK
$client = new Google_Client();
## some need parameter
$client->setApplicationName('your application name');
$client->setClientId('****************');
$client->setClientSecret('************');
$client->setRedirectUri('http://your.website.tld/complete/url2redirect');
$client->setScopes('https://www.googleapis.com/auth/userinfo.email');
## these two lines is important to get refresh token from google api
$client->setAccessType('offline');
$client->setApprovalPrompt('force'); # this line is important when you revoke permission from your app, it will prompt google approval dialogue box forcefully to user to grant offline access
For our app we had to use both these parameters access_type=offline&prompt=consent.
approval_prompt=force did not work for us
Hi I followed following steps and I had been able to get the refresh token.
Authorization flow has two steps.
Is to obtain the authorization code using https://accounts.google.com/o/oauth2/auth? URL.
For that a post request is sent providing following parameters. 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE + '&access_type=offline' Providing above will receive a authorization code.
Retrieving AcessToken and RefreshToken using https://accounts.google.com/o/oauth2/token? URL.
For that a post request is sent providing following parameters.
"code" : code,
"client_id" : CID,
"client_secret" : CSECRET,
"redirect_uri" : REDIRECT,
"grant_type" : "authorization_code",
So in your first attempt once you authorize the permissions you will be able to get the Refresh token. Subsequent attempts will not provide the refresh token. If you want the token again the revoke the access in you application.
Hope this will help someone cheers :)
OAuth has two scenarios in real mode.
The normal and default style of access is called online.
In some cases, your application may need to access a Google API when the user is not present,It's offline scenarios .
a refresh token is obtained in offline scenarios during the first authorization code exchange.
So you can get refersh_token is some scenarios ,not all.
you can have the content in https://developers.google.com/identity/protocols/OAuth2WebServer#offline
.
Since March 2016, use prompt=consent to regenerate Google API refresh token.
As mentioned in https://github.com/googleapis/oauth2client/issues/453,
approval_prompt=force has been replaced with prompt=none|consent|select_account
For those using the Google API Client Library for PHP and seeking offline access and refresh tokens beware as of the time of this writing the docs are showing incorrect examples.
currently it's showing:
$client = new Google_Client();
$client->setAuthConfig('client_secret.json');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
// offline access will give you both an access and refresh token so that
// your app can refresh the access token without user interaction.
$client->setAccessType('offline');
// Using "consent" ensures that your application always receives a refresh token.
// If you are not using offline access, you can omit this.
$client->setApprovalPrompt("consent");
$client->setIncludeGrantedScopes(true); // incremental auth
source: https://developers.google.com/identity/protocols/OAuth2WebServer#offline
All of this works great - except ONE piece
$client->setApprovalPrompt("consent");
After a bit of reasoning I changed this line to the following and EVERYTHING WORKED
$client->setPrompt("consent");
It makes sense since using the HTTP requests it was changed from approval_prompt=force to prompt=consent. So changing the setter method from setApprovalPrompt to setPrompt follows natural convention - BUT IT'S NOT IN THE DOCS!!! That I found at least.

Resources