Using OAuth From PHP (Sample - 3 Legged)

Overview

This document provides a detailed PHP code walkthrough for accessing Constant Contact’s REST API in PHP using OAuth authentication. It shows how a typical web application obtains an account access token using OAuth and how that token is used in Constant Contact APIs.

For a general overview of OAuth usage in the Constant Contact REST APIs, see this page.

Sample Application

The source for the PHP code discussed in this document is available here. The instructions to use the sample are available in the readme file. To execute the sample application, perform the following steps:

  1. Create a Constant Contact email account if you do not already have one. You can create a free trial account from www.constantcontact.com
  2. Get a consumer key and consumer secret by logging into the developer website at developer.constantcontact.com/apikey/login and providing the required information
  3. Download the Constant Contact PHP sample code. Download the OAuth PHP framework (OAuth.php) from http://oauth.googlecode.com/svn/code/php. Place all the .php files in a folder which is accessible from your web server. We’ll call this the “source folder.”
  4. Point your browser to index.php in the source folder.
  5. Enter the consumer key, user name and secret you got from Steps 1 and 2 into the respective text fields and proceed through the authentication process.

 

Using OAuth with PHP

The remainder of this document describes the detailed steps required to create an application which accesses Constant Contact data through the Constant Contact REST APIs which use OAuth authentication. The following steps are described in detail in the sections that follow.. Step 1 – Setup Environment Step 2 – Get your Consumer Key and Secret Step 3 – Get Request Token Step 4 – Redirect user to Constant Contact to Login/Grant Access Step 5 – Exchange Request Token for an Access Token Step 6 – Step 6 – Access the APIs

Step 1 – Setup Environment

This document assumes that your web server is setup with a PHP environment which is ready to use. If you need to set up PHP and you are running Linux, you can launch the setup with: sudo apt-get install libapache2-mod-php5 If you are running Windows, information on setting up PHP is available at XAMPP. The sample code discussed in this document uses the PHP OAuth framework from http://oauth.googlecode.com/svn/code/php. Download OAuth.php to your source folder and import into your source .php files.

Step 2 – Get your Consumer Key and Secret

Log into the developer website (http://developer.constantcontact.com), API Keys section to either view your existing Consumer Key (aka API Key) and Consumer Secret or request a new key and secret. If you are building more than one application, you should request a Consumer Key and Consumer secret for each application.

Step 3 – Get Request Token

Your program will use the consumer key and consumer secret to get a request token and request secret. These will be stored in the sessions and used in subsequent steps to get an access token and access token secret. Following is typical PHP code to get a request token and request secret.
Step 3. 1 Setup the parameters and URL

       define("URI", "http://api.constantcontact.com");
       $request_token_url  = URI.'/ws/oauth_get_request_token';
       $parsed = parse_url($request_token_url );
       $params = array();

Step 3.2 Sign the request with consumer key and consumer secret

       $req_req = OAuthRequest::from_consumer_and_token($oauth _consumer, NULL, "GET", $request_token_url, $params);
       $oauth_consumer = new OAuthConsumer($consumer_key, $consumer_secret, NULL);
       $sig_method = new OAuthSignatureMethod_HMAC_SHA1();
       $req_req->sign_request($sig_method, $oauth_consumer, NULL);

Step 3.3 Execute request

 
       $request  = $req_req->to_url();
       $session = curl_init($request);
       curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);
       // Make the request
       $response = curl_exec($session);

       //Error Handling:
       // there is an error while executing the request, 
       if (!$response) {  
            $response = curl_error($curl);  
        }  
       curl_close($session);

Step 3.4 Store request token and secret

       parse_str($response, $params);
       $oauth_token = $params['oauth_token'];
       $oauth_token_secret = $params['oauth_token_secret'];
       $_SESSION[CONSUMER_KEY] = $consumer_key;
       $_SESSION[CONSUMER_SECRET] = $consumer_secret;
       $_SESSION[REQUEST_TOKEN] = $oauth_token;
       $_SESSION[REQUEST_TOKEN_SECRET] = $oauth_token_secret;

 

Step 4 – Redirect user to Constant Contact to Login/Grant Access

