PHP and REST API - Retrieving Company Updates - linkedin

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

Related

LinkedIn Api issue

Im trying to use linkedin API’s
In specific simpleJobPosting ( which is like i read in the documentation its an api that is used to create a post on linkedIn profile )
I followed all the steps ,, created an app on the linkedIn portal and got ClientId and ClientSecret ,, I’ve generated an access token and verified the organization that I selected,, also i selected the suitable scope before generating an access token (w_member_social)
when I tested it on PostMan I still got an error which is said
U don’t have enough permission to access Post/simpleJobPosting with status 403 and error code 100
I checked the documentation for the error status and said ensure that the header x-restli-method with value batch_create is present and i already included it in the headers and all the other steps
any suggestions ??
step1-As shown here i created an app and got clientId,ClientSecret
step2-i selected the suitable scope(permission)
step3-i've generated an access token
step4-verified the company that i've selected
step5-postman request details

Gravity Forms API always 401

I am trying to use the gravity forms rest api, https://www.gravityhelp.com/documentation/article/web-api/ but I receive a 401 error no matter what I try. I've tried using all the methods listed in the documentation and in Steven Henty's article, https://www.stevenhenty.com/gravity-forms-api/ but it doesn't seem to work.
If I am logged into a wordpress site as administrator should I not be able to use a link like:
http://mydomain/gravityformsapi/forms/
Thank you for any suggestions.
For mine case it was that I haven't clicked the update button "Web API" Tab.
Make sure you click update button , although it does show the API Key's but still you have to click update button to enable API.
I was getting the same thing due to some weirdness about the route endpoint. When calculating the signature you don't use a trailing slash on the route: forms/1.
But you do use a trailing slash in the URL (otherwise I got a 301 Moved Permanently):
http://demo.gravityforms.com/gravityformsapi/the_route/?api_key...
It looks odd to have /?api_key... but that is what works for me.
Here's the ruby example I was using with the demo credentials:
GravityFormsAPI.generate_URL(site: 'demo.gravityforms.com', route: 'forms/1', public_api_key: '5b225f8382', private_api_key: 'fc6d1bc71d2ebfc')
Hope this helps.
Sometimes i received intermittent 401 error after a lot of research i find this article
Azure DocumentDB Intermittent 401 error when querying REST API via Obj-c
If the signature contains + sign i received 401 error
Maybe that help other person
Sorry for my english writing
Based on the solution here I'm posting this answer.Imagine you have created the URL and it didn't work and you got 401. Then after a little time you realized the error that Opps! The parameters I was passing needed a bracket and you run the code again and you again got 401.
Why is that?
This is because the parameters which are apiKey, Signature and Expire time are the same and you only changed the other parameters with your GET request. However these three parameters are used to authenticate the user so that means the old signature which was generated to deny the permission will deny it again no matter what.
So to fix that I just changed the expire time from 1577922200 to 1577933200. I could've changed it to anything but the thing is I just need to give something new so that a new signature can be generated. So when I changed it started working.
OTHER POSSIBLE REASONWhile making the signature using SHA1 you use NSString *string_to_sign = [NSString stringWithFormat:#"%#:%#:%#:%#",api_key,http_method,route,expires];
as per the documentation. But in order to make CCHmac you have to pass it two things:
Key
Data
and based on the link it is created as
const char *cKey = [api_private_key cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [string_to_sign cStringUsingEncoding:NSASCIIStringEncoding];
So what I was mistaking is that I was using API Key in cKey instead of API Private Key. So I change it as per tutorial said and it worked. Otherwise I was getting 401 not matter what I try.

Google Analytics API - inconsistent error "insufficientPermissions' (403)

Backgroud:
I have a PHP code that runs queries to Google Analytics API on behalf of my users.
I am using OAuth2 for authentication and storing the access-tokens of the users in my DB.
My code makes sure not to exceed the quota per user (10 QPS), and I'm using the "quotaUser" parameter in my queries.
The issue:
About 50% of my queries to GA are responded with error 403 ("insufficientPermissions", "User does not have sufficient permissions for this profile.").
The strange this is, that the other ~50% are getting the results from GA successfully.
Some important points:
The only thing common to all the successful queries and common to the unsuccessful queries is the batch that they are in: my code is sending a "batches" of queries (one after one with very short delay between them) to GA's API and every batch is ether passing or failing with 403.
Adding \ removing permissions to the scope did not solved the issue.
It is worth mentioning that this is not a View-ID \ Account-ID issue etc. as the same query can pass or fail for the same user and view.
I saw a related unanswered issue here and couldn't find any other truly-related issues.
A snippet from my code:
//Create a Google Client
$client = new Google_Client();
$client->setAuthConfigFile($this->secretJson);
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Oauth2::PLUS_LOGIN, Google_Service_Analytics::ANALYTICS);
// Set the access token on the client.
$client->setAccessToken($accessToken);
// Create an authorized analytics service object.
$this->analytics = new Google_Service_Analytics($client);
...
//Run the query
$results = $this->analytics->data_ga->get($id, $startDate, $endDate, $metrics, $opts);
Ido, can you still reproduce this issue? It sounds very much like there is a problem with your access token. I would start troubleshooting by making sure you are setting the same access token for all batch runs and validating that the token is not expired (isAccessTokenExpired()).

The Access Token is Valid but We get OAuthException: An active access token error

We've been working on an application for about 2 months, and everything was going perfectly.
we were using PHP SDK and offline mode in permissions for login
But since some days ago after recent changes in Facebook api and removing offline mode we started facing the problem of "Uncaught OAuthException: An active access token must be used to query information about the current user."
The main problem is that it does happen after a while working in our app (about 10 mins) but at the same time when we check the validity of the token via this link
we see that the token is still valid on the other hand the cookie does still exist and it doesn't expire but we get this error :
"Uncaught OAuthException: An active access token must be used to query information about the current user"
I've already visited this link
and I downloaded the latest version but it didn't help could anyone help us please where might be making mistake?
Thanks for responses, I think same as yacon
it seems there's a bug when accessing facebook->api(/me) at the moment we are handling
some parts of the app with javascript which is a real headache to use javascript sdk
and PhP sdk alongside with each other
You can solve this simply store accesstoken to session variable after getLoginUrl
$facebook->getLoginUrl(...)
then whenever you initialize facebook
$facebook = new Facebook(array(
'appId' => Yii::app()->params['facebook_appId'],
'secret' => Yii::app()->params['facebook_appSecret'],
));
get the accesstoken from session and set it using setAccessToken
$facebook->setAccessToken(Yii::app()->session['access_token']);
I handle this situation in this way
1.i get the access token for 1 hour validity
2.extend the token to 60 days validity
3.save that token to session and use it for all project queries.
try{
$facebook_uid = $facebook->getUser();
$facebook->setExtendedAccessToken();
$accessToken = $facebook->getAccessToken();
$fbuser = $facebook->api('/me');
$session['api_me'] = $fbuser;
$session['tokenValue'] = $accessToken;
}catch (Exception $e) {
facebook_uid =null;
}
I think there is a bug in the api. When I use $facebook->api('/'.$facebook_uid) instead of ->api('/me') it works.

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