Getting Started with Dwolla PHP – Send Payment Example

Recently Dwolla released a new API (Dwolla PHP) for PHP Developers. The API is wonderfully simple to use, and pretty well documented, but it took me some time to work through the kinks to get it working properly. Since I couldn’t find a straight-forward, end-to-end example for using the API to send a payment, I thought I should just write one myself.
Dwolla Logo


The scope of this application is to use Dwolla PHP APIs to send a custom payment to my 1099 contractors who market products in my online stores. I enter the dollar amount and choose my funding source, then click the button and they get paid. I built this application in WordPress, but tried to leave the code general enough to be applied anywhere. I’ll comment the code, though, so no matter what platform you’re using you’ll still know what’s going on.



At this point, I’m assuming that you already have a Dwolla account and a Dwolla Application with a Key and Secret Key.


Dwolla PHP Overview

Before diving into the code to send an automated payment from your own Dwolla account to another Dwolla account, it’s helpful to understand the big picture. The API documentation for Dwolla PHP is really good for individual components, but stringing those end to end to send a Dwolla payment wasn’t laid out quite as clear. To send a payment using Dwolla, here are the steps we’ll cover:

  1. Authenticate the recipient’s account OR get their email address or phone number.
  2. Authenticate your own account and obtain a refresh_token.
  3. Use the recipient’s refresh_token to get an access_token from Dwolla.
  4. Use the recipient’s access_token to get their Dwolla ID.
  5. Use your refresh_token to get an access_token from Dwolla.
  6. If necessary, choose an alternative funding account ID (to send payments using a bank account instead of your Dwolla balance).
  7. Send the payment.


Authenticating the Recipient’s Account

If you want to know the easy way, just ask for the recipient’s email address or phone number. If they have a Dwolla account associated with these, it will issue the payment there, or prompt them to create an account if they don’t have one already. For my purposes, chose to authenticate the recipient’s actual Dwolla account.

The first thing you need to do is generate an authentication URL using your Key and Secret Key (which can either be set in the /dwolla/lib/_settings.php file, or stored in your database). The Dwolla PHP API makes this very easy. You’ll need to tell Dwolla where to send your recipient after they’ve authenticated their account, so start there. You’ll also need to determine which scopes (permissions) your application will need for this transaction. If you’re only sending money, all you’ll need is ‘AccountInfoFull’. Your end code should look something similar to this:

// Set redirect location - recipient will be sent here after they authenticate/login with Dwolla.
$redirect = '';

// Get keys/pin from database.
$key = getKeyFromDatabase();
$secret_key = getSecretKeyFromDatabase();

// Set scope/permissions.
$scope = 'AccountInfoFull';

// Instantiate new OAuth class object and set values.
$OAuth = new Dwolla\OAuth();
$OAuth->settings->client_id = $key;
$OAuth->settings->client_secret = $secret_key;
$OAuth->settings->oauth_scope = $scope;

// Generate the Authentication URL.
$OAuth_url = $auth->genAuthUrl($redirect);


Once the Authentication URL gets generated, you can add this as a link anywhere in your page with instructions for your payee/recipient to click it to authenticate their account with Dwolla. They’ll be directed to Dwolla’s site where they will log in, be prompted to accept the scope/permissions you’re requesting, then be redirected to the page you provided in your $redirect variable.

Now, this is important! When Dwolla redirects you back to your page, they will include a $_GET paramater in the URL called ‘code’. This is what you’ll use to get your first set of tokens. The tokens we’re requesting from Dwolla are an ‘access_token’ and a ‘refresh_token’. The access_token expires after a short amount of time (an hour at the time of this writing), while the refresh_token expires after a much longer length of time (currently 60 days). The idea is that you’ll need an access_token to do anything with the APIs (e.g. transactions), and you’ll use the refresh_token to get a new access_token using the Dwolla PHP API each time you need a new code.

To get these tokens, your code should resemble this:


