poloniex futures api php - php

I am unable to POST data to Poloniex Futures API. While the GET works fine.
The POST returns 400005 [msg] => Invalid PF-API-SIGN
Here is the Code for config.php
global $baseurl;
$baseurl = "https://futures-api.poloniex.com";
global $api_key;
$api_key = "XXXXX";
global $api_secret;
$api_secret = "XXXXX";
global $api_passphrase;
$api_passphrase = "XXXXXX";
function signature($request_path = '', $body = '', $timestamp = false, $method = 'POST') {
$body = is_array($body) ? json_encode($body) : $body; // Body must be in json format
$timestamp = $timestamp ? $timestamp : time() * 1000;
$what = $timestamp . $method . $request_path . $body;
return base64_encode(hash_hmac("sha256", $what, $api_secret, true));
}
Working code to get Ticket Data
Code for ticker.php
include_once "config.php";
$endpoint = "/api/v1/position?symbol=BTCUSDTPERP";
$url = "https://futures-api.poloniex.com".$endpoint;
$sigs = signature($endpoint,'',true,"GET");
$now = time() * 1000;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
"PF-API-SIGN: $sigs",
"PF-API-TIMESTAMP: $now",
"PF-API-KEY: $api_key",
"PF-API-PASSPHRASE: $api_passphrase"
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec ($ch);
curl_close ($ch);
$return_data = json_decode($server_output ,true);
print_r($return_data );
Here is what I have tried for Add Margin Manually
POST /api/v1/position/margin/deposit-margin
Code for post_data.php
include_once "config.php";
$endpoint = "/api/v1/position/margin/deposit-margin";
$url = "https://futures-api.poloniex.com".$endpoint;
$now = time() * 1000;
$vars_margin = ["symbol"=>"BTCUSDTPERP","margin"=>1,"bizNo"=>"1112222"];
$vars_margin = json_encode($vars_margin);
$vars_margin_post_fields = "symbol=BTCUSDTPERP&margin=1&bizNo=1112222";
$sigs = signature($endpoint,$vars_margin,true,"POST");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars_margin_post_fields); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
"PF-API-SIGN: $sigs",
"PF-API-TIMESTAMP: $now",
"PF-API-KEY: $api_key",
"PF-API-PASSPHRASE: $api_passphrase"
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec ($ch);
curl_close ($ch);
$return_data = json_decode($server_output ,true);
print_r($return_data );
Really not sure why the post method always says
Array ( [code] => 400005 [msg] => Invalid PF-API-SIGN )
Any help will be appreciated.
Thanks

The Post fields should match what was signed, the json_encoded value.
So try this:
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars_margin);
and be sure to add a header to indicate that the POST data is json encoded:
...
"PF-API-PASSPHRASE: $api_passphrase",
"content-type: application/json"
];

Related

How to add an object parameter into a string post api curl?

Can someone help me to fix this issue, i need to provide an object type parameter to my code to fetch data using shopee API.
here is my code
$partner_key = "c423d22ccf4a8f1ca3cf9f49d7995f7d2a11e58b6a57036bd8385e8d978b4db2";
$partner_id = 2003151;
$shop_id = 30334567;
$ordersn = "";
$username = "info#pollandhopia.com";
$password = "101382qpqeiw";
$datenow = time();
$parcel->item_id = 455371271;
$parcel->variation_id = 0;
$parcel->order_item_id = 455371271;
$parcel->promotion_group_id = 0;
$object = json_encode($parcel);
$post = '{
"shopid": '.$shop_id.',
"ordersn": "220506EWDX3UXW",
"partner_id": '.$partner_id.',
"timestamp": '.$datenow.',
"parcels": '.$parcel.'
}';
$url = "https://partner.shopeemobile.com/api/v1/orders/split";
//Generate a signature base string for POST
$base_string = $url."|".$post;
//Generate a unique signature
$signature = hash_hmac('sha256', $base_string, $partner_key);
#echo $signature.'----'.$datenow.'-'.$object;exit;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization:".$signature, "Content-Type: application/json"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$result = json_decode($result);
curl_close($ch);
Then the documentation params is here
Here is my error:
An uncaught Exception was encountered
Type: Error
Message: Object of class stdClass could not be converted to string

