Codementor Events

Integrating Authorize.net as your Payment Gateway in PHP

Published Nov 22, 2016Last updated Jan 18, 2017

Authorize.net is simple and easy to attach payment gateway solutions. That is the reason why you see a lot of eCommerce platforms offering seamless integration with it.

If you are looking for an accurate way to integrate Authorize.net payment gateway in your custom PHP web application, this tutorial is for you. The process described here uses official PHP SDK by Authorize.net which allows you to capture the payment right from your website, giving you the payment processing response so you don’t actually need the payment notification page and post processing.

We will be covering the following three points to properly attach Authorize.net as your project’s payment gateway:

  • Authorize.net sandbox account
  • Composer
  • How to integrate Authorize.net
  • Switching from sandbox to production

Authorize.net sandbox account

First things first, you will need a sandbox account with Authorize.net to create and test the solution. The process is fairly easy. You need to access and fill the sandbox signup form details.

We will need the API login ID and Transaction ID in our code. You may receive that information in the welcome email. If not, you can see those details on my API page.

Composer

Make sure you have Composer installed, set up; and if you are on Windows, make sure it’s set up in a global environment path.

Are you using a Windows machine? To check if you have Composer installed or not, open C:\ProgramData\ and look for the ComposerSetup directory. The other way to check it would be opening CMD then composer command.

Once you checked and you found out you don’t have Composer installed on your machine, install it by getting it from the Composer website.

Let’s add Composer to the system path so that you can access it globally. Edit your Environment Variable and add this C:\ProgramData\ComposerSetup\bin. Relaunch your CMD and fire composer –version.

Why we need Composer?

Composer is a popular dependency manager tool for PHP. And what is a dependency manager? Suppose one of your project modules depends on a library but that library depends on three other libraries. The composer makes your work easy in such cases. You need to ask the composer to add the libraries your project depend on. The composer will then  manage other sub-dependencies. Easy right?

I hope you have a local Apache – MySQL and PHP setup ready. If not here is the guide to help you manually install apache MySQL and PHP on your Windows machine and mac machine. If you prefer XAMMP, here’s how you can set up a PHP development and production server environments.

Integration

Authorize.net API Document would be a great place to start exploring the API and various parameter explanations. And in this tutorial, we will be exploring the Charge Credit Card method. It’s basically the method to authorize and capture a credit card payment.

First, we need to create a composer.json into your project directory to add the Authorize.net PHP SDK into our project.

You can refer to the official aAuthorize.net composer.json file here. Create a file and copy the content into your file, then hit save. You have two ways:

  1. CMD : As we set the composer into environment path. You can fire Composer commands from any location. Go to your project directory where composer.json file placed. Hit the composer install
  2. Netbeans: If you are using Netbeans like me, you need to right-click the project directory, select the Composer from the menu item, then Install. You will be able to see the rest of the process in the output window.

Once this process completed, you should have a vendor folder created in the project directory. Alternatively, you can download the Authorize.net PHP SDK. Extract it to your project directory and run the composer update command:

    require 'vendor/autoload.php';
    use net\authorize\api\contract\v1 as AnetAPI;
    use net\authorize\api\controller as AnetController;

We have added the autoload.php file in the first line. When we are dealing with a large number of classes, we probably don’t want to deal with individual class inclusion—Autoload.php handles the class inclusion for us.

Next, let’s add two namespaces contract\v1 and controller. If you are wondering where you can find the classes underlying the namespaces, you can find them under: vendor\authorizenet\authorizenet\lib\net\authorize\api\

Before proceeding further, let’s make sure you have the constants directory added to your project directory _(Note: The reason I’m asking you to confirm is because, in my testing, I got some error with Composer adding constant directory and files). _If you don’t have it, download the SDK zip via GitHub and extract the zip file. Find the constant directory and paste it into your project directory. Now we’re good to go.

Go to constants directory and open up the constants.php file. Set the up login_id and transaction_key that you have with your Authorize.net sandbox account. In this tutorial, you will be the merchant.

