PHP - Have my token...now what?

Highlighted
Occasional Participant

PHP - Have my token...now what?

Please forgive me for being repetitive. I originally posted a comment on another (similar) thread, but haven't gotten any responses.

 

I've done API work for Hubspot and Mailchimp, but I am beyond baffled at Constant Contact's PHP samples. Hopefully, I'm missing something painfully simple.

 

I have bumbled my way through the OAuth2 process, and have my token, which I plan on storing in a database and calling as necessary- as other users have suggested.

 

My question is this: What in the world do I now do with this token? I am working from the PHP wrapper. There are a number of references to hard-coding the token (or calling it from a DB, etc) but I can find no mention of how to actually do this. For example, the addContact.php sample tells me that the user could not be found in the Datastore and must be authorized. I do so, and get my token. Great. Wonderful. But where can I "plug in" the token so that the sample app can make use of it? As is, the sample applications don't seem to do much beyond walking you through getting the token.

 

Could someone help me identify where in the PHP wrapper I would provide the token such that I don't have to authorize every single time? What is the point of having an API if I still have to provide my credentials for every new session?

 

Again, please pardon my frustration. I must be missing something very elementary and any insight would be terrific.

14 REPLIES 14
Highlighted
CTCT Employee

Re: PHP - Have my token...now what?

Hi,

 

