PHP and Shopify API connection - php

I'm trying to learn the shopify api for a project. Tried a few pasted codes on their forum, adapting my code to theirs.
The documentation says to do the authentication this way, by providing the following:
https://{username}:{password}#{shop}.myshopify.com/admin/api/{api-version}/{resource}.json
{username} — The API key that you generated
{password} — The API password
{shop} - The name that you entered for your development store
{api-version} — The supported API version you want to use
{resource} — A resource endpoint from the REST admin API
I'm trying to do a GET request on all the orders made on the store.
/ info
$API_KEY = '75c89bf******ea919ce****7702';
$PASSWORD = '2061******82d2802**f***9403';
$STORE_URL = '*****-na-***-c***.myshopify.com';
$AUTHORIZATION = base64_encode($API_KEY . ':' . $PASSWORD);
$url = 'https://' . $API_KEY . ':' . $PASSWORD . '#' . $STORE_URL . '/admin/api/2020-01/orders.json';
$header = array();
$header[] = 'Accept: application/json';
$header[] = 'Content-Type: application/json';
$header[] = 'Authorization: Basic ' . $AUTHORIZATION;
$session = curl_init();
//options
curl_setopt($session, CURLOPT_URL, $url);
curl_setopt($session, CURLOPT_HTTPHEADER, $header);
curl_setopt($session, CURLOPT_GET, 1);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
//exec
$response = curl_exec($session);
curl_close($session);
print_r($response);
// error
if($response === false)
{
print_r('Curl error: ');
}
The code doesn't work at all, without any error code, completly blank, with only the first project echo showing.
I verified my API keys and they are working, I can insert them manually into chrome.

You don't need the header for authorization. Your code should like:
$API_KEY = '75c89bf******ea919ce****7702';
$PASSWORD = '2061******82d2802ff***9403';
$STORE_URL = 'porcao-na-sua-casa.myshopify.com';
$url = 'https://' . $API_KEY . ':' . $PASSWORD . '#' . $STORE_URL . '/admin/api/2020-01/orders.json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE) //can check status code, requst successfully processed if return 200
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);

Found the problem when I ran in terminal, did not install php-curl on this machine.
#Kshitij solution worked, just like mine, when curl was properly installed.

// Provide the required parameters like store url , endpoint etc.
function shopifyApiCall($STORE_URL ,$query = [], $endpoint, $API_KEY, $PASSWORD){
//API_Key : your API key, you can get it from your APP setup.
//Password : Your Access Token
$url = 'https://' . $API_KEY . ':' . $PASSWORD . '#' . $STORE_URL . $endpoint;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt ($ch, CURLOPT_POSTFIELDS, json_encode($query));
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$error_number = curl_errno($ch);
$error_message = curl_error($ch);
curl_close($ch);
// Return an error is cURL has a problem
if ($error_number) {
return $error_message;
} else {
// No error, return Shopify's response by parsing out the body and the headers
$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
// Convert headers into an array
$headers = array();
$header_data = explode("\n",$response[0]);
$headers['status'] = $header_data[0]; // Does not contain a key, have to explicitly set
array_shift($header_data); // Remove status, we've already set it above
foreach($header_data as $part) {
$h = explode(":", $part);
$headers[trim($h[0])] = trim($h[1]);
}
// Return headers and Shopify's response
//return array('headers' => $headers, 'response' => $response[1]);changed headers
return array('headers' => $header_data, 'response' => $response[1]);
}
}

Related

How can I deregister a device if I only have that device's push token, not the HWID?

My database is only storing the push tokens for user devices, not the HWIDs.
Is it possible to use the Pushwoosh API to deregister a device with the push token only? It's not working when I send just the push token with an empty string for the hwid.
Here's my code:
$device_id = '';
$pushwoosh_push_token = 'Push-Token-here';
$pushwoosh_app_code = 'App-Code-here';
$pushwoosh_auth_token = 'Auth-Token-here';
$response = unregister_device_pushwoosh($device_id, $pushwoosh_push_token, $pushwoosh_app_code, $pushwoosh_auth_token);
print_r($response)."<br>";
function unregister_device_pushwoosh($device_id, $pushwoosh_push_token, $pushwoosh_app_code, $pushwoosh_auth_token) {
$url = 'https://cp.pushwoosh.com/json/1.3/unregisterDevice';
$data = array(
'request' => array(
'application' => $pushwoosh_app_code,
'push_token' => $pushwoosh_push_token,
'hwid' => $device_id,
),
);
$content = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
"Content-type: application/json\r\n".
"Authorization: Basic ".base64_encode("$pushwoosh_app_code:$pushwoosh_auth_token")
]);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if (200 != $status)
{
echo("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ', curl_errno ' . curl_errno($curl) . '<br>');
}
curl_close($curl);
return 'Response: ' . $json_response . "\n";
}

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 create a signature for the Ascentis API using PHP