As I said earlier, we are authorizing and charging a credit card payment via Authorize.net and we can do this by creating a method named chargeCreditCard.

    function chargeCreditCard($amount){ … }

This function accepts one argument, that is the amount we are charging to the customer.

As for the payment process, it will be divided into these sections:

  1. Setting up the merchant information
  2. Setting up the credit card information
  3. Setting up the order information
  4. Setting up the transaction information
  5. Setting up the customer information
  6. Making the payment request and processing

1. Setting up the merchant information:

We are setting up the merchant object that contains your login_id, transaction_key, and a referenceId data.

    function chargeCreditCard($amount){ … }

2. Setting up the credit card information

When we are in sandbox mode, Authorize.net allows us to test the payment processing flow via dummy credit card numbers.

We will spare ourselves with entering the mock credit card detail every time we need it in the UI. So, we will create an object of CreditCardType and fill those mock card details here.

    // Create the payment data for a credit card
    $creditCard = new AnetAPI\CreditCardType();
    $creditCard->setCardNumber("4111111111111111");
    $creditCard->setExpirationDate("1226");
    $creditCard->setCardCode("123");
    $paymentOne = new AnetAPI\PaymentType();
    $paymentOne->setCreditCard($creditCard);

When switching to production, along with other changes, don’t forget to change the customer’s provided card details.

3. Setting up the order information

When a customer orders; it’s is either a collection of orders from different items or a single purchase. In any case, you would want to set an order description.

Authorize.net usually sends a payment receipt to the customer. The order description would be visible on the receipt.

    // Preparing the order data for the transaction
    $order = new AnetAPI\OrderType();
    $order->setDescription("New Item");

You can also set the customer invoice number to each transaction for your organizational accounting purpose.

4. Setting up the transaction information

As I said earlier, we will authorize the details and capture the payment. The process here creates a transaction object.

We have the order amount, order information, and card detail object ready. We then need to prepare the transaction request object.

    //create a transaction
    $transactionRequestType = new AnetAPI\TransactionRequestType();
    $transactionRequestType->setTransactionType( "authCaptureTransaction"); 
    $transactionRequestType->setAmount($amount);
    $transactionRequestType->setOrder($order);
    $transactionRequestType->setPayment($paymentOne);

5. Setting up the customer information

We have the merchant, card, order, and transaction information object ready. What we need to do know is to set up the customer information.

Generally, the card and customer information comes either from your web page (in case of guest checkout) or comes from your data server/session.

In my case, I’ve created a payment HTML page where we took the user’s information from the form attached on the page and once submitted, we will process the payment.

    //Preparing customer information object
    $cust = new AnetAPI\CustomerAddressType();
    $cust->setFirstName($_POST['fname']);
    $cust->setLastName($_POST['lname']);
    $cust->setAddress($_POST['address']);
    $cust->setCity($_POST['city']);
    $cust->setState($_POST['state']);
    $cust->setCountry($_POST['country']);
    $cust->setZip($_POST['zip']);
    $cust->setPhoneNumber($_POST['phone']);
    $cust->setEmail("Email-here");
    
    $transactionRequestType->setBillTo($cust);

We need to provide the customer information (the one paying for the order) to Authorize.net.

If in case you miss this, the payment processing will return an error saying BillTo information required. For more information consider reading Authorize.net’s API response code.

6. Making the payment request and processing

We now have everything that we need to capture for the payment. Merchant, order, card, and customer details. Let’s execute the payment processing code.

    $request = new AnetAPI\CreateTransactionRequest();
    $request->setMerchantAuthentication($merchantAuthentication);
    $request->setRefId( $refId);
    $request->setTransactionRequest( $transactionRequestType);

To execute the payment processing we need to prepare the payment request code. To do that we will create an object or CreateTransactionRequest type.

We will set the merchant and transaction related properties with the respective objects we created earlier.

    $controller = new AnetController\CreateTransactionController($request);
    $response = $controller->executeWithApiResponse( \net\authorize\api\constants\ANetEnvironment::SANDBOX);

The code above will create a CreateTransactionController type object. And we will use the executeWithApiResponse method to process the payment request.