Binance REST API - Placing a PHP Order (POST) via Query String

I am struggling using Binance's REST API. I have managed to get working GET request via query string such as pinging the server, ticker information, etc. My challenge now is performing POST request via query string using cURL. I have been scraping code from various places and referring back to the API to get pieces to work but I am unsure as to why I am getting this error returned from the result... {"code":-1102,"msg":"Mandatory parameter 'signature' was not sent, was empty/null, or malformed."}
(ERROR SHOWN ON WEBPAGE). I echo out the signature and its a load of gibberish so I would believe that the hash_hmac performed at the top would be working, but honestly I got pretty lucky making the GET request work. Does anyone have any suggestions as to why this would be broken? Thanks!
$apikey = "MYKEY";
$apisecret = "MYSECRET";
$timestamp = time()*1000; //get current timestamp in milliseconds
$signature = hash_hmac('sha256', "TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=".$timestamp, $apisecret);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.binance.com/api/v3/order/test");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=".$timestamp);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey,"signature: ".$signature));
$response = curl_exec($ch);
curl_close($ch);
echo $response;
As per their API docs:
SIGNED endpoints require an additional parameter, signature, to be sent in the query string or request body.
You are sending the signature via neither of these methods and are instead sending it through the header.
Change this:
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=".$timestamp);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey,"signature: ".$signature));
To this:
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=" . $timestamp . "&signature=" . $signature);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey));
<?php
$secret = "F................";
$key = "D.................";
$s_time = "timestamp=".time()*1000;
$sign=hash_hmac('SHA256', $s_time, $secret);
$url = "https://api.binance.com/api/v3/account?".$s_time.'&signature='.$sign;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-MBX-APIKEY:'.$key));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
$result = json_decode($result, true);
echo '<pre>';
var_dump($result);
echo '</pre>';
?>
Here is an example, using php-curl-class
// Variables
// url, key and secret is on separate file, called using require once
$endPoint = "/api/v3/order/test";
$coin = "BTC";
$fiat = "EUR";
$symbol = $coin . "" . $fiat;
$side = "BUY";
$type = "LIMIT";
$timeInForce = "GTC";
$quantity = 1;
$price = 10000;
$timestamp = time();
// Constructing query arrays
queryArray = array(
"symbol" => $symbol,
"side" => $side,
"type" => $type,
"timeInForce" => $timeInForce,
"quantity" => $quantity,
"price" => $price,
"timestamp" => $timestamp*1000
);
$signature = hash_hmac("sha256", http_build_query($queryArray), $secret);
$signatureArray = array("signature" => $signature);
$curlArray = $queryArray + $signatureArray;
// Curl : setting header and POST
$curl->setHeader("Content-Type","application/x-www-form-urlencoded");
$curl->setHeader("X-MBX-APIKEY",$key);
$curl->post($url . "" . $endPoint, $curlArray);
if ($curl->error) {
echo 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "\n";
}
$order = $curl->response;
print_r($order);
I had the same problem, and nothing of above doesn't helped.
So I finaly figured out how to make order on my way.
So, maybe this helps someone.
function Kupovina($buy_parametri) {
$key = "xxxxxxxxxxxxxxx";
$secret = "xxxxxxxxxxxx";
$s_time = "timestamp=".time()*1000;
$timestamp = time()*1000; //get current timestamp in milliseconds
$sign = hash_hmac('sha256', $buy_parametri."&timestamp=".$timestamp, $secret);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.binance.com/api/v3/order");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $buy_parametri."&".$s_time."&signature=".$sign);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$key));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$buy_parametri = "symbol=BTCUSDT&type=market&side=buy&quantity=0.00086";
Call function:
Kupovina($buy_parametri);

I cant create an order with kucoin api with php

Hello im using that code to create buy order but it shows me that error "{"code":"UNAUTH","msg":"Signature verification failed","success":false,"timestamp":1517154443105}"
$ku_key = 'KEY';
$ku_secret = 'SECRET';
$host = "https://api.kucoin.com";
$nonce = round(microtime(true) * 1000);
$endpoint = "/v1/order";
$querystring = "symbol=POE-BTC&price=0.00000748&amount=5514.70588235&type=BUY";
$signstring = $endpoint.'/'.$nonce.'/'.$querystring;
$hash = hash_hmac('sha256', base64_encode($signstring) , $ku_secret);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host . $endpoint);
$headers = [ 'KC-API-SIGNATURE:' . $hash, 'KC-API-KEY:' . $ku_key, 'KC-API-NONCE:' . $nonce, 'Content-Type:application/json' ];
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; Kucoin Bot; '.php_uname('a').'; PHP/'.phpversion().')' );
/*
YOU CAN USE THIS SECTION, I USE BOTH OF THEM WITH THIS AND WITHOUT THIS. NOT WORKING WITH BOTH.
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=POE-BTC&price=0.00000748&amount=5514.70588235&type=BUY");
*/
curl_setopt($ch, CURLOPT_URL, $host . $endpoint);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = curl_exec($ch);
var_dump($data);
I was facing the same error message today when I was implementing the KuCoin API in my trader software. However, I got it working. Please find my working solution below:
/**
*
* #see https://kucoinapidocs.docs.apiary.io/#introduction/authentication/signature-calculation
*
*/
private function signedRequest($endpoint, $params = array())
{
$ch = curl_init();
// Must be synced, KuCoin rejects requests > 3s
$nonce = round(microtime(true) * 1000);
// Build the data string.
// Note - According documentation:
// Arrange the parameters in ascending alphabetical order (lower cases first)
$queryString = http_build_query($params, '', '&');
// Splice string for signing
$auth = $endpoint . '/' . $nonce . '/' . $queryString;
// Make a base64 encoding of the completed string
$signedStr = base64_encode($auth);
$signature = hash_hmac('sha256', $signedStr, $this->secret);
$headers = array (
'KC-API-KEY:' . $this->key,
'KC-API-NONCE:' . $nonce,
'KC-API-SIGNATURE:' . $signature,
);
// POST is not allowed so we attach the parameter to the url
$curl = $this->base . $endpoint . "?" . $queryString;
// make the request
curl_setopt($ch, CURLOPT_URL, $curl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// do not print output to screen
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
return $result;
}
Tested with endpoint '/v1/account/balances'
public function getWalletBalance()
{
$params = array(
'limit' => '12',
'page' => '1'
);
$balance = $this->signedRequest("/v1/account/balances", $params);
return $this->_getFormattedBalance($balance);
}
You need to order your params alphabetically in both the query string and post request. Their docs need a little improvement but this is stated in them somewhere.
$querystring = "amount=5514.70588235&price=0.00000748&symbol=POE-BTC&type=BUY";
curl_setopt($ch, CURLOPT_POSTFIELDS, "amount=5514.70588235&price=0.00000748&symbol=POE-BTC&type=BUY");

interswitch quickteller API integration in php

i have to add interswitch payment methods in my web application but i am receiving error
following is my code
function billersCategories()
{
$nonce=$randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyz"), 0, 60);
$date = new DateTime();
$timestamp=$date->getTimestamp();
// Signature
$httpMethod = "GET";
$url='https://sandbox.interswitchng.com/api/v2/quickteller/categorys';
$clientId = "IKIA9D98ABCDEFGHIFAKEID1E09104959B9755C41E1";
$clientSecretKey = "d5uAr+U8QhSv8vQtKPDIUI62327Fsfsfsf65=";
$signatureCipher = $httpMethod."&".$url."&".$timestamp."&".$nonce."&".$clientId."&".$clientSecretKey;
$signature = base64_encode($signatureCipher);
$data = array("TerminalID" => "9APY556261");
$data_string = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json',
'Authorization:InterswitchAuth SUtJQTUyNTBERkY1NkU5MzM2OUM0RkRBRjMxQTQ3QTg1RkNDODYyRTRDOUU=',
'Signature:'.$signature,
'Nonce:'.$nonce,
'Timestamp:'.$timestamp,
'SignatureMethod:SHA512'
));
$result = curl_exec($ch);
echo curl_getinfo($ch) . '<br/>';
echo curl_errno($ch) . '<br/>';
echo curl_error($ch) . '<br/>';
var_dump($result);
}
But i am receiving following error
"The HTTP method is not supported for this resource", i tried http method POST but same error, i am new on API can someone please help me to solve this .
Use this instead, fill the following
In the variable
- $clientId
- $clientSecretKey
At the header
- TerminalID
<?php
$nonce=$randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyz"), 0, 60);
$date = new DateTime();
$timestamp=$date->getTimestamp();
$httpMethod = "GET";
$clientId = "YOUR_OWN_ID";
$clientSecretKey = "YOUR_OWN_CLIENT_SECRET_KEY";
$resourceUrl='https://sandbox.interswitchng.com/api/v2/quickteller/categorys';
$resourceUrl = strtolower($resourceUrl);
$resourceUrl = str_replace('http://', 'https://', $resourceUrl);
$encodedUrl = urlencode($resourceUrl);
$transactionParams = "1";
$httpMethod = "GET";
$signatureCipher = $httpMethod . '&' . $encodedUrl . '&' . $timestamp . '&' . $nonce . '&' . $clientId . '&' . $clientSecretKey;
if (!empty($transactionParams) && is_array($transactionParams)) {
$parameters = implode("&", $transactionParams);
$signatureCipher = $signatureCipher . $parameters;
}
$signature = base64_encode(sha1($signatureCipher, true));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$resourceUrl);
// curl_setopt($ch, CURLOPT_POST, 1);
// curl_setopt($ch, CURLOPT_POSTFIELDS,$vars); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Content-Type:application/json',
'Authorization:InterswitchAuth SUtJQTAzREM3RDY5NUREMzZFQURFNTQxNEE2Nzg1MUJCMUZFQ0Y5MUIxRjg=',
'Signature:'.$signature,
'Nonce:'.$nonce,
'Timestamp:'.$timestamp,
'SignatureMethod:SHA1',
'TerminalID:YOUR_ASSIGNED_TERMINAL_ID'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec ($ch);
curl_close ($ch);
echo $server_output;
?>
This worked for me, hope it help someone in future

