Authorize.Net Payment Gateway Integration in PHP

The payment gateway is the most important part of the web application to accept payment online. There are various payment gateway is available to integrate the credit card payment system on the website. Authorize.Net is one of the popular payment gateway to accept payment online with a credit card. Authorize.Net payment API allows accepting credit card payment online.

The Authorize.Net payment gateway provides a simple and powerful solution to integrate checkout system with smooth payment experience online. You can allow the buyer to make payment with their credit card on your website using Authorize.Net payment gateway. Like the Stripe payment gateway, you can easily integrate the Authorize.Net payment API in the PHP-based web application. In this tutorial, we will show you how to integrate Authorize.Net payment gateway in PHP for collecting payment through credit card on the website.

In the example script, we will implement the following functionality to demonstrate the Authorize.Net payment gateway integration process in PHP.

  • Create an HTML form to collect credit card information.
  • Submit the form with credit card details.
  • Verify the card info and process transaction with Authorize.Net PHP SDK.
  • Insert transaction data in the database and display the payment status.

Set Up Authorize.Net Sandbox Account

Before making Authorize.Net payment gateway live on the Production environment, the integration process needs to be tested. To test the credit card payment process, you need to create a Sandbox account and generate test API keys on Authorize.Net Merchant Account.

  • Create Authorize.Net sandbox account from here.
  • After the account creation, the Sandbox API credentials (API Login ID, Transaction Key, and Key) will be generated.


Collect the API Login ID and Transaction Key to later use in the script.

Before getting started to implement Authorize.Net payment gateway in PHP, take a look at the files structure.

├── config.php
├── dbConnect.php
├── index.php
├── payment.php
├── authorize_net_sdk_php/
└── css/
    └── style.css

Create Database Table

To store the transaction details, a table needs to be created in the database. The following SQL creates an orders table in the MySQL database.