The CreateTransactionController’s executeWithApiRespose method will execute the payment processing request. It sends all the data to Authorize.net server and brings the response it gets from the server.

You can perform the post-payment processing by analyzing the response. There would be three possible response you could receive. The null response, error response with error code & message, and finally “ok” if everything goes well.

    if ($response != null) {
            if ($response->getMessages()->getResultCode() == \SampleCode\Constants::RESPONSE_OK) {
                $tresponse = $response->getTransactionResponse();
    
                if ($tresponse != null && $tresponse->getMessages() != null) {
                    echo " Transaction Response code : " . $tresponse->getResponseCode() . "\n";
                    echo "Charge Credit Card AUTH CODE : " . $tresponse->getAuthCode() . "\n";
                    echo "Charge Credit Card TRANS ID : " . $tresponse->getTransId() . "\n";
                    echo " Code : " . $tresponse->getMessages()[0]->getCode() . "\n";
                    echo " Description : " . $tresponse->getMessages()[0]->getDescription() . "\n";
                } else {
                    echo "Transaction Failed \n";
                    if ($tresponse->getErrors() != null) {
                        echo " Error code : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
                        echo " Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
                    }
                }
            } else {
                echo "Transaction Failed \n";
                $tresponse = $response->getTransactionResponse();
                if ($tresponse != null && $tresponse->getErrors() != null) {
                    echo " Error code : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
                    echo " Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
                } else {
                    echo " Error code : " . $response->getMessages()->getMessage()[0]->getCode() . "\n";
                    echo " Error message : " . $response->getMessages()->getMessage()[0]->getText() . "\n";
                }
            }
        } else {
            echo "No response returned \n";
        }

The code above is fairly simple to understand. The root if condition if ($response != null) { … } is used to check if the response we get is null or not.

The nested if statements will check if the transaction has been successful or not. If not then an appropriate message will be displayed.

Customize this logic to match your post payment processing requirements. On successful transactions, you may want to store something into the database; and for failed transactions, you may want the user to retry the transaction.

Switching from sandbox to production

The code above works fine on sandbox mode—you developed and tested the code and everything looks fine. And now you may want to go to production mode.

Here are some of the things you may want to consider changing.

  • Login_id and Transaction_id from merchant object.
  • Credit card details object values should come from your UI.
  • Order object data to come from your server.
  • Customer information object to be prepared from your server with actual data.
  • ExecuteWithApiResponse method should use PRODUCTION instead of SANDBOX.
  • The response object should be used to make proper post payment processing.

Conclusion

As you can see, attaching Authorize.net payment gateway in PHP is an easy task. All you need is the official PHP SDK and the code we covered above. You can integrate it in the framework like Laravel, Codeigniter, and others.

You can check out the solution file on this Github link.


Author’s bio

Darshan is the founder of AlphansoTech a custom WordPress development company. Codeigniter 4 and WordPress are his latest interest.You may find him writing detailed web technology related articles or can connect with him on LinkedIn and Twitter.

Discover and read more posts from Codementor Team
get started
post commentsBe the first to share your opinion
Omar Kishta
a year ago

I have many different ideas that will attract users, but they are related to the sale of virtual characters. I contacted different programmers to create my idea, but they can put together a program but with payment gateways they find it difficult to execute. Merlin: - I followed your link, looked, I think that I will contact them, I hope that they can help me.

Quinn Huntsman
6 years ago

Hi, I was wondering if these instructions could be applied to integrating Authorize.net payment gateway into a Joomla site, and if so, how any of this might become different in that case? I have a site where the user selects a trash service pick up, fills out a form, clicks submit and needs to be redirected to the authorize.net payment gateway, do you know if this is easily doable with something like this?

Ralph Dosser
7 years ago

Thanks for the article.

While there is a method to set the email address in the CustomerAddressType object, it doesn’t actually work. You must instead create a separate CustomerDataType object and then add that to your TransactionRequestType object.

        $customerData = new AnetAPI\CustomerDataType();
        $customerData->setEmail('foo@bar.com');

        $transactionRequestType->setCustomer($customerData);
Show more replies