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.
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.
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
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;
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:
Database Constants:
<?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.
The dbConnect.php
file helps to connect the database using PHP and MySQL.
<?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();
}
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 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.
In this file, the submitted card details are validated and the charge is processed using Authorize.Net API library & PHP.
<?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>
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).
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.
config.php
file,
$ANET_ENV
.
$ANET_ENV = 'PRODUCTION';
Stripe Checkout Integration in PHP
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
Thanks for this help
Can not pass customer information such as name state zip ect to authorize.net just card information.
Our business sells coupons for multiple restaurants. Each of these restaurants will have their own merchant account.
customer can purchase multiple coupons of multiple restaurants from my site.
when customer make a payment.
we want from single transaction to their multiple restaurants accounts. how we can do?
Very Good