Skip to Content
PHPCODE
Authorize net payment gateway Integration in PHP
php code / September 18, 2021

The payment gateway is the most crucial component of a web application that accepts online payments. There are a number of payment gateways that may be used to connect a credit card payment system into a website. Authorize.Net is a popular payment gateway for accepting credit card payments online. The Authorize.Net payment API allows you to take credit card payments over the internet.

The Authorize.Net payment gateway is a simple and effective approach to link a checkout system with a secure online payment experience. You can use the Authorize.Net payment gateway to allow customers to pay with their credit cards on your website. The Authorize.Net payment API, like the Stripe payment gateway, is simple to incorporate into a PHP-based web application. In this tutorial, we’ll show you how to use the Authorize.Net payment gateway in PHP to accept credit card payments on your website.

The following functionality will be included in the example script to demonstrate the Authorize.Net payment gateway integration process in PHP.

To gather credit card information, create an HTML form.
Fill out the form and include your payment card information.
Using the Authorize.Net PHP SDK, verify the card information and complete the transaction.
Display the payment status and insert transaction data into the database.

Create a sandbox account with Authorize.Net.
The integration process must be tested before making the Authorize.Net payment gateway active in the Production environment. Create a Sandbox account and generate test API keys on Authorize.Net Merchant Account to test the credit card payment procedure.

From this page, you may create an Authorize.Net sandbox account.
The Sandbox API credentials (API Login ID, Transaction Key, and Key) will be produced after the account is created.

To utilise later in the script, collect the API Login ID and Transaction Key.

Examine the file structure before beginning to implement the Authorize.Net payment gateway in PHP.

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

Make a database table.
A table in the database must be built to record the transaction details. In the MySQL database, the following SQL creates an orders table.

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;

Configuration of the Authorize.Net API and the Database (config.php)
The Authorize.Net API constant variables and database settings are defined in the config.php file.

Information on the product:

$itemName is the product’s name.
$itemNumber – Product number.
$itemPrice – Product price.
Currency code is $currency.
Constants in the Authorize.Net API:

Specify the API login ID with ANET API LOGIN ID.
ANET TRANSACTION KEY – The API Transaction key is specified here.
Constants in the Database:

DB HOST — This parameter specifies the database host.
DB USERNAME – This is the username for the database.
DB PASSWORD – This field is used to specify the database password.

DB NAME – Name of the database.

<?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');

Connection to the database (dbConnect.php)
The dbConnect.php file allows PHP and MySQL to connect to the database.

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

Checkout Form for Payment (index.php)
Include the configuration file first.

<?php 
// Include configuration file 
require_once 'config.php'; 
?>

Create an HTML form to collect the buyer’s contact information (name and email) as well as payment card information (card number, expiration date, and CVC number). Following the submission of the form, the provided data is sent to the server-side script (payment.php) for credit card payment processing.

<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. To make a charge and handle a card payment, the Authorize.Net PHP library is needed. You don’t need to download any of the essential library files because they’re all included in our source code.

Process Payment using a Credit Card (payment.php)
The submitted card data are confirmed in this file, and the charge is executed with the Authorize.Net API library and PHP.

Include the Authorize.Net PHP SDK’s autoloader.

Using the PHP $_POST method, retrieve user and card information from the payment form fields.

Set API keys and create a MerchantAuthenticationType object.

Set credit card details in a CreditCardType object.

Fill in the payment information in a PaymentType object.

Create an OrderType object and fill in the order details.

Create a CustomerDataType object and populate it with customer information.

With the TransactionRequestType object, you can create a transaction.
Validate the transaction and charge the credit card.
The order and transaction details are inserted into the database if the API request was successful.
The buyer is shown the transaction status based on the API request.

<?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(1 => 'Approved', 2 => 'Declined', 3 => 'Error', 4 => '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>

Details on the Test Card
Use the following card number with a valid future expiration date and any random CVV number to test the payment procedure in the Sandbox environment (3 digits).

Activate the Authorize.Net Payment Gateway

Follow the steps below to make the Authorize.Net payment gateway active on the Production server once the integration is complete and the payment process is running properly.

Access your Authorize.Net merchant account by logging in.
From the top navigation menu bar, select Account.
In the left-hand menu panel, click the Settings link.
Click API Credentials & Keys in the Security Settings > General Security Settings section.
On the Credentials & Keys page for the API,

The API Login ID will be provided to you.
Select New Transaction Key and Submit for Transaction Key.
Replace the Sandbox API keys with the Live API credentials in the config.php file (Login ID and Transaction Key).
In $ANET ENV, change the environment to PRODUCTION.

$ANET_ENV = 'PRODUCTION';

Note :

The Authorize.Net API is the simplest approach to integrate a credit card payment gateway. Using Authorize.Net and PHP, this sample code will help you incorporate the credit card payment process into your website. You can accept credit card payments from buyers and keep the transaction details in your database.

 

PHPCODE © 2024