Authorize.Net Payment Gateway Integration using PHP

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 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.

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, 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.

We need the PHP SDK for accessing the Authorize.Net API to process payments.

Dowonload libary file click here

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 Personal Information, billing address and card information. Also, it contains the JavaScript function to validate form data on submit.

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" name="cust_form_">
  <h3>Personal Information</h3>
  <label>First Name<br/>
  <input type="text" placeholder="First Name" name="fname" id="fname" value="">
  Last Name<br/>
  <input type="text" placeholder="Last Name" name="lname" id="lname" value="">
  <input type="text" placeholder="Email Address" name="email" id="email" value="">
  <input type="text" placeholder="Phone Number" name="phone" id="phone" value="">
  <label>Company Name<br/>
  <input type="text" placeholder="Company Name (Optional)" name="company" id="company">
  <h3>Billing Address</h3>
  <input type="text" placeholder="Postcode"  name="zipcode" id="zipcode"  value="">
  <input type="text" placeholder="Street Address" name="address" id="address" value="">
  <input type="text" placeholder="City" name="city" id="city" value="">
  <input type="text"  placeholder="State" name="state" id="state" value="">
  <select class="form-control" name="country" id="country">
    <option value="US">Country</option>
    <option value="US" selected="selected">US</option>
    <option value="UK">UK</option>
    <option value="CAD">CAD</option>
  <h3>Payment Details</h3>
  <label>Product description<br/>
  <input type="text" placeholder="Plan description" name="description" id="description" value="">
  <label>Card Number <br/>
  <input type="text" class="form-control" placeholder="Card Number" name="cardno" id="cardno" value="">
  <label>Name on Card<br/>
  <input type="text" class="form-control" placeholder="Name On Card" name="name_on_card" id="name_on_card" value="">
  <label>Expiry Month / Year<br>
  <select name="month" id="month" class="demoSelectBox">
    <option value="01">01</option>
    <option value="02">02</option>
    <option value="03">03</option>
    <option value="04">04</option>
    <option value="05">05</option>
    <option value="06">06</option>
    <option value="07">07</option>
    <option value="08">08</option>
    <option value="09">09</option>
    <option value="10">10</option>
    <option value="11">11</option>
    <option value="12">12</option>
  <select name="year" id="year" class="demoSelectBox">
    <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>
  <input type="text" placeholder="CVV" name="cvv" id="cvv" value="">
  <input type="text" placeholder="Amount" name="amount" id="amount" value="10.00" readonly="readonly">
  <button  id="btnCompleteOrder" type="submit" name="register_customer">Pay Now </button>


Configure API Credentials and Request Payment Process

The API auth credentials are defined as PHP constants in a configuration file (constants/SampleCodeConstants.php). A PHP function named chargeCreditCard 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';
  require_once 'constants/SampleCodeConstants.php';
  use net\authorize\api\contract\v1 as AnetAPI;
  use net\authorize\api\controller as AnetController;
  define("AUTHORIZENET_LOG_FILE", "phplog");
function chargeCreditCard($amount, $cardno, $exp, $cvv, $invoice, $description, $fname, $lname, $company, $address, $city, $state, $zip, $country,$email)
    /* Create a merchantAuthenticationType object with authentication details
       retrieved from the constants file */
    $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
    // Set the transaction's refId
    $refId = 'ref' . time();
    // 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 Bill To address
    $customerAddress = new AnetAPI\CustomerAddressType();
    // Set the customer's identifying information
    $customerData = new AnetAPI\CustomerDataType();
    // Add values for transaction settings
    $duplicateWindowSetting = new AnetAPI\SettingType();
    // Add some merchant defined fields. These fields won't be stored with the transaction,
    // but will be echoed back in the response.
    $merchantDefinedField1 = new AnetAPI\UserFieldType();
    $merchantDefinedField2 = new AnetAPI\UserFieldType();
    // Create a TransactionRequestType object and add the previous objects to it
    $transactionRequestType = new AnetAPI\TransactionRequestType();
    // Assemble the complete transaction request
    $request = new AnetAPI\CreateTransactionRequest();
    // Create the controller and get the response
    $controller = new AnetController\CreateTransactionController($request);
    $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);   //PRODUCTION   SANDBOX
    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) {
               echo "<p style='font-family:verdana; font-size:12px; color:#009933;'>Successfully created transaction with Transaction ID: " . $tresponse->getTransId() . "\n";
          echo "<br/>Transaction Response Code: " . $tresponse->getResponseCode() . "\n";
                echo "<br/> Message Code: " . $tresponse->getMessages()[0]->getCode() . "\n";
                echo "<br/> Auth Code: " . $tresponse->getAuthCode() . "\n";
                echo "<br/> Description: " . $tresponse->getMessages()[0]->getDescription() . "\n</p>";
            } else {
                echo "<p class='error'>Transaction Failed \n</p>";
                if ($tresponse->getErrors() != null) {
                    echo "<p class='error'> Error Code  : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
                    echo "<br/> Error Message : " . $tresponse->getErrors()[0]->getErrorText() . "\n</p>";
            // Or, print errors if the API request wasn't successful
        } else {
            echo "<p class='error'>Transaction Failed \n</p>";
            $tresponse = $response->getTransactionResponse();
            if ($tresponse != null && $tresponse->getErrors() != null) {
                echo "<p class='error'> Error Code  : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
                echo " <br/>Error Message : " . $tresponse->getErrors()[0]->getErrorText() . "\n</p>";
      } else {
                echo "<p class='error'> Error Code  : " . $response->getMessages()->getMessage()[0]->getCode() . "\n";
                echo "<br/> Error Message : " . $response->getMessages()->getMessage()[0]->getText() . "\n</p>";
    } else {
        echo  "<p class='error'>No response returned \n</p>";
    return $response;

if (!defined('DONT_RUN_SAMPLES')) {
$amount = '2.00';
$card = '4111111111111111';
$exp = '2021-10';
$cvv ='123';
$invoice = 'Inv-001';
$description ='Payment description';
$fname ='john';
$lname ='deo';
$email ='';
$company ='abc';
$address ='New York';
$city ='New York';
$state ='NY';
$country ='USA';
chargeCreditCard($amount, $card, $exp, $cvv, $invoice, $description, $fname, $lname, $company, $address, $city, $state, $zipcode, $country,$email);



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.

Please follow and like us:

Add a Comment

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