LinkedIn Access Token to authenticate users and use JSAPI Send a message - php

I am working on the PHP application, that captures "Access Token", when user click on register with Linkedin, I use that access token to get all the related information from the user's Linkedin profile.
I now want to include LinkedIn Send a message feature http://developer.linkedin.com/documents/sample-code-sending-message.
Is there any way I can use the Send a message feature with authentication process using user's access token without showing user to login with linkedIn again to send a message?

Yes there is, just store the token in a database (it should be good for 60days) and reuse it in your requests. If the token expires you will have to reauthorize a new one.
Example with my linkedin class from:
https://github.com/EJTH/SLinkedIn
But it should be pretty similar with other classes or extensions.
$ln = new SimpleLinkedIn('APIKEY','APISECRET');
$ln->addScope('rw_nus');
$ln->setTokenData($myUserObj->getLinkedinToken() /* Get token from db */);
if($ln->authorize()){
/* Do OAuth stuff */
$user = $ln->fetch('GET', '/v1/people/~:(firstName,lastName)');
$tokenData = $ln->getTokenData();
/* Save the new token, if it was changed */
$myUserObj->setLinkedinToken($tokenData['access_token']);
} else {
/* User declined authorization */
}
Just remember that your token must have the scope for the action you want to perform.

Send message
how do i send a message/notification with the linkedin api?
You use LinkedIn Access Token and send by function message.

<?php
// base or site url is the site where code linked in button is kept for signup
$baseURL = 'http://localhost/linkedin/';
/* callback or redirect url is the page you want to open
* after successful getting of data i.e. index.php page
* (must be same in linkedin dashboard) */
$callbackURL = 'http://localhost/linkedin/process.php';
// APP ID (will receive from linkedin dashboard)
$linkedinApiKey = 'your api key';
// APP Client
$linkedinApiSecret = 'your api secret';
// This is fixed no need to change
$linkedinScope = 'r_basicprofile r_emailaddress';
?>

Related

Need Email Address from Google with Access Token that we receive from Alexa Skill?

I was able to Link Account using Google Auth v2 in Alexa Skill. And I am able to get Access Token. Now I want to get the Google Email address with which user has used to link account. So how can I get that Google Email Address?
Use the Oauth2 Scope "https://www.googleapis.com/auth/userinfo.email".
Add the scope to your Google Client (Example with the Google Library for PHP):
$googleClient = new Google_Client();
// Your code here with Client ID, Secret, ...
$googleClient->addScope('https://www.googleapis.com/auth/userinfo.email');
That'll give you the E-Mail of the user.
if(isset($_GET['code'])) {
// Your code here, the login code is in $_GET['code']
/**
* Get access token
*/
$token = $googleClient->fetchAccessTokenWithAuthCode($_GET['code']);
$googleClient->setAccessToken($token['access_token']);
// Create Google Auth Service with the Google Client
$google_auth = new Google_Service_Oauth2($googleClient);
// Get the userinfo
$google_auth_info = $google_auth->userinfo->get();
// Get the E-Mail:
$email = $google_auth_info->email;
}
I think the part you're looking for is authinfo->get()->email, but i added a bit more context so you see how to use this.
Don't forget to enable this scope also in your Google Developers Console:
https://console.cloud.google.com/apis/credentials/consent -> Edit -> Step 2: Scopes

Storing the Google OAuth Authorization Token in Database

I am building a portal where multiple users can log in to their multiple Gmail accounts. I have successfully retrieved the token value, However, I want to store that in my database but I am unable to store it.
Below is the code I am using:
function mInititalize(){
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://mail.google.com/');
$client->setClientId(Config('gmail.client_id'));
$client->setClientSecret(Config('gmail.client_secret'));
$client->setRedirectUri('http://localhost:81'.Config('gmail.redirect_url'));
$loginURL = $client->createAuthUrl();
return redirect($loginURL);
}
After Redirection or user login
function mGetToken(){
$token = $client->fetchAccessTokenWithAuthCode( 'code'); // here i get the 'code' from login URL
I pass this code to get token I successfully get token
$oAuth = new Google_Service_Oauth2( $client);
$userData = $oAuth->userinfo_v2_me->get(); // get current user detail
}
I want to store $token value in database, but I am getting error message
>Serialization of 'Closure' is not allowed
Please anyone help me to solve this issue. Thanks.
I would suggest storing OAuth credential information for the Google API, not in your database, but through the API itself. If you're intending to use it any authentication manner, you'll run into problems, as the docs state:
Access tokens periodically expire and become invalid credentials for a related API request. Google Identity Platform: Using OAuth 2.0 for Web Server Applications
But, the same docs also show a way that you can set or retrieve the token natively within the API. Since it's data relating to google's auth'ing process, and since it might go stale if you store it, it seems best to just let them handle it and work with the API. The same source:
If you need to apply an access token to a new Google_Client object—for example, if you stored the access token in a user session—use the setAccessToken method:
$client->setAccessToken($access_token);
$client->getAccessToken();

Google Gmail API - How to login programatically?