// Grab the OAuth code from the URL.
if(isset($_GET['code']) && $_GET['code']) {
    $OAuth_code = strip_tags($_GET['code']);

// Initiate refresh_token variable. 
$refresh_token = '';

// If the code is present in our URL, try to get access and refresh tokens.
if($OAuth_code) {
    // Get the token. Note that this is the same $redirect variable used to generate the Authentication URL and get your Dwolla 'code' above.
    $tokens = $auth->get($OAuth_code, $redirect);

    // If everything was successful, then these values should exist. Let's at least save/update the refresh_token in our database. 
    if(isset($tokens['refresh_token']) && $tokens['refresh_token'] && $tokens['refresh_token'] != '') {
        $refresh_token = $tokens['refresh_token'];
    } else {
        // Error handling.


So at this point, you should have received a valid $refresh_token using Dwolla PHP and have it stored in your database. Your payee/recipient has been successfully authenticated.


Authenticating Your Account as the Paying Party

Using Dwolla PHP to authenticate your account is very similar to authenticating the recipient’s account. There are only 2 primary differences here:

  1. You’ll use the generated Authentication URL to log into your Dwolla account, using your credentials.
  2. You’ll need to use a different scope/set of permissions. For our purposes, we’ll need to use at least Send and Funding, though I actually include others: ‘Send|Transactions|Request|AccountInfoFull|Funding’. (The pipe separators are how additional permissions are formatted, so if you wanted to use these specific permissions, you could just copy and paste everything between the single quotes as-is.)

The last thing I’ll say here is to be sure to store your refresh_token using a name that is clearly distinguishable from your recipient’s refresh_token. It can get a bit confusing, since you’re using two separate refresh_tokens.

Note: Alternatively, you could just authenticate your recipient once, get their Dwolla ID as shown below, and store their ID in your database. I chose to have them authenticate and use a refresh_token to be more flexible in case they wanted to create a business account.


Get the Recipient’s Access Token

Once you have a refresh_token, getting an access_token (to get account ID) is pretty straightforward.

Note: You only need the recipient’s access_token if you’re going to get their Dwolla ID. If you plan on using their phone number or email address to send them payments, you can skip this step – in fact, you didn’t really need to authenticate them at all.

Here’s the code, with comments…


// Get keys from database.
$key = getKeyFromDatabase();
$secret_key = getSecretKeyFromDatabase();

// Get recipient's refresh_token from database.
$recipient_refresh_token = getRefreshTokenFromDatabase();

// Instantiate object and update settings.
$recipient_OAuth = new Dwolla\OAuth();
$recipient_OAuth->settings->client_id = $key;
$recipient_OAuth->settings->client_secret = $secret_key;

// Get a new set of tokens.
$recipient_results = $recipient_OAuth->refresh($recipient_refresh_token);

// Check for error messages in Dwolla's return data.
if($error = $recipient_results['error']) {
    // Error handling.

// Update the refresh_token in the database.
if($new_recipient_refresh_token = $recipient_results['refresh_token']) {

// Check for an access_token. If not present, handle the error.
if(!$recipient_access_token = $contractor_result['access_token']) {
    // Error handling


Using the access_token just received we can now use Dwolla PHP to get their account ID.


Get the Recipient’s Dwolla ID

Getting the recipient’s account ID is also pretty straightforward, thanks to the Dwolla PHP API. The code should look like this:


// For this, we'll use the $recipient_access_token found above.
$recipient_info = new Dwolla\Account();

// Update the access_token setting for this object.
$recipient_info->settings->oauth_token = $recipient_access_token;

// Get full account details.
$recipient_info_details = $recipient_info->full();

// Grab their Dwolla ID.
$recipient_dwolla_id = $recipient_info_details['Id'];


We’ll soon use this $recipient_dwolla_id value to issue the payment to our recipient.


Use Your Refresh Token (as Sender) to Get an Access Token (to Send Payment)

The code is essentially identical to that posted above for the Recipient’s access_token. The only real difference is that you get and update YOUR refresh_token in the database.


Choose the Account from which to Fund the Payment

Once you have your own access_token you can use the Dwolla PHP API to get a list of your verified funding accounts in Dwolla. I actually have this set up as a form, together with the custom payment input box. The code below loops through each funding source and creates a radio element that you can choose from. In your application, you can just grab the $_POST value of the funding source selected and use it to send the payment.

Note: If you only plan on paying from your Dwolla balance, this part isn’t necessary. If you’d like the option to choose, though, this can be helpful. The code will likely go in an input form on the page where your payment UI is.


// Get funding sources.
$funding_sources = new Dwolla\fundingSources();

// Update settings with new access_token.
$funding_sources->settings->oauth_token = $sender_access_token;
$funding_results = $fundingSources->get();


From here, it’s easy to loop through them to create radio buttons for your form (entire form included here for convenience):


// Display form
$r = '';
$r .= ' 
' . "\n"; $r .= '

Custom Payments

' . "\n"; $r .= '

Select an account and enter a dollar amount to pay this recipient. (numbers only, e.g. "12.75")

' . "\n"; // Loop through accounts and print radio buttons. Note that we'll use the account ID (a long string of numbers and letters) as the radio input's value. foreach($fundingResults as $result) { $r .= ' ' . $result['Name'] . "\n"; $r .= '
' . "\n"; } $r .= '
' . "\n"; // Number input box for custom dollar amounts. $r .= ' ' . "\n"; $r .= '

' . "\n"; $r .= ' ' . "\n"; $r .= '
' . "\n"; $r .= '
' . "\n"; echo($r);

Now that you have your form in the UI, in your application page you can look for the $_POST value for the funding source (‘payment-source’):


// Grab payment source (funding source ID). 
if(isset($_POST['payment-source']) && $_POST['payment-source']) {
    $payment_source = strip_tags($_POST['payment-source']);

// Grab the payment-amount from the form.
if(isset($_POST['payment-amount']) && $_POST['payment-amount']) {
    $payment_amount = strip_tags($_POST['payment-amount']);


Now we’re ready to make a payment!


Sending the Payment

Now you have all of the information you need to send secure payments using the Dwolla PHP API.

// Start by getting your Dwolla PIN from the database (note: This is YOUR pin from the sending account, which should match the access_token we got for YOU, not the recipient).
$pin = getPinFromDatabase();

try {
    $pmt = new Dwolla\Transactions();
    $pmt->settings->oauth_token = $sender_access_token;
    $pmt->settings->pin = $pin;

    // Attempt to send the payment. Note that 'fundsSource' is looking for the ID of a funding source linked to your Dwolla account. There are other parameters that could go here, but for now this is all we need.
    $transaction_result = $pmt->send($recipient_dwolla_id, $payment_amount, ['fundsSource' => $payment_source]);

    // If we don't get an error during this try block, we'll assume it's successful. Response is the transaction ID, if the payment was made, otherwise a return message such as "Insufficient funds", or "Invalid PIN" or the like.
    $message = 'Transaction result: ' . $transaction_result;
    $type = 'updated';
    displaySuccessMessage($message, $type);

    // If we didn't get an error, let's store the details in the database. I would recommend storing the $transaction_result (even if it's an error message), the amount paid (or attempted), and the date/time in a format similar to this: date("Y_m_d, H:i:s").
    $transaction_result = strip_tags($transaction_result);
} catch (Exception $e) {
    // Error handling

That’s it! From here, you should find the transaction logged in your Dwolla account. Good luck with your implementation – let me know how things are going in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.