Before the Constant Contact API will provide an access token, the Constant Contact user has to authenticate the request token. This is done by sending the user to a predefined Constant Contact authentication page, which asks the user if they wish to grant access to the application that is making the request (ie. Your application). The following code demonstrates this.

       //initialize $context_root variable with application’s root.
       $callback_url = $context_root . "access_token.php";
       $auth_url = URI.'/ws/oauth_authorize_token?oauth_token='.$oauth_token.'&oauth_callback='.urlencode($callback_url);
       Header("Location: $auth_url");

When a user clicks on the confirm button on the final page of the Constant Contact authentication wizard, the page will be redirected to the callback URL ($context_root . "access_token.php").

Step 5 – Exchange Request Token for an Access Token

Now that we have an authenticated request token and its request token secret, we’ll use these to get an access token using the authorize token URL. This code is very similar to the code above which retrieved the request token. The only significant difference is the URL. After getting the access token and access token secret, these can be stored in the session, as they are used in subsequent steps to get access to the API. This example shows storing tokens and secrets in session variables. In a real application these values would typically be stored in a database to be reused later.
Step 5.1 Setup parameters and URL

       $request_token = $_SESSION[REQUEST_TOKEN];
       $request_token_secret = $_SESSION[REQUEST_TOKEN_SECRET];
       $consumer_key = $_SESSION[CONSUMER_KEY];
       $consumer_secret = $_SESSION[CONSUMER_SECRET];
       $access_url = URI.'/ws/oauth_get_access_token';

Step 5.2 Sign access token

       $sig_method = new OAuthSignatureMethod_HMAC_SHA1();
       $access_consumer = new OAuthConsumer($consumer_key, $consumer_secret, NULL);
       $access _token = new OAuthConsumer($request_token, $request_token_secret);
       $parsed = parse_url($access_url);
       $params = array();
       $acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $test_token, "GET", $endpoint, $params);
       $acc_req->sign_request($sig_method, $test_consumer, $test_token);

Step 5.3 Execute request

       $request  = $acc_req->to_url();
       $session = curl_init($request);
       curl_setopt($session, CURLOPT_RETURNTRANSFER, 1);
       // Make the request
       $response = curl_exec($session);
       //Error Handling:
       // there is an error while executing the request, 
       if (!$response) {  
            $response = curl_error($curl);  
        }  
       curl_close($session);

Step 5.4 Store access token and access token secret

       parse_str($response, $params);
       $access_token = $params['oauth_token'];
       $access_token_secret = $params['oauth_token_secret'];
       $_SESSION[ACCESS_TOKEN] = $access_token;
       $_SESSION[ACCESS_TOKEN_SECRET] = $access_token_secret;

 

Step 6 – Access the APIs

Once the access token and access token secret are available, the APIs can be accessed using the following code.

Step 6.1 Sign API request This code shows how to sign the API request using access token and access token secret, obtained in the steps above.

       $consumer = new OAuthConsumer($_SESSION[CONSUMER_KEY], $_SESSION[CONSUMER_SECRET], NULL);
       $token = new OAuthToken($_SESSION[ACCESS_TOKEN], $_SESSION[ACCESS_TOKEN_SECRET]);
       $parsed = parse_url($webServiceUrl);
       $params = array();
       parse_str($postVars, $params);
       $request = OAuthRequest::from_consumer_and_token($consumer, $token, $method, $webServiceUrl, $params);
       $request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, $token);
	

Step 6.2 Execute request This code shows executing the request that is being signed in above step.

       $response = send_request($request->get_normalized_http_method(), 
       	$webServiceUrl, $request, null);
       // Get the XML from the response, bypassing the header
       //Error Handling:
       //if there is an error, response will have error code and 
       //corresponding error message
       if (!($xml = strstr($response, '<?xml'))) {
       	 echo $response;
       	 $xml = null;
       }	

Step 6.3 Render the list from the XML in the response The following code renders a row for each contact list name in the name.

      
       <?php
       if (isset($xml)){
       	$data = simplexml_load_string($xml);
       	foreach ($data->entry AS $item){
       		$shortId = substr($item->id, 
       			strrpos($item->id, "/") + 1)
       ?>
       <input type='checkbox' name='lists[]' 
       	value='<?php echo $item->id ?>'>
       
       <a href='showList.php?listId='>
       <?php echo $item->content->ContactList->Name ?>
       
       <?php
       } ?>