When i try to request additional permissions from linkedin i do not get any permissions list in the dialog except for the basic permisiions. Could any1 point me to the solution. I tried urlencoding the permissions but still not getting any response. Here is my code: I am calling this function on click of 'Signup with Linkedin' button.
public function linkedinaccessAction()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$scope = 'r_basicprofile+r_emailaddress+r_network+r_contactinfo';
$options = array(
'version' => '1.0',
'siteUrl' => 'http://localhost/project/development/',
'callbackUrl' => 'http://localhost/project/development/signup/linkedinaccess',
'requestTokenUrl' => 'https://api.linkedin.com/uas/oauth/requestToken?scope=' . $scope,
'userAuthorizationUrl' => 'https://api.linkedin.com/uas/oauth/authorize',
'accessTokenUrl' => 'https://api.linkedin.com/uas/oauth/accessToken',
'consumerKey' => 'myconsumerkey',
'consumerSecret' => 'myconsumersecret'
);
$consumer = new Zend_Oauth_Consumer( $options );
if (!isset($_SESSION ['LINKEDIN_ACCESS_TOKEN'])){
if(! empty ( $_GET )){
//consumer = new Zend_Oauth_Consumer( $options );
$accessToken = $consumer->getAccessToken ( $_GET, unserialize ( $_SESSION ['LINKEDIN_REQUEST_TOKEN'] ) );
echo $accessToken;
$_SESSION ['LINKEDIN_ACCESS_TOKEN'] = serialize ( $accessToken );
}else{
$requestToken = $consumer->getRequestToken();
$_SESSION ['LINKEDIN_REQUEST_TOKEN'] = serialize ( $requestToken );
$consumer->redirect();
}
}else{
$accessToken = unserialize ( $_SESSION ['LINKEDIN_ACCESS_TOKEN'] );
// Use HTTP Client with built-in OAuth request handling
$client = $accessToken->getHttpClient($options);
// Set LinkedIn URI
$client->setUri('https://api.linkedin.com/v1/people/~');
// Set Method (GET, POST or PUT)
$client->setMethod(Zend_Http_Client::GET);
// Get Request Response
$response = $client->request();
// Get the XML containing User's Profile
$content = $response->getBody();
print_r($content);
}
}
Thank you.
After rigorous searching finally got the solution from this Linkedin Post
Need to request linkedin permissions as a part of getRequestToken Call:
$requestToken = $consumer->getRequestToken(array('scope' =>'r_emailaddress'));
Related
Here's how I try to get the user data from LinkedIn:
$config = array(
'appKey' => 'appKey',
'appSecret' => 'appSecret',
'callbackUrl' => 'callbackUrl'
);
#session_start();
$linkedin = new LinkedInOAuth2( $config );
if ( $_GET['login_type'] == 'linkedin_login' ) {
$scope = array( 'r_emailaddress', 'r_basicprofile' );
social_js_redirect( $linkedin-getAuthorizeUrl( $config['appKey'], $config['callbackUrl'], $scope ) );
} elseif ( ! empty( $_GET['code'] && ! empty( $_GET['state'] ) ) ) {
$data = $linkedin->getAccessToken( $config['appKey'], $config['appSecret'], $config['callbackUrl'] );
if ( ! empty( $data['access_token'] ) ) {
$linkedin->getProfile(); // Get user data from linkedin to add to database
} else {
// Invalid Authorization
}
}
This is the error code that adds into the database:
Array
(
[0] => Array
(
[errorCode] => 0
[message] => Then token used in this request has been revoked by the user.
[requestId] => xxx
[status] => 401
[timestamp] => 1540051999134
)
)
NOTE: By check my PHP code you will understand that LinkedIn successfully get the access token
could you try adding a delay of 5-6 seconds after obtaining the token. Most problems i see on stackoverflow/github regarding this problem has to due to the fact that LinkedIn doesnt seem to activate the token that it gives immediately, so waiting a bit helps.
I am trying to get sessionid by using ebay Trading API . I am able to get session id successfully by using Curl but as soon as i try to fetch session id via Guzzle Http client, get below error in response from ebay
FailureUnsupported API call.The API call "GeteBayOfficialTime" is
invalid or not supported in this release.2ErrorRequestError18131002
I suppose there's some issues with the way i am using GuzzleHttp client . I am currently using GuzzleHttp v6 and new to this . Below is the code i am using to get session id by calling actionTest function
public function actionTest(){
$requestBody1 = '<?xml version="1.0" encoding="utf-8" ?>';
$requestBody1 .= '<GetSessionIDRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
$requestBody1 .= '<Version>989</Version>';
$requestBody1 .= '<RuName>test_user-TestAs-Geforc-ldlnmtua</RuName>';
$requestBody1 .= '</GetSessionIDRequest>';
$headers = $this->getHeader();
$client = new Client();
$request = new Request('POST','https://api.sandbox.ebay.com/ws/api.dll',$headers,$requestBody1);
$response = $client->send($request);
/*$response = $client->post('https://api.sandbox.ebay.com/ws/api.dll', [
'headers' => $headers,
'body' => $requestBody1
]);*/
echo $response->getBody();die;
}
public function getHeader()
{
$header = array(
'Content-Type: text/xml',
'X-EBAY-API-COMPATIBILITY-LEVEL: 989',
'X-EBAY-API-DEV-NAME: a4d749e7-9b22-441e-8406-d3b65d95d41a',
'X-EBAY-API-APP-NAME: TestUs-GeforceI-SBX-345ed4578-10122cfa',
'X-EBAY-API-CERT-NAME: PRD-120145f62955-96aa-4d748-b1df-6bf4',
'X-EBAY-API-CALL-NAME: GetSessionID',
'X-EBAY-API-SITEID: 203',
);
return $header;
}
Plz suggest the possible shortcoming in the way i am making request . I already tried/modified the guzzle request call by referring various reference site and guzzle official doc but error remained same .
You need to pass an associative array of headers as explained in the documentation.
public function getHeader()
{
return [
'Content-Type' => 'text/xml',
'X-EBAY-API-COMPATIBILITY-LEVEL' => '989',
'X-EBAY-API-DEV-NAME' => '...',
'X-EBAY-API-APP-NAME' => '...',
'X-EBAY-API-CERT-NAME' => '...',
'X-EBAY-API-CALL-NAME' => '...',
'X-EBAY-API-SITEID' => '203',
];
}
In case you are interested there is an SDK available that simplifies the code. An example of how to call GetSessionID is shown below.
<?php
require __DIR__.'/vendor/autoload.php';
use \DTS\eBaySDK\Trading\Services\TradingService;
use \DTS\eBaySDK\Trading\Types\GetSessionIDRequestType;
$service = new TradingService([
'credentials' => [
'appId' => 'your-sandbox-app-id',
'certId' => 'your-sandbox-cert-id',
'devId' => 'your-sandbox-dev-id'
],
'siteId' => '203',
'apiVersion' => '989',
'sandbox' => true
]);
$request = new GetSessionIDRequestType();
$request->RuName = '...';
$response = $service->getSessionID($request);
echo $response->SessionID;
this is my code, i am trying to post tweet with image, but only text get posted?I really really want to post image as well. I am pulling my hair out for that, HELP!!?
<?php
error_reporting(E_ALL);
require_once('TwitterAPIExchange.php');
//echo 'start';
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
require_once('connect.php');
$recid=$_GET['recid'];
//echo $recid;
$dsn='mysql:host='.$hostname.';dbname=twitter_db';
try{
$dbh=new PDO($dsn,$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$stmt=$dbh->prepare("SELECT * FROM gr_twitter WHERE recid=:recid");
$stmt->execute(array(
'recid'=>$recid
));
$foundResult=$stmt->fetchAll();
$tweetmsg=$foundResult[0]['tweet'];
$tweetImage=$foundResult[0]['tweetImageName'];
$timestamp=$foundResult[0]['sentTimestamp'];
print_r($foundResult);
$stmt2=$dbh->prepare("UPDATE gr_twitter SET sent=1 WHERE recid=:recid");
$stmt2->execute(array(
'recid'=>$recid
));
}
catch(PDOException $e){}
// Perform a GET request and echo the response **/
/** Note: Set the GET field BEFORE calling buildOauth(); **/
$url = 'https://api.twitter.com/1.1/statuses/update.json';
$requestMethod='POST';
////images is stored in D:\Databases\RC_Data_FMS\images\Files\images\tweetImage folder
$tweetImage='D:\Databases\RC_Data_FMS\images\Files\images\tweetImage/images.jpg';
$postfields = array(
'status' => $tweetmsg,
'media' => "#{$tweetImage}"
);
/** POST fields required by the URL above. See relevant docs as above **/
//print_r($postfields).'<br />';
$twitter = new TwitterAPIExchange($Yh_settings);
$response= $twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
echo "Success, you just tweeted!<br />";
var_dump(json_decode($response));
//////////////////////////////////////////////////////////////////////////
function objectToArray($d)
{
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
// return array_map(__FUNCTION__, $d);
} else {
// Return array
// return $d;
}
}
?>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
I recommend you to use tmhOAuth library if you want to post images that are located in your server.
Here you have an example:
<?php
require_once('./tmhOAuth.php');
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => CONSUMER_KEY,
'consumer_secret' => CONSUMER_SECRET,
'user_token' => OAUTH_TOKEN,
'user_secret' => OAUTH_TOKEN_SECRET
));
$tweetText = 'Your text here';
$imageName = 'picture.png';
$imagePath = dirname(__FILE__) . DIRECTORY_SEPARATOR . $imageName;
$code = $tmhOAuth->request(
'POST',
$tmhOAuth->url('1.1/statuses/update_with_media'),
array(
'media[]' => "#{$imagePath};type=image/png;filename={$imageName}",
'status' => $tweetText
),
true, // use auth
true // multipart
);
?>
Hope this helps!
I have a problem with Github api.
I parse the access_token but when i try to get the user I get the following error:
Warning: file_get_contents(https://api.github.com/user?access_token=mplamplampla): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden
When I try to get the contents through address bar in my browser is working!
My code:
//Get the access token
$postdata = http_build_query(
array(
'client_id' => 'mplamplaID',
'client_secret' => 'mplamplaSECRET',
'code' => trim($_GET['code']),
'redirect_uri' => 'http://vlingos.com/github.php'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$vip = file_get_contents('https://github.com/login/oauth/access_token',false,$context);
parse_str($vip);
//Get the User
$json = file_get_contents('https://api.github.com/user?access_token='.$access_token);
if(isset($json) and (is_array($json)===true or is_object($json)===true)){
$jsonIterator = new RecursiveIteratorIterator(new RecursiveArrayIterator(json_decode($json, TRUE)),RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
$git_user[$key] = $val;
}
print_r($git_user);
}else{
echo "can't get user";
}
Can someone propose something?
kindest regards
Enable your token is correct. generate new token, refer to:https://help.github.com/articles/creating-an-access-token-for-command-line-use/
test it:
curl https://api.github.com/user?access_token=your token
I had some really complicated code, and now I've made it ridiculously simple, and it doesn't work.
Currently it simply takes me back to the page with the login URL echoed out.
Code is here:
<?php
require 'facebook.php';
// Create our application instance
// (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'sd',
'secret' => 'sda',
));
// Get User ID
$user = $facebook->getUser();
if($user) {
echo $user;
} else {
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>'http://www.facebook.com/pages/CharlesTestPage/225802194155435?sk=app_252946408094785','scope'=>'email'));
echo $loginUrl;
}
exit;
?>
Please. I have spent a whole paid work day on this now, and am at the point of crying, not only for myself but for my boss.
Cry.
Edit: OK, the weird thing is, if I have the redirect_uri set to the facebook tab, if it's not authenticated itself, then it constantly redirects in an infinite loop. However, if I remove the redire
This is what's working for me using PHP SDK 3.1.1. Try it and let us know if this works:
include('facebook.php');
session_start();
//facebook application
$config['appid' ] = "YOUR_APP_ID";
$config['secret'] = "YOUR_APP_SECRET";
$config['baseurl'] = "http://example.com/facebookappdirectory";
$config['appbaseurl'] = "http://apps.facebook.com/your-app-name";
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $config['appid'],
'secret' => $config['secret'],
'cookie' => true,
));
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email'
)
);
if ($user) {
try {
//get user basic description
$userInfo = $facebook->api("/$user");
$fb_access_token = $facebook->getAccessToken();
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
error_log('APP ERROR: '.$e);
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
if (isset($_GET['code'])){
header("Location: " . $config['appbaseurl']);
exit;
}
Check for
if(isset($_GET['code'])){
$user = $facebook->getUser();
$access_token = $facebook->getAccessToken();
}
Facebook return userID only after the login and that code.