I am trying to create the proper signature for the Ascentis API. There documentation is http://www.ascentis.com/API/Ascentis_API_Documentation.pdf. Page 4 describes the Signature format.
Here is my PHP code. Am I doing something wrong? I get a "not authorized error".
$url='https://selfservice2.ascentis.com/mycompany/api/v1.1/employees';
$timestamp=gmdate('Y-m-d\TH:i:s\Z');
$path=strtolower(str_replace('https://selfservice2.ascentis.com','',$url));
$signature_string="GET {$path} {$timestamp}";
$signature=hash_hmac("sha1",$signature_string,$secret_key);
$authorization=encodeUrl($client_key).':'.encodeUrl($signature);
Here's a more complete example. Props to #Steve Lloyd for getting me in the right direction.
$codes['secret_key'] = 'my_secret';
$client_key = 'my_key';
$url = 'https://selfservice.ascentis.com/my_company/api/v1.1/employees?lastname=%s';
$timestamp = gmdate('Y-m-d\TH:i:s\Z');
$path = strtolower(str_replace('https://selfservice.ascentis.com', '', $url));
$signature_string = "GET {$path} {$timestamp}";
$signature = base64_encode(hash_hmac("sha1", $signature_string, $codes['secret_key'], TRUE));
$authorization = urlencode($client_key) . ':' . urlencode($signature);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: " . $authorization,
"Accept: application/xml",
"Timestamp: " . $timestamp,
]);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$data = curl_exec($ch);
$info = curl_getinfo($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "Received $httpcode from $url\n";
echo "Key: $client_key\n";
echo "Signature: $signature\n";
echo "authorization: $authorization\n";
echo "request info:" . var_export($info, TRUE) . "\n";
echo "data:\n";
var_export($data, TRUE)
After playing the trial and error game I was able to get this working. It turns out that you have to set hash_hmac to raw_output. Here is the working code:
$url='https://selfservice2.ascentis.com/mycompany/api/v1.1/employees';
$timestamp=gmdate('Y-m-d\TH:i:s\Z');
$path=strtolower(str_replace('https://selfservice2.ascentis.com','',$url));
$signature_string="GET {$path} {$timestamp}";
$signature=base64_encode(hash_hmac("sha1",$signature_string,$codes['secret_key'],true));
$authorization=encodeUrl($client_key).':'.encodeUrl($signature);

How to get fortnox access token with the help of authorization code and client secret using PHP?

I have a sand box account in fortnox and i am trying to get the access token using following code, but i keep getting same error:
$requestMethod = "GET";
$ch = curl_init();
$options = array(
'Authorization-Code: '. AUTHORIZATION_CODE .'',
'Client-Secret: '. CLIENT_SECRET .'',
'Content-Type: '. CONTENT_TYPE .'',
'Accept: '. ACCEPTS .''
);
curl_setopt ($ch, CURLOPT_CAINFO, "/xampp/htdocs/cacert.pem");
curl_setopt($ch, CURLOPT_URL, "https://api.fortnox.se/3/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, $options);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestMethod);
$curlResponse = curl_exec($ch);
$info = curl_getinfo($ch);
//echo 'Took ' . $info['total_time'] . ' seconds for url ' . $info['url'];
echo $curlResponse;
if ($curlResponse === FALSE) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
Error: PHP / 4.5.37 Can not sign in , access tokens , or client- secret missing ( 2000311 ) .
I get the Access-Token using the following code which is very close to your code. It worked fine for me.
Your error is described on the Errors page, but it adds nothing new to the text you already shown.
Please note that you can retrive the Access-Token only once, check Authentication section in the Fortnox documentation.
An Access-Token can only be retrieved once with every Authorization-Code, multiple requests with the same Authorization-Code will make both the Authorization-Code and the Access-Token invalid.
public function actionRetrieveAccessToken($authCode, $clientSecret)
{
$headers = [
'Authorization-Code: ' . $authCode,
'Client-Secret: ' . $clientSecret,
'Content-Type: application/json',
'Accept: application/json',
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api.fortnox.se/3/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$responseText = curl_exec($curl);
$response = json_decode($responseText, true);
if (isset($response['ErrorInformation'])) {
echo 'Request failed with error messages:' . PHP_EOL;
echo $response['ErrorInformation']['Error'] . ': ';
echo $response['ErrorInformation']['Message'];
echo ' (' . $response['ErrorInformation']['Code'] . ')' . PHP_EOL;
} else {
echo 'Access Token: ' . $response['Authorization']['AccessToken'] . PHP_EOL;
}
}
$content_type = 'application/json';
$api_url="api url here";
$curl = curl_init();
$headers = array(
'Content-Type: '.$content_type.'',
'Authorization : '.'Bearer ' . $this->access_token
);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
if (!empty($data))
{
$data = json_encode($data);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
$response = curl_exec($curl);
logthis($response,"utils");
curl_close($curl);

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