PHP Soap Client call to WCF service? - wcf

How to do this, I m new Soap API, Any sample Code
$soapClient = new SoapClient("http://website.com/EComintegration/IntegrationService.svc?wsdl");
// Prepare SoapHeader parameters
$sh_param = array(
'UserName' => 'admin',
'Password' => 'admin');
//'ClientID' => 1,
//'OutletID' => 1,
//'TerminalID' => 1);
$headers = new SoapHeader('http://website.com/EComintegration/IntegrationService.svc', 'UserCredentials', $sh_param);
// Prepare Soap Client
$soapClient->__setSoapHeaders(array($headers));
// Setup the RemoteFunction parameters
$ap_param = array(
'Location' => 2,
'DateFilter'=>'20200220'
);
// Call RemoteFunction ()
$error = 0;
try {
$info = $soapClient->__call("GetInventory", array($ap_param));
} catch (SoapFault $fault) {
$error = 1;
print("
alert('Sorry, blah returned the following ERROR: ".$fault->faultcode."-".$fault->faultstring.". We will now take you back to our home page.');
window.location = 'main.php';
");
}
if ($error == 0) {
$auth_num = $info->ItemName;
}

WCF is also an implementation of SOAP web service, thereby we should call the service like calling a SOAP web service. Please refer to the official documentation.
https://www.php.net/manual/en/book.soap
https://www.php.net/manual/en/class.soapclient
Also, here are some relevant links, wish it is helpful to you.
How to consume a WCF Web Service that uses custom username validation with a PHP page?
https://forums.asp.net/t/1602125.aspx
https://social.msdn.microsoft.com/Forums/vstudio/en-US/4abef020-7fb5-40ef-be77-227d329bb172/call-wcf-service-from-php-with-authentication?forum=wcf
Feel free to let me know if there is anything I can help with.

Related

How to implement code for OAuth 2.0 Authorization for Google Directory API Without Command Line Interface

I have seen code in google directory api documentation for command line interface and have worked with it, the code works fine. But I want write code that runs without terminal and runs when on a page when the page is loaded because i have to run the code in the terminal every hour after it's expired, is there anyway i can get the code to run when i visit the page of authorization code.
The code work's with command-line interface, but i want it to work without command-line, what can i do?
Given Below is the code from Google Directory API and the URL:
URL : https://developers.google.com/admin-sdk/directory/v1/quickstart/php
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('G Suite Directory API PHP Quickstart');
$client->setScopes(Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Directory($client);
// Print the first 10 users in the domain.
$optParams = array(
'customer' => 'my_customer',
'maxResults' => 10,
'orderBy' => 'email',
);
$results = $service->users->listUsers($optParams);
if (count($results->getUsers()) == 0) {
print "No users found.\n";
} else {
print "Users:\n";
foreach ($results->getUsers() as $user) {
printf("%s (%s)\n", $user->getPrimaryEmail(),
$user->getName()->getFullName());
}
}
I have also tried to implement the code from OAuth 2.0 for Web Server Applications in wordpress page with the template but it's not working, which is from https://developers.google.com/identity/protocols/oauth2/web-server#php_1
and this is my code:
<?php
require __DIR__ . '/vendor/autoload.php';
session_start();
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
$client = new Google_Client();
$client->setApplicationName('G Suite Directory API PHP Quickstart');
$client->addScope(Google_Service_Directory::ADMIN_DIRECTORY_USER);
$client->setAuthConfig('/path/to/credentials.json');
$client->setAccessType('offline');
$client->setApprovalPrompt("consent");
$client->setIncludeGrantedScopes(true); // incremental auth
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Directory($client);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

This endpoint does not support the `merchant` facade"

I have set up the bitpay API in PHP, I created a merchant token. for testing purpose, I have set up bitcoin core testnet wallet. But when I create payout to send bitcoin to my testnet wallet, I give me exception of "This endpoint does not support the merchant facade". My code for creating key,
$storageEngine = new \Bitpay\Storage\EncryptedFilesystemStorage('mypassword');
$privateKey = $storageEngine->load('bitpay.pri');
$publicKey = $storageEngine->load('bitpay.pub');
$client = new \Bitpay\Client\Client();
$network = new \Bitpay\Network\Testnet();
$adapter = new \Bitpay\Client\Adapter\CurlAdapter();
$client->setPrivateKey($privateKey);
$client->setPublicKey($publicKey);
$client->setNetwork($network);
$client->setAdapter($adapter);
$sin = \Bitpay\SinKey::create()->setPublicKey($publicKey)->generate();
try {
$token = $client->createToken(
array(
'facade' => 'merchant',
'label' => 'Demo',
'id' => (string) $sin,
)
);
$pairingCode = $token->getPairingCode();
$createdToken = $token->getToken();
$this->ci->dashboard->addSettings('bit_token', $createdToken);
echo $pairingCode;
} catch (\Exception $e) {
return $response;
}
But when i crate a payout, then it gives me exception.
I've dived into similar issue and it looks that to access Payouts API you have to use PAYROLL facade. You can find more info in the docs

On Tomcat Server Using Yii Framework HTTP_X_USERNAME locally recognized but not online

I prepared an api using yii framework. The api contains an authentication method which checks the HTTP_X_USERNAME and HTTP_X_PASSWORD parameters and compares them with some data in the database.
While testing everything locally on the test dev (WAMP + Eclipse + Tomcat) it worked normally. I tested everything with the Postman. I have put those two parameters (HTTP_X_...) into the header.
After I uploaded the api to the production server (Tomcat) the api always returns authentication FALSE although the authorization data locally and online is the same. The code stops at the part where it checks if those parameters are even set "You must be authorized to access the api. No USERNAME and PASSWORD set.".
Does any one have an idea where the problem is? Why does it work locally and not online???
private function _checkAuth() {
$headers = apache_request_headers ();
if (! (isset ( $headers ['HTTP_X_USERNAME'] ) and isset ( $headers ['HTTP_X_PASSWORD'] ))) {
// Error: Unauthorized
$this->badResponse ( 401, 'You must be authorized to access the api. No USERNAME and PASSWORD set.');
}
$username = $headers ['HTTP_X_USERNAME'];
$password = $headers ['HTTP_X_PASSWORD'];
// Find the user
$criteria = new CDbCriteria ();
$criteria->addCondition ( 'email = :email');
$criteria->addCondition( 'api_access_token = :pass');
$criteria->params = array(':email' => $username, ":pass" => $password);
$school = AutoSchool::model ()->find ( $criteria );
if ($school === null) {
$this->badResponse ( 401, 'Error: You must be authorized to access the api.' );
}
return $school->id;
}
Finally found the problem!
After debuging found that the problem was the method apache_request_headers() since it did not return anything useful which i set in the header.
I implemented my own method
private function apache_request_headers2() {
foreach($_SERVER as $key=>$value) {
if (substr($key,0,5)=="HTTP_") {
$key=str_replace(" ","-",ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
$out[$key]=$value;
}else{
$out[$key]=$value;
}
}
return $out;
}
But this is not all. I had to change the header parameters i was requesting. I had to use $headers ['PHP_AUTH_USER'] and $headers ['PHP_AUTH_PW'] instead of HTTP_X_USERNAME and HTTP_X_PASSWORD.
And finally while issuing the POST request I had to use Basic Authentication and not setting the Header parameters
And the complete code of the edited method:
private function _checkAuth() {
$headers = $this->apache_request_headers2();
if (! (isset ( $headers ['PHP_AUTH_USER'] ) and isset ( $headers ['PHP_AUTH_PW'] ))) {
// Error: Unauthorized
$this->badResponse ( 401, 'You must be authorized to access the api. No USERNAME and PASSWORD set.');
}
$username = $headers ['PHP_AUTH_USER'];
$password = $headers ['PHP_AUTH_PW'];
// Find the user
$criteria = new CDbCriteria ();
$criteria->addCondition ( 'email = :email');
$criteria->addCondition( 'api_access_token = :pass');
$criteria->params = array(':email' => $username, ":pass" => $password);
$school = AutoSchool::model ()->find ( $criteria );
if ($school === null) {
$this->badResponse ( 401, 'Error: You must be authorized to access the api.' );
}
return $school->id;
}

Got problems with webhook to Telegram Bot API

Why is my webhook not working? I do not get any data from telegram bot API. Here is the detailed explanation of my problem:
I got SSL cert from StartSSL, it works fine on my website (according to GeoCerts SSL checker), but still seems like my webhook to Telegram Bot API doesn't work (despite it says that webhook was set I do not get any data).
I am making a webhook to my script on my website in this form:
https://api.telegram.org/bot<token>/setWebhook?url=https://mywebsite.com/path/to/giveawaysbot.php
I get this text in response:
{"ok":true,"result":true,"description":"Webhook was set"}
So it must be working, but it actually doesn't.
Here is my script code:
<?php
ini_set('error_reporting', E_ALL);
$botToken = "<token>";
$website = "https://api.telegram.org/bot".$botToken;
$update = file_get_contents('php://input');
$update = json_decode($update);
print_r($update); // this is made to check if i get any data or not
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
switch ($message) {
case "/test":
sendMessage($chatId,"test complete");
break;
case "/hi":
sendMessage($chatId,"hey there");
break;
default:
sendMessage($chatId,"nono i dont understand you");
}
function sendMessage ($chatId, $message) {
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chatId."&text=".urlencode($message);
file_get_contents($url);
}
?>
I don't actually receive any data to $update. So webhook is not working. Why?
Just another one moment, why your webhooks not work.
In my case the reason was in allowed_updates webhook parameter.
By calling :
https://api.telegram.org/bot<your_bot_token>/getWebhookInfo
You can see
{
"ok": true,
"result": {
"url": "<your webhook url should be here>",
"has_custom_certificate": false,
"pending_update_count": 0,
"max_connections": 40,
"allowed_updates": [
"callback_query"
]
}
}
It means, that your bot can't react to your text messages, and you will not receive any webhooks!
You can note, that "allowed_updates" contains array. So, currently it will react only to inline button events (passed as keyboard layout!). According to the setWebhook documentation, allowed_updates is an "optional" parameter.
To start receieve text messages, you need to add "message" to your "allowed_updates" prop. To do it, just again set your webhooks and add it to query. Like here :
https://api.telegram.org/bot<your_token>/setWebHook?url=<your_url>&allowed_updates=["callback_query","message"]
You will receive something like "url already added", but don't worry, allowed_updates will be updated even in this case. Just try type your message to bot and test your webhooks.
That's all, now, telegram will send webhooks to each direct message from you to your bot. Hope, it helps someone.
I was with this problem. I was trying to look everywhere and couldn't find the solution for my problem, because people were all the time saying that the problem was the SSL certificate. But I found the problem, and that were a lot of things missing on the code to interact with the telegram API webhook envolving curl and this kind of stuff. After I looked in an example at the telegram bot documentation, I solved my problem. Look this example https://core.telegram.org/bots/samples/hellobot
<?php
//telegram example
define('BOT_TOKEN', '12345678:replace-me-with-real-token');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
function apiRequestWebhook($method, $parameters) {
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
$parameters["method"] = $method;
header("Content-Type: application/json");
echo json_encode($parameters);
return true;
}
function exec_curl_request($handle) {
$response = curl_exec($handle);
if ($response === false) {
$errno = curl_errno($handle);
$error = curl_error($handle);
error_log("Curl returned error $errno: $error\n");
curl_close($handle);
return false;
}
$http_code = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE));
curl_close($handle);
if ($http_code >= 500) {
// do not wat to DDOS server if something goes wrong
sleep(10);
return false;
} else if ($http_code != 200) {
$response = json_decode($response, true);
error_log("Request has failed with error {$response['error_code']}: {$response['description']}\n");
if ($http_code == 401) {
throw new Exception('Invalid access token provided');
}
return false;
} else {
$response = json_decode($response, true);
if (isset($response['description'])) {
error_log("Request was successfull: {$response['description']}\n");
}
$response = $response['result'];
}
return $response;
}
function apiRequest($method, $parameters) {
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
foreach ($parameters as $key => &$val) {
// encoding to JSON array parameters, for example reply_markup
if (!is_numeric($val) && !is_string($val)) {
$val = json_encode($val);
}
}
$url = API_URL.$method.'?'.http_build_query($parameters);
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
return exec_curl_request($handle);
}
function apiRequestJson($method, $parameters) {
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
$parameters["method"] = $method;
$handle = curl_init(API_URL);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($parameters));
curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
return exec_curl_request($handle);
}
function processMessage($message) {
// process incoming message
$message_id = $message['message_id'];
$chat_id = $message['chat']['id'];
if (isset($message['text'])) {
// incoming text message
$text = $message['text'];
if (strpos($text, "/start") === 0) {
apiRequestJson("sendMessage", array('chat_id' => $chat_id, "text" => 'Hello', 'reply_markup' => array(
'keyboard' => array(array('Hello', 'Hi')),
'one_time_keyboard' => true,
'resize_keyboard' => true)));
} else if ($text === "Hello" || $text === "Hi") {
apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'Nice to meet you'));
} else if (strpos($text, "/stop") === 0) {
// stop now
} else {
apiRequestWebhook("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message_id, "text" => 'Cool'));
}
} else {
apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'I understand only text messages'));
}
}
define('WEBHOOK_URL', 'https://my-site.example.com/secret-path-for-webhooks/');
if (php_sapi_name() == 'cli') {
// if run from console, set or delete webhook
apiRequest('setWebhook', array('url' => isset($argv[1]) && $argv[1] == 'delete' ? '' : WEBHOOK_URL));
exit;
}
$content = file_get_contents("php://input");
$update = json_decode($content, true);
if (!$update) {
// receive wrong update, must not happen
exit;
}
if (isset($update["message"])) {
processMessage($update["message"]);
}
?>
I had similar problem. Now solved.
The problem is possibly in a wrong public certificate. Please follow with attention instructions I propose in my project:
https://github.com/solyaris/BOTServer/blob/master/wiki/usage.md#step-4-create-self-signed-certificate
openssl req -newkey rsa:2048 -sha256 -nodes -keyout /your_home/BOTServer/ssl/PRIVATE.key -x509 -days 365 -out /your_home/BOTServer/ssl/PUBLIC.pem -subj "/C=IT/ST=state/L=location/O=description/CN=your_domain.com"
Telegram setWebhooks API do not check data inside your self-signed digital certificate, returning "ok" even if by example you do not specify a valid /CN! So be carefull to generate a public .pem certificate containing /CN=your_domain corresponding to your REAL HOST domain name!
It may be the SSL cert. I had the same problem: Webhook confirmed but actually SSL cert borked.
This reddit thread was helpful: https://www.reddit.com/r/Telegram/comments/3b4z1k/bot_api_recieving_nothing_on_a_correctly/
This may help who works with Laravel Telegram SDK.
I had a problem with self-signed webhook in Laravel 5.3.
After setup and getting OK result from Telegram with "Webhook was set" message, it didn't work.
The problem was related to CSRF verification. So I added the webhook url to CSRF exceptions and now everything works like a charm.
I had this problem too, after somehow the telegram didn't run my bot, so I tried to renew the certificate and set web hooks again, but again it didn't work, so I updated my VPS(yum update) and then renew my certificate and set web hooks again. after these it started working again.
This is because you are not setting the certificate like this
curl -F "url=https://bot.sapamatech.com/tg" -F "certificate=#/etc/apache2/ssl/bot.pem" https://api.telegram.org/bot265033849:AAHAs6vKVlY7UyqWFUHoE7Toe2TsGvu0sf4/setWebhook
Check this link on how to set Telegram Self Signed Certificate
Try this code. If you have a valid SSL on your web host and you have properly run the setWebhook, it should work (does for me). Make sure you create a file called "log.txt" and give write permission to it:
<?php
define('BOT_TOKEN', '????');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
// read incoming info and grab the chatID
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatID = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
// compose reply
$reply ="";
switch ($message) {
case "/start":
$reply = "Welcome to Siamaks's bot. Type /help to see commands";
break;
case "/test":
$reply = "test complete";
break;
case "/hi":
$reply = "hey there";
break;
case "/help":
$reply = "commands: /start , /test , /hi , /help ";
break;
default:
$reply = "NoNo, I don't understand you";
}
// send reply
$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".$reply;
file_get_contents($sendto);
// Create a debug log.txt to check the response/repy from Telegram in JSON format.
// You can disable it by commenting checkJSON.
checkJSON($chatID,$update);
function checkJSON($chatID,$update){
$myFile = "log.txt";
$updateArray = print_r($update,TRUE);
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, $chatID ."nn");
fwrite($fh, $updateArray."nn");
fclose($fh);
}
I had this problem too. In my case was mistake in declaring my API method. I created GET method instead of POST at first.
#api.route('/my-webhook-url')
class TelegramWebhook(Resource):
def post(self): # POST, Carl!
# ...
return response
In my case the error was due to the PHP configuration ( using cPanel )
[26-Jan-2021 09:38:17 UTC] PHP Warning: file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /home/myUsername/public_html/mydomain.com/my_bot_file.php on line 40
and
[26-Jan-2021 09:38:17 UTC] PHP Warning: file_get_contents(https://api.telegram.org/bot<my-bot-id>/sendmessage?chat_id=647778451&text=hello charlie ! k99 ): failed to open stream: no suitable wrapper could be found in /home/myUsername/public_html/myDomain.com/my_bot_file.php on line 40
so - it is pretty self explanatory.
The allow_url_fopen=0 var in the php configuration actually disables the requiered action.
But anyhow your best bet is to look at the error log on your server and see if there are any other errors in the script or server config.

Linkedin API: Exchange JSAPI Token for REST API OAuth Token

I'm having some difficulty exchanging my JSAPI token for a REST API token. I'm using this for reference:
https://developer-programs.linkedin.com/documents/exchange-jsapi-tokens-rest-api-oauth-tokens
I've: set up a self signed SSL cert locally, so Linkedin's secure cookie works properly; given my app r_basicprofile and r_emailaddress permissions.
Here's my front end code:
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: **MY_CLIENT_ID**
authorize: true
credentials_cookie: true
</script>
...
$('.linkedin-signin').click(function(e) {
IN.User.authorize( function () {
IN.API.Raw("/people/~").result(function(data) {
$.post(location.origin+'/api/account/create/linkedin', { 'lId': data.id } ).done(function(result) {
console.log(result);
});
});
});
return false;
});
And here is my PHP code, which is almost exactly as in their docs:
$consumer_key = '**MY_CLIENT_ID**';
$consumer_secret = '**MY_CLIENT_SECRET**';
$cookie_name = "linkedin_oauth_${consumer_key}";
$credentials_json = $_COOKIE[$cookie_name];
$credentials = json_decode($credentials_json);
$access_token_url = 'https://api.linkedin.com/uas/oauth/accessToken';
$oauth = new OAuth($consumer_key, $consumer_secret);
$access_token = $credentials->access_token;
// swap 2.0 token for 1.0a token and secret
$oauth->fetch($access_token_url, array('xoauth_oauth2_access_token' => $access_token), OAUTH_HTTP_METHOD_POST);
Everything looks good, but on $oauth->fetch, I get the error:
OAuthException(code: 401): Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)
Which leads me to believe that the token is invalid... but it's taken directly from the cookie, so how could it be invalid? Any ideas?
Today we got the weird 401 error too, apperently linkedin was broken, because after an hour it worked again without any changes on our side.
I found this site though and eventhough it's a really old post, i tought i'd share how we fixed it, which works.
JS Front-end
var AppConfig = {
linkedin : {
onLoad : "linkedinLibInit",
api_key : 'YOUR_API_KEY',
authorize : false,
credentials_cookie: true
}
};
window.linkedinLibInit = function ( response ) {
// post init magic
// cleanup window callback function
delete window.linkedinLibInit;
}
$.getScript( "//platform.linkedin.com/in.js?async=true", function success() {
IN.init( AppConfig.linkedin );
} );
function connectToLinkedIn() {
if ( IN.User.isAuthorized() ) {
_linkedinAuthorized();
}
else {
IN.User.authorize( _linkedinAuthorized );
}
}
function _linkedinAuthorized() {
IN.API.Profile( "me" )
.fields( 'id', 'first-name', 'last-name', 'location', 'industry', 'headline', 'picture-urls::(original)', 'email-address' )
.result( function ( response ) {
var accessToken = JSON.parse( $.cookie( 'linkedin_oauth_' + AppConfig.linkedin.api_key ) );
// performApi Call to backend
} )
.error( function ( err ) {
// render error
} );
}
PHP Backend using PECL oAuth
function offlineAuthLinkedIn($accessToken, $linkedinConfig) {
$oAuth = new \OAuth( $linkedinConfig['app_id'], $linkedinConfig['app_secret'] );
$oAuth->fetch(
'https://api.linkedin.com/uas/oauth/accessToken',
array('xoauth_oauth2_access_token' => $accessToken),
OAUTH_HTTP_METHOD_POST
);
$response = null;
parse_str($oAuth->getLastResponse(), $response);
$oAuth->setToken($response['oauth_token'], $response['oauth_token_secret']);
$oAuth->fetch(
'http://api.linkedin.com/v1/people/~:(id,first-name,last-name,formatted-name,headline,location,picture-url,picture-urls::(original),public-profile-url)',
array(),
OAUTH_HTTP_METHOD_GET,
array('x-li-format' => 'json')
);
$profile = json_decode($oAuth->getLastResponse(), true);
$profile['user_id'] = $profile['id'];
if (true == isset($profile['pictureUrl']))
{
$profile['profile_image'] = $profile['pictureUrl'];
unset($profile['pictureUrl']);
}
return $profile;
}