How To Set Up Recurring Payments In Authorize.net

We have written an article Accept Credit Card Payment Using Authorize.net Payment Gateway. In that article, we discussed how one can receive credit card payment through Authorize.net. Also, that article is basically focused on one-time payment.

But what if someone wants to integrate recurring payments in their application? In this article, we show you how to set up recurring payments using Authorize.net.

What Is Recurring Payment?

Recurring or subscription payment means automatically charge credit card a fixed amount after a specific interval and for a specified time period.

For instance, let’s say you are running your website on the Bluehost hosting and you have paid an amount for the first year. When your plan expires Bluehost will automatically charge your credit card payment for the next year(if you have chosen recurring payment option).

The benefit of allowing subscription plan is you don’t need to remember expiry date of service you are using. Service provider keeps it as an automated system. Once your plan expired, they renew your service by taking payments from your credit card in the background.

Having said that, let’s see how to set up recurring payments using Authorize.net.

You should first read our article Accept Credit Card Payment Using Authorize.net Payment Gateway. In that article, we have discussed about installation and configuration of Authorize.net SDK libraries.

For our tutorial, we are using the sandbox account. So you should first create your Sandbox account and get your API keys. You can find your API keys from Account->API Credentials & Keys.

Installation

To get started, we need to install PHP SDK Library. We recommend Composer for installing the library.

Create a composer.json file in your project root directory and add the below code in it.

composer.json

{
    "require": {
        "php": ">=5.6",
        "authorizenet/authorizenet": "~1.9.6"
    }
}

Open the terminal in your project root directory and run the composer install command. This command will download the dependency of a library.

Set Up The Environment

We have installed the PHP SDK library. Now create two files called constants.php and subscriptionpayment.php. In the constants.php file we store our API keys as follows.

constants.php

<?php
define('ANET_LOGIN_ID', 'YOUR_LOGIN_ID');
define('ANET_TRANSACTION_KEY', 'YOUR_TRANSACTION_KEY');
?>

Make sure you have replaced placeholders YOUR_LOGIN_ID and YOUR_TRANSACTION_KEY with actual values.

subscriptionpayment.php is the file where we will write a code for subscription payments of a credit card. To do so first, we need to include core files from the library.

subscriptionpayment.php

<?php
require_once "vendor/autoload.php";
require_once "constants.php";
 
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
?>

Actual Code For Recurring Payments In Authorize.net

Authorize.net provides a sample code library for developers reference. For our tutorial, we are using the reference of RecurringBilling.

We slightly modify createSubscription method from the reference code and write it as follows.

function createSubscription($arr_data = [])
{
    extract($arr_data);
    /* Create a merchantAuthenticationType object with authentication details
       retrieved from the constants file */
    $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
    $merchantAuthentication->setName(ANET_LOGIN_ID);
    $merchantAuthentication->setTransactionKey(ANET_TRANSACTION_KEY);
     
    // Set the transaction's refId
    $refId = 'ref' . time();
    // Subscription Type Info
    $subscription = new AnetAPI\ARBSubscriptionType();
    $subscription->setName("Sample Subscription");
    $interval = new AnetAPI\PaymentScheduleType\IntervalAType();
    $interval->setLength($intervalLength);
    $interval->setUnit("days");
    $paymentSchedule = new AnetAPI\PaymentScheduleType();
    $paymentSchedule->setInterval($interval);
    $paymentSchedule->setStartDate(new DateTime($start_date));
    $paymentSchedule->setTotalOccurrences($totalcycles);
    //$paymentSchedule->setTrialOccurrences("1");
    $subscription->setPaymentSchedule($paymentSchedule);
    $subscription->setAmount($amount);
    //$subscription->setTrialAmount("0.00");
     
    $creditCard = new AnetAPI\CreditCardType();
    $creditCard->setCardNumber($card_number);
    $creditCard->setExpirationDate($expiry_date);
    $payment = new AnetAPI\PaymentType();
    $payment->setCreditCard($creditCard);
    $subscription->setPayment($payment);
    $order = new AnetAPI\OrderType();
    $order->setInvoiceNumber(mt_rand(10000, 99999));   //generate random invoice number     
    $order->setDescription("Daily Subscription For 1 USD"); 
    $subscription->setOrder($order); 
     
    $billTo = new AnetAPI\NameAndAddressType();
    $billTo->setFirstName($first_name);
    $billTo->setLastName($last_name);
    $subscription->setBillTo($billTo);
    $request = new AnetAPI\ARBCreateSubscriptionRequest();
    $request->setmerchantAuthentication($merchantAuthentication);
    $request->setRefId($refId);
    $request->setSubscription($subscription);
    $controller = new AnetController\ARBCreateSubscriptionController($request);
    $response = $controller->executeWithApiResponse( \net\authorize\api\constants\ANetEnvironment::SANDBOX);
     
    if (($response != null) && ($response->getMessages()->getResultCode() == "Ok") )
    {
        echo "SUCCESS: Subscription ID : " . $response->getSubscriptionId() . "\n";
     }
    else
    {
        echo "ERROR :  Invalid response\n";
        $errorMessages = $response->getMessages()->getMessage();
        echo "Response : " . $errorMessages[0]->getCode() . "  " .$errorMessages[0]->getText() . "\n";
    }
    return $response;
}