How to get an email address with a LinkedIn signup API with PHP

I got this code from some tutorial about linked signup, but the tutorial provide just the basic information. I need to get the user email also... How can I do that?
Here is the code:
auth.php
This is the link where I get access form on likedin.
<?php
session_start();
$config['base_url'] = '';
$config['callback_url'] = '';
$config['linkedin_access'] = '';
$config['linkedin_secret'] = '';
include_once "linkedin.php";
# First step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
//$linkedin->debug = true;
# Now we retrieve a request token. It will be set as $linkedin->request_token
$linkedin->getRequestToken();
$_SESSION['requestToken'] = serialize($linkedin->request_token);
# With a request token in hand, we can generate an authorization URL, which we'll direct the user to
//echo "Authorization URL: " . $linkedin->generateAuthorizeUrl() . "\n\n";
header("Location: " . $linkedin->generateAuthorizeUrl()); ?>
demo.php
This is the script that I get after signup.
<?php
session_start();
$config['base_url'] = 'http://xxx/linkedin/auth.php';
$config['callback_url'] = 'http://xxx/linkedin/demo.php';
$config['linkedin_access'] = '';
$config['linkedin_secret'] = '';
include_once "linkedin.php";
# First step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
//$linkedin->debug = true; if (isset($_REQUEST['oauth_verifier'])){
$_SESSION['oauth_verifier'] = $_REQUEST['oauth_verifier'];
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->getAccessToken($_REQUEST['oauth_verifier']);
$_SESSION['oauth_access_token'] = serialize($linkedin->access_token);
header("Location: " . $config['callback_url']);
exit;} else{
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->access_token = unserialize($_SESSION['oauth_access_token']);}
# You now have a $linkedin->access_token and can make calls on behalf of the current member
$xml_response = $linkedin->getProfile("~:(id,first-name,last-name,headline,picture-url)");
$id = $linkedin->getProfile('~:(id)');
$fname = $linkedin->getProfile('~:(first-name)');
$lname = $linkedin->getProfile('~:(last-name)');
$headline = $linkedin->getProfile('~:(headline)');
$picture = $linkedin->getProfile('~:(picture-url)');
$id = trim(strip_tags($id));
$fname = trim(strip_tags($fname));
$lname = trim(strip_tags($lname));
$headline = trim(strip_tags($headline));
$picture = trim(strip_tags($picture)); ?>
linkedin.php
This is LinkedIn library:
<?php require_once("OAuth.php"); class LinkedIn {
public $base_url = "http://api.linkedin.com";
public $secure_base_url = "https://api.linkedin.com";
public $oauth_callback = "oob";
public $consumer;
public $request_token;
public $access_token;
public $oauth_verifier;
public $signature_method;
public $request_token_path;
public $access_token_path;
public $authorize_path;
function __construct($consumer_key, $consumer_secret, $oauth_callback = NULL)
{
if($oauth_callback) {
$this->oauth_callback = $oauth_callback;
}
$this->consumer = new OAuthConsumer($consumer_key, $consumer_secret, $this->oauth_callback);
$this->signature_method = new OAuthSignatureMethod_HMAC_SHA1();
$this->request_token_path = $this->secure_base_url . "/uas/oauth/requestToken";
$this->access_token_path = $this->secure_base_url . "/uas/oauth/accessToken";
$this->authorize_path = $this->secure_base_url . "/uas/oauth/authorize";
}
function getRequestToken()
{
$consumer = $this->consumer;
$request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $this->request_token_path);
$request->set_parameter("oauth_callback", $this->oauth_callback);
$request->sign_request($this->signature_method, $consumer, NULL);
$headers = Array();
$url = $request->to_url();
$response = $this->httpRequest($url, $headers, "GET");
parse_str($response, $response_params);
$this->request_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
}
function generateAuthorizeUrl()
{
$consumer = $this->consumer;
$request_token = $this->request_token;
return $this->authorize_path . "?oauth_token=" . $request_token->key;
}
function getAccessToken($oauth_verifier)
{
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->request_token, "GET", $this->access_token_path);
$request->set_parameter("oauth_verifier", $oauth_verifier);
$request->sign_request($this->signature_method, $this->consumer, $this->request_token);
$headers = Array();
$url = $request->to_url();
$response = $this->httpRequest($url, $headers, "GET");
parse_str($response, $response_params);
$this->access_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
}
function getProfile($resource = "~")
{
$profile_url = $this->base_url . "/v1/people/" . $resource;
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $profile_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com"); # this is the realm
# This PHP library doesn't generate the header correctly when a realm is not specified.
# Make sure there is a space and not a comma after OAuth
// $auth_header = preg_replace("/Authorization\: OAuth\,/", "Authorization: OAuth ", $auth_header);
// # Make sure there is a space between OAuth attribute
// $auth_header = preg_replace('/\"\,/', '", ', $auth_header);
// $response will now hold the XML document
$response = $this->httpRequest($profile_url, $auth_header, "GET");
return $response;
}
function setStatus($status)
{
$profile_url = $this->base_url . "/v1/people/~";
$status_url = $this->base_url . "/v1/people/~/current-status";
echo "Setting status...\n";
$xml = "<current-status>" . htmlspecialchars($status, ENT_NOQUOTES, "UTF-8") . "</current-status>";
echo $xml . "\n";
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "PUT", $status_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
$response = $this->httpRequest($profile_url, $auth_header, "GET");
return $response;
}
# Parameters should be a query string starting with "?"
# Example search("?count=10&start=10&company=LinkedIn");
function search($parameters)
{
$search_url = $this->base_url . "/v1/people-search:(people:(id,first-name,last-name,picture-url,site-standard-profile-request,headline),num-results)" . $parameters;
//$search_url = $this->base_url . "/v1/people-search?keywords=facebook";
echo "Performing search for: " . $parameters . "<br />";
echo "Search URL: $search_url <br />";
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $search_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
$response = $this->httpRequest($search_url, $auth_header, "GET");
return $response;
}
function httpRequest($url, $auth_header, $method, $body = NULL)
{
if (!$method) {
$method = "GET";
};
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header)); // Set the headers.
if ($body) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header, "Content-Type: text/xml;charset=utf-8"));
}
$data = curl_exec($curl);
curl_close($curl);
return $data;
}}
The email address is only available to the authenticated user and not his/her connections.
Make sure you've requested the r_emailaddress member permissions from the user when authorizing your application. Authentication covers authentication and grant member permissions in detail.
Make the following GET call to fetch the email address for the authenticated user:
GET http://api.linkedin.com/v1/people/~:(email-address)
For people searching for v2 urls
please follow the below urls
payload = {
'grant_type': 'authorization_code',
'code': token,
'redirect_uri': s.SOCIAL_AUTH_CALLBACK_URL,
'client_id': s.LINKED_IN_CLIENT_ID,
'client_secret': s.LINKED_IN_CLIENT_SECRET
}
POST "https://www.linkedin.com/oauth/v2/accessToken"
to get access token
GET "https://api.linkedin.com/v2/me"
to get the user data send auth token in header
GET "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))"
to get user email address.
You can get email address via api
$this->userProfileUrl = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,public-profile-url,email-address)?oauth2_access_token=";
But you have to set scope like $oauth->scope = 'r_basicprofile,r_emailaddress';
use Oauth
https://developer-programs.linkedin.com/documents/profile-api
Or try
https://developer.linkedin.com/docs/oauth2
You can access the linkedin user email address with below EP:
`https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))`
Make sure that you have defined the scope 'r_emailaddress' in your library.
You can use below curl request to fetch the data:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '. $token,
'X-Restli-Protocol-Version: 2.0.0',
'Accept: application/json',
'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$response = curl_exec($ch);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$body = substr($response, $headerSize);
$response_body = json_decode($body,true);
$response_body will return the following response:
Array (
[elements] => Array
(
[0] => Array
(
[handle] => urn:li:emailAddress:123456
[handle~] => Array
(
[emailAddress] => your#email.in
)
)
)
)
You should pass '&scope=r_basicprofile+r_emailaddress' this at time of AccessToken Request
Step 1: AccessToken Request will be like
https://www.linkedin.com/oauth/v2/accessToken?grant_type=authorization_code&code={Your code}&redirect_uri={Yourredirect_uri}&client_id={Your client_id}&client_secret={Your client_secret }&scope=r_liteprofile+r_emailaddress
This will return you the AccessToken using which You do have to make 2 more requests 1 is for Email and Profile Details
Step 2: for Email request will be like
https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))&oauth2_access_token={AccessToken You get from step 1}'
Step 3: for basic profile request will be like
https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,emailAddress,profilePicture(displayImage~:playableStreams))&oauth2_access_token={AccessToken You get from step 1}'
The LinkedIn API does not offer the email address as part of the profile object. See the docs here to read what data is available.
EDIT:
See Kamyar's answer. Apparently as of August 2012 LinkedIn now allows pulling the email addresses.
You can try :
->elements[0]->{"handle~"}->emailAddress
goodluck
Step 1: AccessToken Request
$postData = array(
'grant_type' => 'authorization_code',
'code' => urldecode(trim($_GET['code'])),
'redirect_uri' => url_for('social_login/linkedin'),
'client_id' => CFG_LINKEDIN_APP_ID,
'client_secret' => CFG_LINKEDIN_SECRET_KEY
);
$ch = curl_init("https://www.linkedin.com/oauth/v2/accessToken");
curl_setopt($ch, CURLOPT_HEADER, array('Content-Type' => 'application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$body = substr($response, $header_size);
curl_close($ch);
if(!$response)
{
die('Curl error: ' . curl_error($ch));
}
$response = json_decode($body,true);
In $response you will find the AccessToken using which You do have to make 2 more requests 1 is for Email and Profile Details
Step 2: profile request
$access_token = $response['access_token'];
$ch = curl_init('https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,emailAddress,profilePicture(displayImage~:playableStreams))&oauth2_access_token=' . $access_token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$response = curl_exec($ch);
curl_close($ch);
Step 3: for Email request
$ch = curl_init('https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))&oauth2_access_token=' . $access_token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$response2 = curl_exec($ch);
curl_close($ch);
Result: user data
$user = [
'first_name' => current($response['firstName']['localized']),
'last_name' => current($response['lastName']['localized']),
'photo' => $response['profilePicture']['displayImage~']['elements'][0]['identifiers'][0]['identifier'],
'email' => $response2['elements'][0]['handle~']['emailAddress']
];

Categories