Public Apps

Setup Your Dev Environment

This step is where you will set up the foundation for your new app.

Download the wrapper

Download the PHP API Wrapper below and unzip it.

Download the API PHP Library
  • Fully handles OAuth integration
  • Requires PHP 5.x with Curl support
  • Includes a full PHP Library tutorial

You could also choose to clone the Git repo and alter the php.ini file include_path variable to the path of the API Wrapper.


Create a test file, and let's start coding

For this example we will need one php file. Create this file inside the PHP API Wrapper's directory so that it can find the needed dependencies.

username@localhost:~/my-test-app$ touch mysite.php
username@localhost:~/my-test-app$ vi testApp.php

First, create a virtualenv

The easiest way to go about this is to create a virtualenv for your test app and use pip to install the aweber_api wrapper. Here are the commands to follow:

username@localhost:~$ virtualenv my-test-app
New python executable in my-test-app/bin/python
Please make sure you remove any previous custom paths from your 
/Users/username/.pydistutils.cfg file.
Installing setuptools............done.
Installing pip...............done.

Next, start development mode

username@localhost:~$ cd my-test-app/
username@localhost:~/my-test-app$ source bin/activate

Install the aweber_api using pip

(my-test-app)username@localhost:~/my-test-app$ pip install aweber_api
Downloading/unpacking aweber-api
  Downloading aweber_api-1.4.0.tar.gz
  Running setup.py egg_info for package aweber-api
    no previously-included directories found matching 'doc/.build'

    Installed /Users/username/my-test-app/build/aweber-api/nose-1.1.3.dev-py2.6.egg
Downloading/unpacking httplib2>=0.7.0 (from aweber-api)
  Downloading httplib2-0.7.5.zip (113Kb): 113Kb downloaded
  Running setup.py egg_info for package httplib2
Downloading/unpacking oauth2>=1.2 (from aweber-api)
  Downloading oauth2-1.5.211.tar.gz
  Running setup.py egg_info for package oauth2
Installing collected packages: aweber-api, httplib2, oauth2
  Running setup.py install for aweber-api
  Running setup.py install for httplib2
  Running setup.py install for oauth2
Successfully installed aweber-api httplib2 oauth2
Cleaning up...

Now you can see the dependencies that were installed in your virtualenv

(my-test-app)username@localhost:~/my-test-app$ pip freeze
aweber-api==1.4.0
httplib2==0.7.5
oauth2==1.5.211
wsgiref==0.1.2

Create a test file, and let's start coding

(my-test-app)username@localhost:~/my-test-app$ touch test_app.py
(my-test-app)username@localhost:~/my-test-app$ vi test_app.py

You can use whichever editor you like, vim (MacVim) is just my own preference.

Connecting to AWeber

We are going to show you how to develop a simple application that connects your app to an AWeber Account and then adds a subscriber to a list

There is a security protocol you have to use to connect to the AWeber API and request Account data, you can't just go pulling data all willy-nilly now.

This process is one that is pretty standard and used in a bunch of API's, it's called OAuth.


OAuth in a nutshell:

Step 1: Get AppID and URL's.
Step 2: Login to AWeber Account to get authorization_code.
Step 3: Accept and print access keys.

Let's break it down...


Step 1: Get AppID and URL's

The first thing we need is our App ID. This can be found on your MyApps page and is right next to your consumer keys. The App ID is used when creating public applications. It requires a much easier authentication process and allows the App ID itself to be published. Private applications use the consumer keys for the authentication process and those are not to be distributed or shared.

Next we can set the URL's that we will need in this application. One is the authorization URL which points to the AWeber auth endpoint. The URL https://auth.aweber.com/1.0/oauth/authorize_app/<APP ID> prompts the user to login to their AWeber Account to grant access to their AWeber Account data. The App ID at the end allows AWeber to identify which app a user is trying to connect to.

The other URL we need is a callback URL. In this tutorial we will direct back to our 'oob' which means out of band or not in service.


Step 2: Login to AWeber Account to get authorization code.

This next step can be done in many different ways but the basic idea is to direct the user to login to their AWeber Account. When you run the example, we print the URL to the AWeber auth endpoint. You can copy and paste this into your browser, login to the AWeber Account and enter the authorization_code you receive into the console.


This is what you should see at the AWeber auth endpoint.
Step 3: Accept and print access keys

Use the library specific method shown below to decipher your keys and then print them. This requires a AWeberAPI instance.



