How to get oauth_verification using PECL OAUTH? - php

I'm trying to get the verification code using php, but as I can see, there is only "manual" (I have to authorize manually) solution for this.
Is there any way to authorize your request token using pecl oauth? I see only getAccessToken and getRequestToken functions, there is nothing for authentication.
The following process requires the verification code at getAccessToken:
private function accessToken( $request_token, $request_token_secret ){
$oauth = $this->oauth;
$access_url = $this->access_url;
$authorize_url = $this->authorize_url;
$consumer_key = $this->consumer_key;
$consumer_secret = $this->consumer_secret;
try {
$oauth = new OAuth( $consumer_key, $consumer_secret );
$oauth->setToken( $request_token, $request_token_secret );
$access_token_info = $oauth->getAccessToken( $access_url, null, VERIFICATION_CODE );
if(!empty($access_token_info)) {
//print_r($access_token_info);
return $access_token_info;
} else {
print "Failed fetching access token, response was: " . $oauth->getLastResponse();
return false;
}
} catch(OAuthException $E) {
echo "Response: ". $E->lastResponse . "\n";
return false;
}
}

Related

"Login with Google" in PHP - Google+ API shutdown migration - how to migrate away from plus.people.get?

I got a warning email from Google reminding me of Google+'s EOL which is supposed to break my current "Login with Google", but I am unsure what exactly should I change.
Let me show you my (simplified) login code:
google-login.php
new class {
public function __construct() {
$state = mt_rand();
$client = new Google_Client();
$client->setApplicationName(Config::Google['app_name']);
$client->setClientId(Config::Google['id']);
$client->setClientSecret(Config::Google['secret']);
$client->setRedirectUri(sprintf('https://%s/members/google-callback.php', $_SERVER['HTTP_HOST']));
$client->setScopes(['profile', 'email']);
$client->setState($state);
$_SESSION['state'] = $state;
$url = $client->createAuthUrl(); // $url = https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=online&client_id=CLIENT_ID.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fread2me.online%2Fmembers%2Fgoogle-callback.php&state=1588245f23f2a&scope=profile%20email&approval_prompt=auto
header ("location: $url");
}
};
google-callback.php
new class {
private $newUser = false;
public function __construct() {
if (!isset($_GET['state']) || $_GET['state'] != $_SESSION['state'])
die('State mismatch.');
$client = new Google_Client();
$client->setApplicationName(Config::Google['app_name']);
$client->setClientId(Config::Google['id']);
$client->setClientSecret(Config::Google['secret']);
$client->setRedirectUri(sprintf('https://%s/members/google-callback.php', $_SERVER['HTTP_HOST']));
$client->setScopes(['profile', 'email']);
$plus = new Google_Service_Plus($client);
if (isset($_GET['code'])) {
$client->fetchAccessTokenWithAuthCode($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken() || $client->isAccessTokenExpired()) {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$url = $client->createAuthUrl();
header ("location: $url");
}
try {
$me = $plus->people->get('me');
} catch (Google_Exception $e) {
\Rollbar::report_message($e->getMessage());
print_r($e->getMessage());
return;
}
$accessToken = $client->getAccessToken()['access_token'];
$email = $me->getEmails()[0]->getValue();
$name = $me->getDisplayName();
$avatar = $me->getImage()->getUrl();
$id = $me->getId();
if ($this->isEmailInSystem($email) === false) {
$this->newUser = true;
$this->addUser($email, $name, 'google', $accessToken, $id, $avatar);
}
header ("location: " . '/');
}
};
Now, I'm going through at what seems to be the up-to-date Sign In guide for PHP, but I am not sure what to change - any ideas?
Thanks
The best migration is to move from the Plus API to the People API, which provides access to the user's profile in a similar (tho not quite identical) way.
You would replace the creation of the $plus object with a new Goolge_Service_PeopleService object. Something like
$people = new Google_Service_PeopleService( $client );
Getting the profile is more involved since you need to specify which fields from the profile you want to get. But you might do it something like
$profile = $people->people->get(
'people/me',
array('personFields' => 'names,emailAddresses,photos')
);
The first parameter needs to be "people/me" to specify that you're requesting the authorized user's profile.
The second is an array of query parameters. You need to specify the "personFields" that you want from the list of what is available (scroll down on this page till you see the description of the available fields) and specify this as a comma separated list in a string. In my example above, I illustrate getting the name, email addresses, and photos. But consult the list and experiment.
The exact fields you get from the result in $profile will be different than those you got from $plus, but they should match the fields you requested. Check the values and exactly how they're structured.
I ran into the same issue as Google+ APIs shutting down on March 7, 2019.
Make sure Google People API is enable in your google console
I used google-api-php-client Library.
Once you have an access token here is code to get the person object using people API
$accessToken = 'REPLACE_WITH_ACCESS_TOKEN';
$clientId = 'REPLACE_WITH_CLIENT_ID';
$clientSecret = 'REPLACE_WITH_CLIENT_SECRET';
$developerKey = 'REPLACE_WITH_DEVELOPER_KEY';
$client = new Google_Client();
$client->setApplicationName("Application Name");
$client->setClientId($clientId . '.apps.googleusercontent.com');
$client->setClientSecret($clientSecret);
$client->setDeveloperKey($developerKey);
$client->setScopes(['https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile']);
$client->setAccessToken($accessToken);
$guzzleClient = new \GuzzleHttp\Client(array( 'curl' => array( CURLOPT_SSL_VERIFYPEER => false, ), ));
$client->setHttpClient($guzzleClient);
$people = new Google_Service_PeopleService( $client );
if ($client->getAccessToken()) {
try {
$me = $people->people->get(
'people/me',
array('personFields' => 'emailAddresses,names,photos')
);
$id = preg_replace('/[^0-9]/', '', $me->getResourceName());
$email = $me->getEmailAddresses()[0]->value;
$name = $me->getNames()[0]->displayName;
$avtar = $me->getPhotos()[0]->getUrl();
} catch (Google_Exception $e) {
// error
echo $e->getMessage();
}
}
I also disabled Google+ API to make sure the application is not using it anymore anywhere.
With latest version of Google API PHP Client you can fetch profile details from Google_Client object itself.
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$attributes = $client->verifyIdToken($token['id_token'], GOOGLE_CLIENT_ID);
print_r($attributes);
Refer this article.
Obviously, the lines
$plus = new Google_Service_Plus($client);
and
$me = $plus->people->get('me');
You need to use google email API, see https://developers.google.com/gmail/api/quickstart/php , so the first line will be
$service = new Google_Service_Gmail($client);
and second ... hmmm ... not sure there WILL be any avatar after removing of google plus ...

Getting blank data in a SalesForce integration with PHP

I am trying integration with SalesForce using SOAP webservice.
I can build a connection with PHP and SOAP after that if I'm trying to call my method that is authenticate user, I am not getting any data, I'm getting blank.
Below is the code
define("USERNAME", "xxxxxxxxxxx");
define("PASSWORD", "xxxxxxxxxxx");
define("SECURITY_TOKEN", "xxxxxxxxxxx");
require_once ('soapclient/SforcePartnerClient.php');
require_once ('soapclient/SforceHeaderOptions.php');
// Login
$sfdc = new SforcePartnerClient();
$SoapClient = $sfdc->createConnection('soapclient/PartnerWSDL.xml');
$loginResult = false;
$loginResult = $sfdc->login('USERNAME', 'PASSWORD' . 'SECURITY_TOKEN');
// Define constants for the web service. We'll use these later
$parsedURL = parse_url($sfdc->getLocation());
define ("_SFDC_SERVER_", substr($parsedURL['host'],0,strpos($parsedURL['host'], '.')));
define ("_WS_NAME_", 'CustomerPortalServices');
define ("_WS_WSDL_", _WS_NAME_ . '.xml');
define ("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_);
//echo _WS_ENDPOINT_;
define ("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);
// SOAP Client for Web Service
$client = new SoapClient('http://localhost/SFDC/soapclient/CustomerPortalServices_WSDL.xml');
$sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" => $sfdc->getSessionId()));
$client->__setSoapHeaders(array($sforce_header));
// username and password sent from Form
echo $myusername=addslashes($_POST['login_username']);
echo $mypassword=addslashes($_POST['login_password']);
try {
// call the web service via post
$wsParams=array(
'username'=>'abc#gmail.com',
'password'=>'mypassword'
);
print_r($wsParams);
$response = $client->authenticateUser($wsParams);
// dump the response to the browser
print_r($response);
//header("location: index.php");
// this is really bad.
} catch (Exception $e) {
global $errors;
$errors = $e->faultstring;
echo "Ooop! Error: <b>" . $errors . "</b>";
die;
}
This is the method i am calling
global class CustomerPortalServicesNew {
webService static Summary authenticateUserNew(String uname,String passwd) {
System.debug('##'+'Entered in the authenticateUser');
List<contact> checkConList = new List<Contact>([select id,Email, Password__c, AccountId from contact where Email =:uname]);
System.debug('##'+'contact '+checkConList);
for(contact c:checkConList){
system.debug('##'+'Iterating in contactList'+checkConList);
if(c.Password__c==passwd){
system.debug('##'+c.AccountId);
return getAccountSummary(c.AccountId);
}
else{
system.debug('##'+'password has not matched');
return null;
}
}
system.debug('##'+'class finished');
return null;
}
I am getting response like this
object(stdClass)[8]
public 'result' =>
object(stdClass)[9]
not getting data
I think you need to print:
print_r($response->result);
If it's not working, try a var_dump($response)

got a 401 when I get access token for LinkedIn

$oauth->getAccessToken() causes Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect).
How do I look at the request headers to figure out what exactly is wrong?
$oauth = new OAuth(CONSUMER_KEY, CONSUMER_SECRET);
$oauth->disableSSLChecks();
$request_token_response = $oauth->getRequestToken('https://api.linkedin.com/uas/oauth/requestToken');
if($request_token_response === FALSE) {
throw new Exception("Failed fetching request token, response was: " . $oauth->getLastResponse());
} else {
$request_token = $request_token_response;
var_dump($request_token);
if (!isset($_GET['oauth_verifier'])) {
$this->redirect("https://api.linkedin.com/uas/oauth/authorize?oauth_token=" . $request_token['oauth_token']);
} else {
$oauth_verifier = $_GET['oauth_verifier'];
$oauth->setToken($request_token['oauth_token'], $request_token['oauth_token_secret']);
$access_token_url = 'https://api.linkedin.com/uas/oauth/accessToken';
$access_token_response = $oauth->getAccessToken($access_token_url, "", $oauth_verifier);
if($access_token_response === FALSE) {
throw new Exception("Failed fetching request token, response was: " . $oauth->getLastResponse());
} else {
$access_token = $access_token_response;
$params = array();
$headers = array();
$method = OAUTH_HTTP_METHOD_GET;
// Specify LinkedIn API endpoint to retrieve your own profile
$url = "http://api.linkedin.com/v1/people/~";
// By default, the LinkedIn API responses are in XML format. If you prefer JSON, simply specify the format in your call
// $url = "http://api.linkedin.com/v1/people/~?format=json";
// Make call to LinkedIn to retrieve your own profile
$oauth->fetch($url, $params, $method, $headers);
echo $oauth->getLastResponse();
}
}
}
}
oauth_verifier only verifies the request_token from which it was obtained. I needed to store the original request_token in session instead of getting a new request_token on callback.

Two-legged OAuth Yahoo PHP example

I try to make private API requests for Yahoo. I used the code below but it does not work. It always returns the message 'invalid sig'.
Can you help me with a Two-legged OAuth Yahoo PHP example that works?
Thank you very much.
<?php // a super-stripped down 2-leg oauth server/client example
//http://oauth.net/code/
//http://oauth.googlecode.com/svn/code/php/OAuth.php
require 'oauth.php';
$key = 'key';
$secret = 'secret';
$consumer = new OAuthConsumer($key, $secret);
$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
if ($_GET['server']) {
$method = $_SERVER['REQUEST_METHOD'];
$uri = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$sig = $_GET['oauth_signature'];
$req = new OAuthRequest($method, $uri);
// token is null because we're doing 2-leg
$valid = $sig_method->check_signature($req, $consumer, null, $sig);
if (!$valid) {
die('invalid sig');
}
echo 'orale!';
}
else {
// call this file
$api_endpoint = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'];
// handle request in 'server' block above
$parameters = array(
'server' => 'true');
// use oauth lib to sign request
$req = OAuthRequest::from_consumer_and_token($consumer, null, "GET", $api_endpoint, $parameters);
$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
$req->sign_request($sig_method, $consumer, null); // note: double entry of token
// get data using signed url
$ch = curl_init($req->to_url());
curl_exec($ch);
curl_close($ch);
}
Do you generate the signature according to the Yahoo specification here?
Or you can use plaintext signature as described here.

Sending BTC with Coinbase's API?

https://coinbase.com/api/v1/transactions/send_money?api_key=xxx
I have that URL but after the api_key paramter what comes next (I blocked out my API Key so people can't access my BTC)?
Can someone give me an example of how to properly use coinbase's send_money API?
I don't have a PHP environment handy to test this with but I think it would go like this:
Get their PHP library: https://github.com/coinbase/coinbase-php
<?php
require_once(dirname(__FILE__) . '/../lib/Coinbase.php');
// Create an application at https://coinbase.com/oauth/applications and set these values accordingly
$_CLIENT_ID = "83a481f96bf28ea4bed1ee8bdc49ba4265609efa40d40477c2a57e913c479065";
$_CLIENT_SECRET = "a8dda20b94d09e84e8fefa5e7560133d9c5af9da93ec1d3e79ad0843d2920bbb";
// Note: your redirect URL should use HTTPS.
$_REDIRECT_URL = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$coinbaseOauth = new Coinbase_OAuth($_CLIENT_ID, $_CLIENT_SECRET, $_REDIRECT_URL);
if(isset($_GET['code'])) {
// Request tokens
$tokens = $coinbaseOauth->getTokens($_GET['code']);
// The user is now authenticated! Access and refresh tokens are in $tokens
// Store these tokens safely, and use them to make Coinbase API requests in the future.
// For example:
$coinbase = new Coinbase($coinbaseOauth, $tokens);
try {
echo 'Balance: ' . $coinbase->sendMoney($to, $amount, $notes=null, $userFee=null, $amountCurrency=null) . '<br>';
echo $coinbase->createButton("Alpaca socks", "10.00", "CAD")->embedHtml;
} catch (Coinbase_TokensExpiredException $e) {
$newTokens = $coinbaseOauth->refreshTokens($tokens);
// Store $newTokens and retry request
}
} else {
// Redirect to Coinbase authorization page
// The provided parameters specify the access your application will have to the
// user's account; for a full list, see https://coinbase.com/docs/api/overview
// You can pass as many scopes as you would like
echo "Connect with Coinbase";
}
Here is the send money code
public function sendMoney($to, $amount, $notes=null, $userFee=null, $amountCurrency=null)
{
$params = array( "transaction[to]" => $to );
if($amountCurrency !== null) {
$params["transaction[amount_string]"] = $amount;
$params["transaction[amount_currency_iso]"] = $amountCurrency;
} else {
$params["transaction[amount]"] = $amount;
}
if($notes !== null) {
$params["transaction[notes]"] = $notes;
}
if($userFee !== null) {
$params["transaction[user_fee]"] = $userFee;
}
return $this->post("transactions/send_money", $params);
}

Categories