CREATE TABLE `orders` (
 `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `item_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `item_number` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `item_price` float(10,2) NOT NULL,
 `item_price_currency` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `card_number` bigint(20) NOT NULL,
 `card_exp_month` varchar(2) COLLATE utf8_unicode_ci NOT NULL,
 `card_exp_year` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
 `paid_amount` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
 `txn_id` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `payment_status` varchar(25) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Ok | Error',
 `payment_response` enum('1','2','3','4') COLLATE utf8_unicode_ci NOT NULL COMMENT '1=Approved | 2=Declined | 3=Error | 4=Held for Review',
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Authorize.Net API and Database Configuration (config.php)

In the config.php file, constant variables of the Authorize.Net API and database settings are defined.

Product Information:

  • $itemName – Name of the product.
  • $itemNumber – Product number.
  • $itemPrice – Product price.
  • $currency – Currency code.

Authorize.Net API Constants:

  • ANET_API_LOGIN_ID – Specify the API login ID.
  • ANET_TRANSACTION_KEY – Specify the API Transaction key.

Database Constants:

  • DB_HOST – Specify the database host.
  • DB_USERNAME – Specify the database username.
  • DB_PASSWORD – Specify the database password.
  • DB_NAME – Specify the database name.
// Product Details
$itemName "Demo Product"
$itemNumber "PN12345"
$itemPrice 25
$currency "USD"

// Authorize.Net API configuration 
// Database configuration 

Note that: Authorize.Net API Login ID and Transaction Key will be found in the API Credentials & Keys section of your Authorize.Net merchant account.

Database Connection (dbConnect.php)

The dbConnect.php file helps to connect the database using PHP and MySQL.

// Connect with the database 
// Display error if failed to connect 
if ($db->connect_errno) { 
printf("Connect failed: %s\n"$db->connect_error); 

Payment Checkout Form (index.php)

At first, include the configuration file.

// Include configuration file 
require_once 'config.php';

Create an HTML form to collect the user information (name and email) and card details (Card Number, Expiration Date, and CVC No.) from the buyer. After the form submission, the provided data is submitted to the server-side script (payment.php) for processing the credit card payment.

<div class="panel">
    <div class="panel-heading">
        <h3 class="panel-title">Charge <?php echo '$'.$itemPrice?> with Authorize.Net</h3>
        <!-- Product Info -->
        <p><b>Item Name:</b> <?php echo $itemName?></p>
        <p><b>Price:</b> <?php echo '$'.$itemPrice.' '.$currency?></p>
    <div class="panel-body">
        <!-- Payment form -->
        <form action="payment.php" method="POST">
            <div class="form-group">
                <input type="text" name="name" placeholder="Enter name" required="" autofocus="">
            <div class="form-group">
                <input type="email" name="email" placeholder="Enter email" required="">
            <div class="form-group">
                <label>CARD NUMBER</label>
                <input type="text" name="card_number" placeholder="1234 1234 1234 1234" autocomplete="off" required="">
            <div class="row">
                <div class="left">
                    <div class="form-group">
                        <label>EXPIRY DATE</label>
                        <div class="col-1">
                            <input type="text" name="card_exp_month" placeholder="MM" required="">
                        <div class="col-2">
                            <input type="text" name="card_exp_year" placeholder="YYYY" required="">
                <div class="right">
                    <div class="form-group">
                        <label>CVC CODE</label>
                        <input type="text" name="card_cvc" placeholder="CVC" autocomplete="off" required="">
            <button type="submit" class="btn btn-success">Submit Payment</button>

Authorize.Net PHP SDK

Authorize.Net PHP SDK helps to integrate Authorize.Net payment gateway in the web application. The Authorize.Net PHP library is used to create a charge and process the card payment. All the required library files are included in our source code, you don’t need to download it separately.

Charge Credit Card and Process Payment (payment.php)

In this file, the submitted card details are validated and the charge is processed using Authorize.Net API library & PHP.

  • Include the autoloader of the Authorize.Net PHP SDK.
  • Retrieve user and card information from the payment form fields using PHP $_POST method.
  • Create a MerchantAuthenticationType object and set API keys.
  • Create a CreditCardType object and set credit card details.
  • Add the payment data to a PaymentType object.
  • Create OrderType object and set order info.
  • Create CustomerDataType object and set customer info.
  • Create a transaction with TransactionRequestType object.
  • Charge the credit card and validate the transaction.
  • If the API request was successfull, the order nad transaction details are inserted in the database.
  • Based on the API request, transaction status is shown to the buyer.
// Include Authorize.Net PHP sdk
require 'authorize_net_sdk_php/autoload.php'
net\authorize\api\contract\v1 as AnetAPI;
net\authorize\api\controller as AnetController;

// Include configuration file 
require_once 'config.php';

$paymentID $statusMsg '';
$ordStatus 'error';
$responseArr = array(=> 'Approved'=> 'Declined'=> 'Error'=> 'Held for Review');

// Check whether card information is not empty
if(!empty($_POST['card_number']) && !empty($_POST['card_exp_month']) && !empty($_POST['card_exp_year']) && !empty($_POST['card_cvc'])){
// Retrieve card and user info from the submitted form data
$name $_POST['name'];
$email $_POST['email'];
$card_number preg_replace('/\s+/'''$_POST['card_number']);
$card_exp_month $_POST['card_exp_month'];
$card_exp_year $_POST['card_exp_year'];
$card_exp_year_month $card_exp_year.'-'.$card_exp_month;
$card_cvc $_POST['card_cvc'];
// Set the transaction's reference ID
$refID 'REF'.time();
// Create a merchantAuthenticationType object with authentication details
    // retrieved from the config file
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();   
// Create the payment data for a credit card
$creditCard = new AnetAPI\CreditCardType();
// Add the payment data to a paymentType object
$paymentOne = new AnetAPI\PaymentType();
// Create order information
$order = new AnetAPI\OrderType();
// Set the customer's identifying information
$customerData = new AnetAPI\CustomerDataType();
// Create a transaction
$transactionRequestType = new AnetAPI\TransactionRequestType();
$request = new AnetAPI\CreateTransactionRequest();
$controller = new AnetController\CreateTransactionController($request);
$response $controller->executeWithApiResponse(constant("\\net\authorize\api\constants\ANetEnvironment::$ANET_ENV"));
    if (
$response != null) {
// Check to see if the API request was successfully received and acted upon
if ($response->getMessages()->getResultCode() == "Ok") {
// Since the API request was successful, look for a transaction response
            // and parse it to display the results of authorizing the card
$tresponse $response->getTransactionResponse();

            if (
$tresponse != null && $tresponse->getMessages() != null) {
// Transaction info
$transaction_id $tresponse->getTransId();
$payment_status $response->getMessages()->getResultCode();
$payment_response $tresponse->getResponseCode();
$auth_code $tresponse->getAuthCode();
$message_code $tresponse->getMessages()[0]->getCode();
$message_desc $tresponse->getMessages()[0]->getDescription();
// Include database connection file 
include_once 'dbConnect.php';
// Insert tansaction data into the database
$sql "INSERT INTO orders(name,email,item_name,item_number,item_price,item_price_currency,card_number,card_exp_month,card_exp_year,paid_amount,txn_id,payment_status,payment_response,created,modified) VALUES('".$name."','".$email."','".$itemName."','".$itemNumber."','".$itemPrice."','".$currency."','".$card_number."','".$card_exp_month."','".$card_exp_year."','".$itemPrice."','".$transaction_id."','".$payment_status."','".$payment_response."',NOW(),NOW())";
$insert $db->query($sql);
$paymentID $db->insert_id;
$ordStatus 'success';
$statusMsg 'Your Payment has been Successful!';
            } else {
$error "Transaction Failed! \n";
                if (
$tresponse->getErrors() != null) {
$error .= " Error Code  : " $tresponse->getErrors()[0]->getErrorCode() . "<br/>";
$error .= " Error Message : " $tresponse->getErrors()[0]->getErrorText() . "<br/>";
$statusMsg $error;
// Or, print errors if the API request wasn't successful
} else {
$error "Transaction Failed! \n";
$tresponse $response->getTransactionResponse();
            if (
$tresponse != null && $tresponse->getErrors() != null) {
$error .= " Error Code  : " $tresponse->getErrors()[0]->getErrorCode() . "<br/>";
$error .= " Error Message : " $tresponse->getErrors()[0]->getErrorText() . "<br/>";
            } else {
$error .= " Error Code  : " $response->getMessages()->getMessage()[0]->getCode() . "<br/>";
$error .= " Error Message : " $response->getMessages()->getMessage()[0]->getText() . "<br/>";
$statusMsg $error;
    } else {
$statusMsg =  "Transaction Failed! No response returned";
$statusMsg "Error on form submission.";
?> <div class="status"> <?php if(!empty($paymentID)){ ?> <h1 class="<?php echo $ordStatus?>"><?php echo $statusMsg?></h1> <h4>Payment Information</h4> <p><b>Reference Number:</b> <?php echo $paymentID?></p> <p><b>Transaction ID:</b> <?php echo $transaction_id?></p> <p><b>Status:</b> <?php echo $responseArr[$payment_response]; ?></p> <h4>Product Information</h4> <p><b>Name:</b> <?php echo $itemName?></p> <p><b>Price:</b> <?php echo $itemPrice.' '.$currency?></p> <?php }else{ ?> <h1 class="error">Your Payment has Failed</h1> <p class="error"><?php echo $statusMsg?></p> <?php ?> </div>

Test Card Details

To test the payment process on the Sandbox environment, use the following card number with valid future expiration date and any random CVV number (3 digits).

  • 4111111111111111 – Visa

Make Authorize.Net Payment Gateway Live

Once the integration is completed and the payment process is working properly, follow the below steps to make Authorize.Net payment gateway live on the Production server.

  • Login to your Authorize.Net merchant account.
  • Click the Account link from the top navigation menu bar.
  • Click the Settings link in the left-side menu panel.
  • Go to the Security Settings » General Security Settings section and click the API Credentials & Keys.
  • In the API Credentials & Keys page,
    • You will get the API Login ID.
    • For Transaction Key, select New Transaction Key and Submit.
  • In the config.php file,
    • Replace the Sandbox API keys by the Live API credentials (Login ID and Transaction Key).
    • Set environment to PRODUCTION in $ANET_ENV.

Related Articles

Comments 0