The consumer key and secret uniquely identify our application.

They will never change (unless done manually on the My Apps page) and are required to get account data.

The access key and secret allow you to interact with the authenticated AWeber Account.

These are unique to the AWeber Account but can be reused until the account holder disconnects the application or if the consumer keys are changed, which breaks the link between the application and the account.

You could use a database to store these keys for later use. Do not hardcode them if you intend to distribute the source code!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?php
require('aweber_api/aweber_api.php');

# replace XXX with your App ID
$appID = 'XXX';

# prompt user to go to authorization URL
echo "Go to this url in your browser: {$this->application->getAuthorizeUrl()}\n";

# prompt user to enter authorization code
echo 'Type authorization code here: ';
$code = trim(fgets(STDIN));

# exchange authorization code for new consumer keys and secrets, and an access token key and secret
$credentials = AWeberAPI::getDataFromAweberID($code);
list($consumerKey, $consumerSecret, $accessKey, $accessSecret) = $credentials;

?>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from aweber_api import AWeberAPI

# replace XXX with your app ID
app_id = 'XXX'

# prompt user to go to authorization url
authorization_url = 'https://auth.aweber.com/1.0/oauth/authorize_app/%s' % app_id
print 'Go to this url in your browser: %s' % authorization_url

# prompt for authorization code
authorization_code = raw_input('Type code here: ')

# exchange authorization code for new consumer and access keys and secrets
auth = AWeberAPI.parse_authorization_code(authorization_code)
consumer_key, consumer_secret, access_key, access_secret = auth

# print results
print auth

Here is the response:

