Authorize.Net Payment Gateway Integration using PHP

by Vincy. Last modified on September 27th, 2022.

Authorize.Net payment gateway is one of the widely used payment enabling mechanisms in many eCommerce software. payment gateway integration supports the standard Visa, MasterCard, Discover, Apple Pay, Google Pay, PayPal and all popular similar services.

In this tutorial, we are going to see how to use the Authorize.Net Payment Gateway API to make Payment Transactions to charge a credit card. For charging a credit card using Authorize.Net, I have used the sample Hello Word program that is available in the Authorize.Net API developer documentation.

Authorize.Net provides API services with features like payment transactions, webhooks and more for building a payment solution in our application. In previous articles, we have seen various payment gateway integration using PayPal, Stripe and Sage Pay. If you are searching for those codes, the linked tutorials will be useful.

Stripe payment gateway integration is a similar service provider in comparison to and it is becoming hugely popular now. Sage Pay payment gateway integration is a similar popular service in UK and Europe.

This example is for making test transactions by creating a sandbox account in Authorize.Net. The card information will be got from the user by using a HTML form. While submitting this form, the form data are validated and sent to the PHP. Previously, we have created a credit card validator in PHP.


In PHP code, the API returns the response in JSON format. By parsing the response the user acknowledgment message will be shown with the transaction id.

Steps to Integrate Authorize.Net Payment Gateway

  1. Create Authorize.Net account to get API Login id and key.
  2. Import PHP SDK to access Authorize.Net API.
  3. Create a payment form to get credit card information from the user.
  4. Configure API credentials and request payment process.
  5. Handle API response and store the data in the database.

Create Authorize.Net account to get API Credentials

Signup to the Authorize.Net sandbox environment to get the API credentials to process test payment transactions. Sandbox is used for testing the payment gateway integration. The following screenshot shows the Authorize.Net page with the generated API login id and key.

Import PHP SDK to access Authorize.Net API