Notice the line $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX); from the above method. When we shift to production we should change SANDBOX to PRODUCTION in this line. Also we need to change our login id and transaction keys to match with our live account.

Our method createSubscription takes an array parameter which we should build in below way.

$arr_subscription = [
    'intervalLength' => 7, // Here 7 means recurring payment occurs after each 7 days
    'start_date' => date('Y-m-d'),
    'totalcycles' => 10, //Billing cycles. Here 10 means 10 transactions
    'amount' => 1.00,
    'card_number' => '4111111111111111',
    'expiry_date' => '2020-12',
    'first_name' => 'John',
    'last_name' => 'Smith'
];

We are using test credit card numbers provided on Testing Guide.

By passing above array to the function createSubscription, it will create a subscription payment of 1.00 USD after each 7 days up to 10 billing cycles.

Recurring Payment

Final Code

subscriptionpaymen.phpt

<?php
require_once "vendor/autoload.php";
require_once "constants.php";
 
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
 
$arr_subscription = [
    'intervalLength' => 7,
    'start_date' => date('Y-m-d'),
    'totalcycles' => 10,
    'amount' => 1.00,
    'card_number' => '4111111111111111',
    'expiry_date' => '2020-12',
    'first_name' => 'John',
    'last_name' => 'Smith'
];
 
createSubscription($arr_subscription);
 
function createSubscription($arr_data = [])
{
    extract($arr_data);
    /* Create a merchantAuthenticationType object with authentication details
       retrieved from the constants file */
    $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
    $merchantAuthentication->setName(ANET_LOGIN_ID);
    $merchantAuthentication->setTransactionKey(ANET_TRANSACTION_KEY);
     
    // Set the transaction's refId
    $refId = 'ref' . time();
    // Subscription Type Info
    $subscription = new AnetAPI\ARBSubscriptionType();
    $subscription->setName("Sample Subscription");
    $interval = new AnetAPI\PaymentScheduleType\IntervalAType();
    $interval->setLength($intervalLength);
    $interval->setUnit("days");
    $paymentSchedule = new AnetAPI\PaymentScheduleType();
    $paymentSchedule->setInterval($interval);
    $paymentSchedule->setStartDate(new DateTime($start_date));
    $paymentSchedule->setTotalOccurrences($totalcycles);
    //$paymentSchedule->setTrialOccurrences("1");
    $subscription->setPaymentSchedule($paymentSchedule);
    $subscription->setAmount($amount);
    //$subscription->setTrialAmount("0.00");
     
    $creditCard = new AnetAPI\CreditCardType();
    $creditCard->setCardNumber($card_number);
    $creditCard->setExpirationDate($expiry_date);
    $payment = new AnetAPI\PaymentType();
    $payment->setCreditCard($creditCard);
    $subscription->setPayment($payment);
    $order = new AnetAPI\OrderType();
    $order->setInvoiceNumber(mt_rand(10000, 99999));   //generate random invoice number     
    $order->setDescription("Daily Subscription For 1 USD"); 
    $subscription->setOrder($order); 
     
    $billTo = new AnetAPI\NameAndAddressType();
    $billTo->setFirstName($first_name);
    $billTo->setLastName($last_name);
    $subscription->setBillTo($billTo);
    $request = new AnetAPI\ARBCreateSubscriptionRequest();
    $request->setmerchantAuthentication($merchantAuthentication);
    $request->setRefId($refId);
    $request->setSubscription($subscription);
    $controller = new AnetController\ARBCreateSubscriptionController($request);
    $response = $controller->executeWithApiResponse( \net\authorize\api\constants\ANetEnvironment::SANDBOX);
     
    if (($response != null) && ($response->getMessages()->getResultCode() == "Ok") )
    {
        echo "SUCCESS: Subscription ID : " . $response->getSubscriptionId() . "\n";
     }
    else
    {
        echo "ERROR :  Invalid response\n";
        $errorMessages = $response->getMessages()->getMessage();
        echo "Response : " . $errorMessages[0]->getCode() . "  " .$errorMessages[0]->getText() . "\n";
    }
    return $response;
}
?>

We hope you understand how to set up recurring payments in Authorize.net. Please share your thoughts in the comment section below.

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

1 thought on “How To Set Up Recurring Payments In Authorize.net

  1. Hi can you tell me why payment successfully in PRODUCTION mode. if i am using SANBOX cart info
    i am following your code instruction

Leave a Reply

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