I'm looking to write a PHP script that scans my gmail inbox, and reads unread emails. There needs to be NO user interaction. This has to happen on a cronjob that executes a PHP file.
Is this even possible with the API? Googles documentation is absolutely terrible, and no-where does there seems to be any examples that allow you to authorize a log in programatically. They always require a user to physically press the allow button on an oauth request.
Has anybody got experience in trying to simply login and list your messages, without the need of human interaction?
client login
I think what you are trying to ask here is how to login to the api using your login and password. The anwser is you cant this was called client login and google shut down that option in 2015. You have not choice but to use the Oauth2 if you want to connect to the gmail api
service accounts
Normally i would say that you should use a service account. However service accounts only work with gmail if you have a gsuite account in which case you can set up domain wide delegation's here
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
* Initializes a client object.
* #return A google client object.
*/
function getGoogleClient() {
return getServiceAccountClient();
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
* Scopes will need to be changed depending upon the API's being accessed.
* array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* #return A google client object.
*/
function getServiceAccountClient() {
try {
// Create and configure a new client object.
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope([YOUR SCOPES HERE]);
return $client;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
oatuh2
In the event that you are not using gsuite. Then what you can do is authenticate your code once. Make sure to request off line access. A refresh token will be returned to you. If you save this refresh token you can then use that refresh token at anytime to request a new access token. In the example below you can see how the refresh token was simply stored in a session varable you could store it in a file and read from that when ever you need.
function getOauth2Client() {
try {
$client = buildClient();
// Set the refresh token on the client.
if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
$client->refreshToken($_SESSION['refresh_token']);
}
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Refresh the access token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
$_SESSION['access_token'] = $client->getAccessToken();
}
return $client;
} else {
// We do not have access request access.
header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
}
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
code ripped from Oauth2Authentication.php
smtp
You mentioned that you want to use the gmail api but have you considered going directly though the mail server? This would allow you to use login and password. or oauth -> Imap-smtp
You need to use three-legged OSuth, that is OAuth where the end-user (owner of the gmail account), logs in and authorizes your app to read their email. There is no other way to access a user's Gmail account via the API except with three-legged OAuth.
The end user needs to click on the first time. Once your app has received consent from the end user, the app can access the Gmail API on behalf of the user in the future without clicks. I find this documentation the clearest, look for grantOfflineAccess().
You could copy and paste a simple JavaScript Frontend from the documentation that allows you to do the log in, and write your backend logic in PHP.

Laravel PHP Fitbit API OAUTH - storing and reusing access tokens

I am currently using the fitbit library with a laravel wrapper (see https://github.com/popthestack/fitbitphp).
I am attempting to store the access token once a user authenticates and then subsequently reuse that token instead of having to make a separate request for a new token each time. Is it possible using fitbits oauth 1 implementation to reuse the access tokens or will I need to make a new request using request tokens etc. each time. I apologize in advance, I have a fairly visceral understanding of oauth in the first place but fitbit in particular has been tripping me up. Thanks.
here is the function I have that requests info from fitbit...
public function getFitbit() {
// get data from input
$code = Input::get( 'oauth_token' );
// get fb service
$fb = fitbitOauth::consumer( 'Fitbit' );
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from fitbit, get the token
$fb->requestAccessToken(
$_GET['oauth_token'],
$_GET['oauth_verifier']
);
// Send a request now that we have access token
$result = json_decode($fb->request('user/-/profile.json'));
print_r($result);
}
// if not ask for permission first
else {
// get fb authorization
$token = $fb->requestRequestToken();
$url = $fb->getAuthorizationUri(array('oauth_token' => $token->getRequestToken()));
// return to facebook login url
return Redirect::to( (string)$url );
}
}
I can run through the above example. Direct a user to the page where they can authenticate their account. This then redirects to a page that displays their info. If I reload the page with the 'token' and 'verifier' set already it fails. I want to be able to save off their token to a DB and reference it in the future.

Generate a Dwolla access token using AJAX instead of redirecting to their webpage?

Looking at Dwolla's API documentation and trying the oauth.php example code (code shown below) on my site it is not clear to me if I can generate an access token without redirecting to Dwolla's page.
Redirecting from my site to their site back to my site is really terrible from a UI/UX perspective and is no better than the crappy interface Paypal provides.
Does anyone know how to generate a Dwolla access token using AJAX?
<?php
// Include the Dwolla REST Client
require '../lib/dwolla.php';
// Include any required keys
require '_keys.php';
// OAuth parameters
$redirectUri = 'http://localhost:8888/oauth.php'; // Point back to this file/URL
$permissions = array("Send", "Transactions", "Balance", "Request", "Contacts", "AccountInfoFull", "Funding");
// Instantiate a new Dwolla REST Client
$Dwolla = new DwollaRestClient($apiKey, $apiSecret, $redirectUri, $permissions);
/**
* STEP 1:
* Create an authentication URL
* that the user will be redirected to
**/
if(!isset($_GET['code']) && !isset($_GET['error'])) {
$authUrl = $Dwolla->getAuthUrl();
header("Location: {$authUrl}");
}
/**
* STEP 2:
* Exchange the temporary code given
* to us in the querystring, for
* a never-expiring OAuth access token
**/
if(isset($_GET['error'])) {
echo "There was an error. Dwolla said: {$_GET['error_description']}";
}
else if(isset($_GET['code'])) {
$code = $_GET['code'];
$token = $Dwolla->requestToken($code);
if(!$token) { $Dwolla->getError(); } // Check for errors
else {
session_start();
$_SESSION['token'] = $token;
echo "Your access token is: {$token}";
} // Print the access token
}
TL;DR - No, that's not how OAuth works
The whole point of the OAuth scheme is authentication on the website of the service that you want to use, in this case, Dwolla. By forcing the user to go to their page it ensures a few things:
The user is made aware that they are using an external service whose terms of service may be different than your application
The user is made aware of the features requested by your application for that service. In dwolla's case there are different levels of functionality that can be requested by your application including transferring of money, so it's important that your users are aware of that!
You can read up more on OAuth at http://oauth.net/

Categories