Linkedin API: Exchange JSAPI Token for OAuth Token REST API

I find it difficult to change the JSAPI token to the REST API token. I use this for reference:

https://developer-programs.linkedin.com/documents/exchange-jsapi-tokens-rest-api-oauth-tokens

I: install the SSL certificate myself locally, so the Linkedin secure cookie works correctly; given my r_basicprofile applications and r_emailaddress permissions.

Here is 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 the same 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->fetchI get an error:

OAuthException(code: 401): Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)

What makes me think that the token is invalid ... but it is taken directly from the cookie, as it may be invalid? Any ideas?

+4
1

401, , , - .

, , , , , , .

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 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;
}
+1

Source: https://habr.com/ru/post/1612458/


All Articles