Array ( [0] => AXXXXXXXXXXXXXXXXXXXXXXJ [1] => XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXI [2] => AXXXXXXXXXXXXXXXXXXXXXXm [3] => aXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX )
(my-test-app)username@localhost:~/my-test-app$ python test_dist.py
Go to this url in your browser: https://auth.aweber.com/1.0/oauth/authorize_app/7XXXXXX8
Type code here: AXXXXXXXXXXXXXXXXXXXXXXJ|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXI|AXXXXXXXXXXXXXXXXXXXXXXJ|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXI|wXXXXb|
('AXXXXXXXXXXXXXXXXXXXXXXJ', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'AXXXXXXXXXXXXXXXXXXXXXXJ', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')



        

Creating A Working App

Congrats, you made it past the hardest step. Now we can do something fun. We can use the built in methods from the wrapper we chose to query the API for information about the AWeber Account we just connected with.

First, we have to change the permissions for our app so that we can request subscriber data from our application.

Asking permission to access subscriber data:

Go to the my Apps page and click on the edit icon to see the settings of the application we have been working with.

Then choose the 'Permission Settings'.

Check the 'Request Subscriber Data' checkbox then click 'Save Permission Settings'.

The What's, the Why's, and the How's

The consumer keys are used to create an AWeberAPI Object which is passed to the API endpoint to identify the application trying to access data.

The access keys allow the application to interact with the AWeber Account that the keys correspond to. An account variable is created from these which holds the Account Entry and can be used for instance, to query all subscribers in an account or to traverse through all data contained within the account that is authenticated.

The addSubscriber() method here requires two variables. The first is a subscriber which can contain any one of these Subscriber Entry Attributes within the associative array. It also requires a List Object which can contain any one of these List Entry Attributes. We only need them so we can get the account and List ids to create the List URL for the resource using the RESTful way.

Once you create the url for the resource you can use the loadFromURL() method to process the GET request. It requires a string with the short path url. It returns the response in the form of an entry or collection object. LoadFromURL() is a method from the AWeberAPIBase class but must be called using a AWeberAPI Object containing all four keys. This is our account variable that we defined in __construct().

To actually create the subscriber, we need to traverse to the Subscribers Collection which is within a List Entry. The Subscriber Entry has a create method that can then be called and requires an associative array with the Subscriber Entry Attributes. After the subscriber is created, the attributes can be accessed as shown.

Notice that there are try/catch blocks to intercept any API issues. Troubleshoot any API errors on our Troubleshooting Page.

Common Errors with this example application:


If you do not have a correct list object or account object, you may encounter following error:
PHP Notice: Trying to get property of non-object
PHP Fatal error: Call to a member function create() on a non-object

If you have not changed the extended permissions, you may encounter the following error: AWeberResourceNotImplemented' with message 'Resource "email" is not implemented on this resource.'

If you have not changed the extended permissions, you may encounter the following error: AWeberResourceNotImplemented' with message 'Resource "email" is not implemented on this resource.'

Finished App

Here lies the complete application. Make sure to paste in the access keys and consumer keys.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
require('aweber_api/aweber_api.php');

class MyApp{

    function __construct() {
        # replace XXX with your real keys and secrets
        $this->consumerKey = 'XXX';
        $this->consumerSecret = 'XXX';
        $this->accessToken = 'XXX';
        $this->accessSecret = 'XXX';

        $this->application = new AWeberAPI($this->consumerKey, $this->consumerSecret);
        $this->account = $application->getAccount($accessToken, $accessSecret);
        $this->list = $this->findList('default');
    }

    function connectToAWeberAccount() {
        $appID = '7XXXXXX8';
        //appID is used to authenticate. To get account data via the api, you
        //must use the consumer key and secret along with the access key and secret
        //associated with the AWeber Account being queried.
        $authorize_url = "https://auth.aweber.com/1.0/oauth/authorize_app/$appID";
        $callback_url = 'http://localhost:8888/aweber-AWeber-API-PHP-Library/mysite.php';

        echo "Go to this url in your browser: {$this->application->getAuthorizeUrl()}\n";
        echo 'Type code here: ';
        $code = trim(fgets(STDIN));

        $credentials = AWeberAPI::getDataFromAweberID($code);
        list($consumerKey, $consumerSecret, $accessKey, $accessSecret) = $credentials;
        print $credentials;
        return $credentials;

    }

    function findList($listName) {
        try {
            $foundLists = $this->account->lists->find(array('name' => $listName));
            //must pass an associative array to the find method

            return $foundLists[0];
        }

        catch(Exception $exc) {
            print $exc;
        }
    }

    function findSubscriber($email) {
        try {
            $foundSubscribers = $this->account->findSubscribers(array('email' => $email));
            //must pass an associative array to the find method

            return $foundSubscribers[0];
        }

        catch(Exception $exc) {
            print $exc;
        }
    }

    function addSubscriber($subscriber, $list) {
        try {
            $listUrl = "/accounts/{$this->account->id}/lists/{$list->id}";
            $list = $this->account->loadFromUrl($listUrl);

            $newSubscriber = $list->subscribers->create($subscriber);
            print_r($newSubscriber);
            print $newSubscriber->email;
            //you need extended permissions to access the subscriber email
        }

        catch(Exception $exc) {
            print $exc;
        }
    }
}


$app = new MyApp();

$app->findSubscriber('whtever@aol.com');

$list = $app->findList('default');

$subscriber = array(
    'email' => 'johndoe@example.com',
    'name'  => 'John Doe'
);

$app->addSubscriber($subscriber, $list);
?>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from aweber_api import AWeberAPI


class MyApp(object):

    def __init__(self):
        # replace XXX with your keys
        consumer_key = 'XXX'
        consumer_secret = 'XXX'
        self.access_token = 'XXX'
        self.access_secret = 'XXX'

        self.application = AWeberAPI(consumer_key, consumer_secret)
        self.account = self.application.get_account(self.access_token, self.access_secret)

    def connect_to_AWeber_account(self):
        app_id = '7XXXXXX8'
        authorization_url = 'https://auth.aweber.com/1.0/oauth/authorize_app/%s' % app_id
        print 'Go to this url in your browser: %s' % authorization_url
        authorization_code = raw_input('Type code here: ')

        auth = AWeberAPI.parse_authorization_code(authorization_code)
        consumer_key, consumer_secret, access_key, access_secret = auth
        print auth
        return auth

    def find_list(self):
        lists = self.account.lists.find(name="default")
        return lists[0]

    def find_subscriber(self):
        subscribers = self.account.findSubscribers(email="whtever@example.com")
        return subscribers[0]

    def add_subscriber(self, subscriber, _list):
        list_url = '/accounts/%s/lists/%s' % (self.account.id, _list.id)
        _list = self.account.load_from_url(list_url)

        try:
            new_subscriber = _list.subscribers.create(**subscriber)
            print new_subscriber.email

        except Exception, exc:
            print exc


app = MyApp()
_list = app.find_list()
subscriber = {
    'email': 'johndoe@example.com',
    'name': 'john doe',
}
app.add_subscriber(subscriber, _list)