I made the following changes to the index.php file to use my access token.  I commented out the datastore object (the if-else container around pretty much everything in our example.  The end result is this code.  I just removed everything I had commented out from our wrapper for clarity.  The config.php file only contains this:

 

<?php

$username = "";
$accessToken = "";
$apikey = "";

?>

 The index.php only contains this.  It is a very simple Search for a contact form.  You can see I just completely removed the datastore object.  It is really just there to show people how they would get people to auhorize the app and then it would be up to the developer how they would want to store the information like access token.

 

<?php

session_start ();
require_once 'ConstantContact.php';
require_once 'config.php';
		
$ConstantContact = new ConstantContact ( "oauth2", $apikey, $username, $accessToken );
?>

<html>
<body> <H1>Search for a contact</H1> <form action="index.php" method="post"> <input type="text" name="searchEmailAddress" maxlength="50" /> <input type="submit" name="submit" value="Submit" /> </form> <?php // False would represent the contact not existing if($search != false){ $details = $ConstantContact->getContactDetails($search[0]); echo $details->emailAddress . " Exists"; $ConstantContact->DeleteContact($search[0]); echo $details->emailAddress . "Updated"; session_destroy(); } // Prints all details of that contact print_r($details); ?> </body> </html>

I hope that helps show the code that is really needed for authentication (not much).

 

Best Regards,

Shannon W.

API Support Specialist

Highlighted
Occasional Participant

Re: PHP - Have my token...now what?

Shannon:

 

Thank you kindly. I'll have to toy with this a bit, but it seems I was getting hung up on the datastore object, which (for my uses) is not necessary.

 

Many, many thanks.

Highlighted
Occasional Participant

Re: PHP - Have my token...now what?

Hi Shannon, 

I'm trying to use your test example to ultimately create a signup form, without success. I'm pretty sure that it's not a problem with the authentication... I have my access token hard coded in config.php, and am able to retrieve a xml feed list of users in the browser by appending this token to the querystring. What I have is identical to the config.php and index.php in your post, however, this always returns:

Constant Contact HTTP Request Exception: 

 Troubleshooting the file, it appears that any method causes this error. I'm able to successfully create the $ConstantContact object for example:

<?php
session_start ();
require_once 'ConstantContact.php';
require_once 'config.php';
		
$ConstantContact = new ConstantContact("oauth2", $apiKey, $username, $accessToken);
echo '<pre>';
print_r($ConstantContact);
echo '</pre>';
/* WILL OUTPUT
ConstantContact Object
(
    [apiKey] => 
    [username] => myUser
    [password] => 
    [consumerSecret] => 
    [CTCTRequest] => CTCTRequest Object
        (
            [baseUri] => https://api.constantcontact.com
            [username] => myUser
            [apiKey] => XXXMYAPIKEYXXX
            [authType] => oauth2
            [requestLogin] => 
            [consumerSecret] => 
            [consumer] => 
            [accessToken] => 
            [signatureMethod] => 
            [access_token] => XXXMYACCESSTOKENXXX
        )

    [authType] => oauth2
)
*/
?>

I'm also able to build a new $Contact(), but any method (Like $ConstantContact->getContactDetails() in your example or $ConstantContact->addContact($Contact) will return the unknown "HTTP Request exception." Any ideas why even this simple example wouldn't work?

Thx

Highlighted
CTCT Employee

Re: PHP - Have my token...now what?

Hi,

 

Did you download the PHP wrapper files at our main PHP wrapper repository here?  The first thing I would try is to replace the files other than config.php and index.php (which has code you modified) with the files hosted there, to be sure you have everything you need in the files.  

 

Best Regards,

Shannon W.

API Support Specialist

Highlighted
Occasional Participant

Re: PHP - Have my token...now what?

@Shannon

Hello,

Yes, I'm using the github repository above. I've also used your github repo to retrieve my access token and successful used it by appending it to the endpoint. (For example retrieve a list of all contacts or a particular contact by email address.)

I'm still not able to successfully use the API. For the sake of trouble shooting I'm trying to simplify things as much as possible:

This is my config.php:

<?php
$username = "MyAccount";
$accessToken = "XXX-MYACCESSTOKEN-XXX";
$apikey = "XXX-MYAPIKEY-XXX";
?>

 

 

This is my index.php:

<?php
session_start ();
require_once 'ConstantContact.php';
require_once 'config.php';
 
$ConstantContact = new ConstantContact("oauth2", $apiKey, $username, $accessToken);
$Contact = new Contact();
$Contact->emailAddress = 'ExistingUser@email.com';
$email_exists = $ConstantContact->searchContactsByEmail($Contact->emailAddress);
    if($email_exists == false || $email_exists == ''){
        echo 'searchContactsByEmail() returned nothing';   
    } else {
        echo 'User is already registered';   
    }
?>

 

This index.php outputs the following line:

Constant Contact HTTP Request Exception: 

searchContactsByEmail() returned nothing

 

I looks like the Constant Contact error comes from an exception thrown in CTCTRequest "makeRequest" method. (basically, a cUrl error.) I've output debug_backtrace() within "makeRequest" and everything appears to be okay up to that point, it's the actually cUrl that isn't working. Trying to recreate by hardcoding recreating the cUrl by itself in a separate file also doesn't work with curl_errno() outputting:

"Curl error: SSL connection timeout" 

 

I've tried numerous cUrl options trying to get this to work without any luck. any ideas?

Thank you.

 

example cUrl script (outputs "SSL connection timeout")

    if (!function_exists('curl_init')){
        die('cURL is not installed!');
    }
    $curl = curl_init();
 
    curl_setopt($curl, CURLOPT_URL, "https://api.constantcontact.com/ws/customers/MyAccount/contacts?email=KnownUser@email.com");
    curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
    curl_setopt($curl, CURLOPT_HEADER, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_TIMEOUT, 20);
    //curl_setopt($curl, CURLOPT_HTTPGET, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: Bearer XXX-MYACCESSTOKEN-XXX, ContentType: application/atom+xml, Accept: application/atom+xml"));
    $output = curl_exec($curl);
    if($output === false){
        echo 'Curl error: ' . curl_error($curl);
        $info = curl_getinfo($curl);
        echo '<pre>';
        print_r($info);
        echo '</pre>';
    } else {
        echo $output;
    }
    curl_close($curl);

 

 

Highlighted
Occasional Participant

Re: PHP - Have my token...now what?

One small correction... rereading my previous post the $apiKey variables don't match.

This is not the problem, and was just a case of me copying from a different version to create the above post. As I said, the debug_backtrace correctly traces through all classes with the correct properties (api, email, access_token, etc.) until the "makeRequest" method.

 

thanks again.

Highlighted
CTCT Employee

Re: PHP - Have my token...now what?

Hi,

 

I suspect something is going awry and the contact object isn't getting created fully according to what our system needs to handle it.  I am looking into this to give you a simple example of something that should work using methods.   Thanks for your patience.

 

Best Regards,

Shannon W.

API Support Specialist

Highlighted
CTCT Employee

Re: PHP - Have my token...now what?

Hi,

 

Want to try this add/update contact example and see if it works for you?

 

<?php

session_start ();
require_once 'ConstantContact.php';
require_once 'config.php';

$ConstantContact = new ConstantContact("oauth2", $apiKey, $username, $accessToken); 

// Get potential contact lists
$lists = $ConstantContact->getLists();
// Lists are returned in multidimentional arrays 0 being the list, and 1 being the next50

// Email address here is used for testing purposes
// NOTE:  This email address will be added to your account if you execute this script,
//		  you should send this to do-not-mail after your testing
$emailAddress = "testemail10162012@test.com";

// Search for our new Email address
$search = $ConstantContact->searchContactsByEmail($emailAddress);

// If the search didnt return a contact object
if($search == false)
{
	// Create a new Contact Object to store data into
	$contactObj = new Contact();
	// Adding multiple lists to this new Contact Object
	$contactObj->lists = array($lists['lists'][0]->id, $lists['lists'][1]->id);
	// Set the email address
	$contactObj->emailAddress = $emailAddress;
	// Create the Contact and DONE
	$Contact = $ConstantContact->addContact($contactObj);
}
// Otherwise we update our existing else { // Gather data from our previous search and store it into a data type $contactObj = $ConstantContact->getContactDetails($search[0]); // We need to get the old list and add a new list to it as // this request requires a PUT and will remove the lists // as they are stored in an array array_push($contactObj->lists, $lists['lists'][1]->id ); // Update the contact and DONE $UpdateContact = $ConstantContact->updateContact($contactObj); } ?>

 

 

Best Regards,

Shannon W.

API Support Specialist

Highlighted
Occasional Participant

Re: PHP - Have my token...now what?

Hi Shannon,

This returned the same error message, and no email was added to contacts list:

Constant Contact HTTP Request Exception: 

 

Developer Portal

View API documentation, code samples, get your API key.

Constant Contact Would Like To Hear From You!

We want to hear from customers like you about your favorite features and how they have helped your business or organization. Tell us by answering a few questions in...

Read More
Featured