We need the PHP SDK for accessing the Authorize.Net API to process payments. This SDK can be imported by using the composer. Make sure that the composer is installed in your machine and create the composer.json file and add the below script into it.

  "require": {
    "php": ">=5.6",
    "ext-curl": "*",
    "authorizenet/authorizenet": ">=1.9.3"

Then, run the following command.

composer update

Create Payment Form to Get Card Information payment gateway integration is better in many a situation as it provides flexible feature using which we can reduce the friction in the payment flow. We can get the user card information within our website instead of forwarding them to the payment processing provider’s site.

This code is used to create the HTML payment form to get card information. Also, it contains the JavaScript function to validate form data on submit.

<link href="style.css" rel="stylesheet" type="text/css"/ >
<title> Payment Gateway Integration using PHP</title>
    <?php if(!empty($message)) { ?>
    <div id="response-message" class="<?php echo $reponseType; ?>"><?php echo $message; ?></div>
    <?php  } ?>
    <div id="error-message"></div>
            <form id="frmPayment" action=""
                        onSubmit="return cardValidation();">
                <div class="field-row">
                    <label>Card Number</label> <span
                        id="card-number-info" class="info"></span><br> <input
                        type="text" id="card-number" name="card-number"
                <div class="field-row">
                    <div class="contact-row column-right">
                        <label>Expiry Month / Year</label> <span
                            id="userEmail-info" class="info"></span><br>
                        <select name="month" id="month"
                            <option value="09">09</option>
                            <option value="10">10</option>
                            <option value="11">11</option>
                            <option value="12">12</option>
                        </select> <select name="year" id="year"
                            <option value="2018">2018</option>
                            <option value="2019">2019</option>
                            <option value="2020">2020</option>
                            <option value="2021">2021</option>
                            <option value="2022">2022</option>
                            <option value="2023">2023</option>
                            <option value="2024">2024</option>
                            <option value="2025">2025</option>
                            <option value="2026">2026</option>
                            <option value="2027">2027</option>
                            <option value="2028">2028</option>
                            <option value="2029">2029</option>
                            <option value="2030">2030</option>
                    <input type="submit" name="pay_now" value="Submit"
                        id="submit-btn" class="btnAction">

                    <div id="loader">
                        <img alt="loader" src="LoaderIcon.gif">
                <input type='hidden' name='amount' value='151.51'> 
    <div class="test-data">
        <h3>Test Card Information</h3>
        <p>Use these test card numbers with valid expiration month
            / year for testing.</p>
        <table class="tutorial-table" cellspacing="0" cellpadding="0" width="100%">
                <th>CARD NUMBER</th>
                <td>American Express</td>
                <td>Diners Club/ Carte Blanche</td>
    <script src="vendor/jquery/jquery-3.2.1.min.js"
function cardValidation () {
    var valid = true;
    var cardNumber = $('#card-number').val();
    var month = $('#month').val();
    var year = $('#year').val();


    if (cardNumber.trim() == "") {
    	   valid = false;

    if (month.trim() == "") {
    	    valid = false;
    if (year.trim() == "") {
        valid = false;

    if(valid == false) {
        $("#error-message").html("All Fields are required").show();

    return valid;

Configure API Credentials and Request Payment Process

The API auth credentials are defined as PHP constants in a configuration file. A PHP class named AuthorizeNetPayment is used to handle the functions to set the merchant authentication, credit card type, transaction request type and more setup that are required to process payment via Authorize.Net API.

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

class AuthorizeNetPayment

    private $APILoginId;
    private $APIKey;
    private $refId;
    private $merchantAuthentication;
    public $responseText;

    public function __construct()
        require_once "config.php";
        $this->APILoginId = API_LOGIN_ID;
        $this->APIKey = TRANSACTION_KEY;
        $this->refId = 'ref' . time();
        $this->merchantAuthentication = $this->setMerchantAuthentication();
        $this->responseText = array("1"=>"Approved", "2"=>"Declined", "3"=>"Error", "4"=>"Held for Review");

    public function setMerchantAuthentication()
        $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
        return $merchantAuthentication;
    public function setCreditCard($cardDetails)
        $creditCard = new AnetAPI\CreditCardType();
        $creditCard->setExpirationDate( $cardDetails["year"] . "-" . $cardDetails["month"]);
        $paymentType = new AnetAPI\PaymentType();
        return $paymentType;
    public function setTransactionRequestType($paymentType, $amount)
        $transactionRequestType = new AnetAPI\TransactionRequestType();
        return $transactionRequestType;

    public function chargeCreditCard($cardDetails)
        $paymentType = $this->setCreditCard($_POST);
        $transactionRequestType = $this->setTransactionRequestType($paymentType, $_POST["amount"]);
        $request = new AnetAPI\CreateTransactionRequest();
        $request->setRefId( $this->refId);
        $controller = new AnetController\CreateTransactionController($request);
        $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
        return $response;
} Payment Response and Update Database

In this PHP code, the AuthorizeNetPayment class instance is created and the charge credit card request is created. As a result, the function will return the payment response in JSON format. This JSON object is parsed and the payment data like responseCode, authCode, responseText, tranId and more are stored in the database.


require_once "config.php";

$type = "";
$message = "";
if (!empty($_POST["pay_now"])) {
    require_once 'AuthorizeNetPayment.php';
    $authorizeNetPayment = new AuthorizeNetPayment();
    $response = $authorizeNetPayment->chargeCreditCard($_POST);
    if ($response != null)
        $tresponse = $response->getTransactionResponse();
        if (($tresponse != null) && ($tresponse->getResponseCode()=="1"))
            $authCode = $tresponse->getAuthCode();
            $paymentResponse = $tresponse->getMessages()[0]->getDescription();
            $reponseType = "success";
            $message = "This transaction has been approved. <br/> Charge Credit Card AUTH CODE : " . $tresponse->getAuthCode() .  " <br/>Charge Credit Card TRANS ID  : " . $tresponse->getTransId() . "\n";
            $authCode = "";
            $paymentResponse = $tresponse->getErrors()[0]->getErrorText();
            $reponseType = "error";
            $message = "Charge Credit Card ERROR :  Invalid response\n";
        $transactionId = $tresponse->getTransId();
        $responseCode = $tresponse->getResponseCode();
        $paymentStatus = $authorizeNetPayment->responseText[$tresponse->getResponseCode()];
        require_once "DBController.php";
        $dbController = new DBController();
        $param_type = 'sssdss';
        $param_value_array = array(
        $query = "INSERT INTO tbl_authorizenet_payment (transaction_id, auth_code, response_code, amount, payment_status, payment_response) values (?, ?, ?, ?, ?, ?)";
        $id = $dbController->insert($query, $param_type, $param_value_array);
        $reponseType = "error";
        $message= "Charge Credit Card Null response returned";

Switch Authorize.Net Payment Mode from Sandbox to Live

After testing the payment flow in the Authorize.Net sandbox environment, it’s time to go live. It is very simple from switching the payment mode from sandbox to live. The below list of changes has to be done to process Authorize.Net live payment.

  • Create merchant account and get the API Login id and the Transaction key to use in live mode.
  • Use the real card information.
  • Change the API endpoint from SANDBOX to PRODUCTION.

Authorize.Net Payment Form Output

Authorize.Net payment gateway integration is one of the easiest to achieve. The following screenshot shows the payment form to enter the card information to process payment via Authorize.Net API. In this output, the success response is shown with the transaction id. In this HTML view, the test card details are shown.



Comments to “Authorize.Net Payment Gateway Integration using PHP”

  • Chukwuemekalum Chiemelu says:

    Hello nice one Vincy
    Quick question so I can use this and create a donation platform or e-commerce and then I would get credited for any transaction

    • Vincy says:

      Hi Chiemelu,

      Yes definitely you can use this payment gateway integration script and create a donation platform.

Leave a Reply

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

↑ Back to Top

Share this page