Perl sample code

You can find below a sample code implementing OAuth2 and an access to the ‘/me’ endpoint.

Copy the contents into a file, for instance named ‘viadeoapi.pl’, into your webserver CGI directory and access it through a browser.

The script will then redirects you to the Viadeo OAuth2 authentication page, just enter some Viadeo credentials and you will be redirected to ‘https://api.viadeo.com/me’ with the accesss_token set.

Note: Error catching is here minimal, you have to implement a better error management. Please also note than if you activate cookies, the authentication session of the user will be kept.

Note 2: For LWP HTTPS access you have to install the Crypt::SSLeay module.

#!/usr/bin/perl -w

use strict;
use LWP::UserAgent;
use JSON;
use CGI;

my $client_id     = "[your client id]";
my $client_secret = "[your client secret]";
my $oauth_base    = "https://secure.viadeo.com/oauth-provider";
my $api_base      = "https://api.viadeo.com";
my $authorize_url = $oauth_base . "/authorize2";
my $token_url     = $oauth_base . "/access_token2";

my $query = new CGI;

# Step 2 - An error occured during Step 1
if (defined $query->param('error')) {
        print CGI->header . "Authentication failed : " . $query->param('error');

# Step 2 - OK, we've got our code
} elsif (defined $query->param('code')) {

        # Request for an access_token
        my $uri = URI->new($token_url);
        my %params = ( 'grant_type'     => 'authorization_code',
                       'client_id'      => $client_id,
                       'client_secret'  => $client_secret,
                       'redirect_uri'   => $query->url(),
                       'code'           => $query->param('code'));
        my $ua = new LWP::UserAgent;
        my $req = new HTTP::Request POST => $uri->as_string;
        $uri->query_form(%params);
        $req->content_type('application/x-www-form-urlencoded');
        $req->content($uri->query);
        my $res = from_json($ua->request($req)->content);

        # The access token cannot be retrieved
        if (defined $res->{'error'}) {
                print CGI->header . "An error occured : " . $res->{'error'};

        # Ok now have the access token, let's request the API
        } else {
                my $url = $api_base . "/me.xml" . "?access_token=" . $res->{'access_token'};
                print CGI->redirect($url);
        }

# Step 1 - We don't have an access_token
} else {
        my %params = ();
        $params{'response_type'} = 'code';
        $params{'client_id'} = $client_id;
        $params{'redirect_uri'} = $query->url();
        my $uri = URI->new($authorize_url);
        $uri->query_form(%params);
        print CGI->redirect($uri);
}