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.
    authorize-net-create-sandbox-account-api-keys-login-id-transaction-key-codexworld

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.

authorize.net_integration_php/
├── 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` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `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,
 PRIMARY KEY (`id`)
) 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.
<?php 
// Product Details
$itemName "Demo Product"
$itemNumber "PN12345"
$itemPrice 25
$currency "USD"

// Authorize.Net API configuration 
define('ANET_API_LOGIN_ID''YOUR_API_LOGIN_ID'); 
define('ANET_TRANSACTION_KEY''YOUR_TRANSACTION_KEY'); 
$ANET_ENV 'SANDBOX'// or PRODUCTION
 
// Database configuration 
define('DB_HOST''MySQL_Database_Host'); 
define('DB_USERNAME''MySQL_Database_Username'); 
define('DB_PASSWORD''MySQL_Database_Password'); 
define('DB_NAME''MySQL_Database_Name'); 

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.

<?php  
// Connect with the database 
$db = new mysqli(DB_HOSTDB_USERNAMEDB_PASSWORDDB_NAME); 
 
// Display error if failed to connect 
if ($db->connect_errno) { 
    
printf("Connect failed: %s\n"$db->connect_error); 
    exit(); 
}

Payment Checkout Form (index.php)

At first, include the configuration file.

<?php 
// 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>
    <div class="panel-body">
		
        <!-- Payment form -->
        <form action="payment.php" method="POST">
            <div class="form-group">
                <label>NAME</label>
                <input type="text" name="name" placeholder="Enter name" required="" autofocus="">
            </div>
            <div class="form-group">
                <label>EMAIL</label>
                <input type="email" name="email" placeholder="Enter email" required="">
            </div>
            <div class="form-group">
                <label>CARD NUMBER</label>
                <input type="text" name="card_number" placeholder="1234 1234 1234 1234" autocomplete="off" required="">
            </div>
            <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>
                        <div class="col-2">
                            <input type="text" name="card_exp_year" placeholder="YYYY" required="">
                        </div>
                    </div>
                </div>
                <div class="right">
                    <div class="form-group">
                        <label>CVC CODE</label>
                        <input type="text" name="card_cvc" placeholder="CVC" autocomplete="off" required="">
                    </div>
                </div>
            </div>
            <button type="submit" class="btn btn-success">Submit Payment</button>
        </form>
    </div>
</div>

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.
<?php 
// Include Authorize.Net PHP sdk
require 'authorize_net_sdk_php/autoload.php'
use 
net\authorize\api\contract\v1 as AnetAPI;
use 
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();   
    
$merchantAuthentication->setName(ANET_API_LOGIN_ID);   
    
$merchantAuthentication->setTransactionKey(ANET_TRANSACTION_KEY);   
    
    
// Create the payment data for a credit card
    
$creditCard = new AnetAPI\CreditCardType();
    
$creditCard->setCardNumber($card_number);
    
$creditCard->setExpirationDate($card_exp_year_month);
    
$creditCard->setCardCode($card_cvc);
    
    
// Add the payment data to a paymentType object
    
$paymentOne = new AnetAPI\PaymentType();
    
$paymentOne->setCreditCard($creditCard);
    
    
// Create order information
    
$order = new AnetAPI\OrderType();
    
$order->setDescription($itemName);
    
    
// Set the customer's identifying information
    
$customerData = new AnetAPI\CustomerDataType();
    
$customerData->setType("individual");
    
$customerData->setEmail($email);
    
    
// Create a transaction
    
$transactionRequestType = new AnetAPI\TransactionRequestType();
    
$transactionRequestType->setTransactionType("authCaptureTransaction");   
    
$transactionRequestType->setAmount($itemPrice);
    
$transactionRequestType->setOrder($order);
    
$transactionRequestType->setPayment($paymentOne);
    
$transactionRequestType->setCustomer($customerData);
    
$request = new AnetAPI\CreateTransactionRequest();
    
$request->setMerchantAuthentication($merchantAuthentication);
    
$request->setRefId($refID);
    
$request->setTransactionRequest($transactionRequestType);
    
$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";
    }
}else{
    
$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.
      $ANET_ENV 'PRODUCTION';

Stripe Checkout Integration in PHP

Conclusion

Authorize.Net API is the easiest way to integrate payment gateway for credit card payment. Our sample code helps you to integrate the credit card payment process in your website using Authorize.Net and PHP. You can allow the buyer to make payment with their credit card and store the transaction data in the database.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

4 Comments

  1. Ankit Prasad Said...
  2. Joe Said...
  3. Dilip Gautam Said...
  4. Darya Said...

Leave a reply

keyboard_double_arrow_up