Authorize.Net Payment Gateway Integration using PHP
Authorize.Net is the most popular payment Gateway and widely used payment-enabling mechanisms in many E-commerce applications.Authorize.net payment gateway integration supports the standard Visa, MasterCard, Discover, Apple Pay, Google Pay, PayPal, and all popular similar services.
Authorize.Net provides API services with features like payment transactions, webhooks, and more. In this tutorial, I will explain to you a step-by-step process to integrate Authorize.Net Payment Gateway in PHP for accepting online payments.
Features
- Easy integration with your web application
- Filters to Help Fight Fraud
- No-Hassle Subscriptions and Recurring Billing
- No update? No extra charge
- Easy-to-read reports
- Invoice online for faster payments and more
Create Authorize.Net account to get API Credentials
- Create Authorize.Net sandbox account.
- Get Sandbox API credentials API LOGIN ID, TRANSACTION KEY and KEY.
Before started to implement the Authorize.Net Payment Gateway in PHP, look files structure:
- authorize-net-payment-gateway-integration-in-php
- anet-sdk-php
- css
- templates
- config.php
- DBConnection.php
- AuthorizeNetPayment.php
- Order.php
- payment.php
- index.php
Step 1: Create the database and Table
For this tutorial, you need a MySQL database with the following table:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
-- Table structure for table `anet_payment` CREATE TABLE `anet_payment` ( `first_name` varchar(100) DEFAULT NULL, `last_name` varchar(100) DEFAULT NULL, `email` varchar(100) DEFAULT NULL, `id` int(11) NOT NULL, `transaction_id` varchar(30) NOT NULL, `auth_code` varchar(25) NOT NULL, `response_code` varchar(25) NOT NULL, `payment_response` text NOT NULL, `total_amt` float(10,2) NOT NULL, `modified_date` varchar(12) NOT NULL, `created_date` varchar(12) NOT NULL, `status` varchar(25) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- Indexes for table `anet_payment` ALTER TABLE `anet_payment` ADD PRIMARY KEY (`id`); -- AUTO_INCREMENT for table `anet_payment` ALTER TABLE `anet_payment` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; |
Step 2: Authorize.Net API Configuration file named
config.php
In the config.php file, constant variables of the Authorize.Net API and database settings are defined.
1 2 3 4 5 |
<?php define('ANET_API_LOGIN_ID', 'YOUR-API-LOGIN-ID'); define('ANET_TRANSACTION_KEY', 'YOUR-TRANSACTION-KEY'); define('ANET_ENV', 'SANDBOX'); // {OR} PRODUCTION ?> |
Step 3: Database Connection file named
DBConnection.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php /** * @package DBConnection * * @author TechArise Team * * @email info@techarise.com * */ // Database Connection class DBConnection { private $_dbHostname = "localhost"; private $_dbName = "demo_DB"; private $_dbUsername = "root"; private $_dbPassword = "root"; private $_con; public function __construct() { try { $this->_con = new PDO("mysql:host=$this->_dbHostname;dbname=$this->_dbName", $this->_dbUsername, $this->_dbPassword); $this->_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } } // return Connection public function returnConnection() { return $this->_con; } } ?> |
Step 4: Create class Request Payment Process file named
AuthorizeNetPayment.php
- Include Authorize.Net PHP SDK.
- Charge Credit Card
- Process Payment
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
<?php require './anet-sdk-php/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 $_anet_env; private $_merchantAuthentication; public $_responseText; //__construct public function __construct() { require_once "./config.php"; $this->_APILoginId = ANET_API_LOGIN_ID; $this->_APIKey = ANET_TRANSACTION_KEY; $this->_anet_env = ANET_ENV; $this->_refId = 'ref' . time(); $this->_merchantAuthentication = $this->setMerchantAuthentication(); $this->_responseText = array("1"=>"Approved", "2"=>"Declined", "3"=>"Error", "4"=>"Held for Review"); } // set Merchant Authentication public function setMerchantAuthentication() { // Create a merchantAuthenticationType object with authentication details // retrieved from the config file $merchantAuthentication = new AnetAPI\MerchantAuthenticationType(); $merchantAuthentication->setName($this->_APILoginId); $merchantAuthentication->setTransactionKey($this->_APIKey); return $merchantAuthentication; } // set Credit Card public function setCreditCard($cardDetails) { // Create the payment data for a credit card $creditCard = new AnetAPI\CreditCardType(); $creditCard->setCardNumber($cardDetails["card_number"]); $creditCard->setExpirationDate( $cardDetails["card_exp_month"] . "-" . $cardDetails["card_exp_year"]); $creditCard->setCardCode($cardDetails["card_cvc"]); // Add the payment data to a paymentType object $paymentType = new AnetAPI\PaymentType(); $paymentType->setCreditCard($creditCard); return $paymentType; } // set TransactionRequest Type public function setTransactionRequestType($paymentType, $amount) { // Create a transaction $transactionRequestType = new AnetAPI\TransactionRequestType(); $transactionRequestType->setTransactionType("authCaptureTransaction"); $transactionRequestType->setAmount($amount); $transactionRequestType->setPayment($paymentType); return $transactionRequestType; } public function customerData($data) { // Set the customer's identifying information $customerData = new AnetAPI\CustomerDataType(); $customerData->setType("individual"); $customerData->setId(time()); $customerData->setEmail($data['email']); // Set the customer's address $customerAddress = new AnetAPI\CustomerAddressType(); $customerAddress->setFirstName($data['first_name']); $customerAddress->setLastName($data['last_name']); $customerAddress->setCompany("TA"); $customerAddress->setAddress("Delhi"); $customerAddress->setCity("Delhi"); $customerAddress->setState("DE"); $customerAddress->setZip("1100001"); $customerAddress->setCountry("India"); } // charge Credit Card public function chargeCreditCard($cardDetails) { $paymentType = $this->setCreditCard($_POST); $transactionRequestType = $this->setTransactionRequestType($paymentType, $_POST["amount"]); $request = new AnetAPI\CreateTransactionRequest(); $request->setMerchantAuthentication($this->_merchantAuthentication); $request->setRefId( $this->_refId); $request->setTransactionRequest($transactionRequestType); $controller = new AnetController\CreateTransactionController($request); $response = $controller->executeWithApiResponse(constant("\\net\authorize\api\constants\ANetEnvironment::$this->_anet_env")); return $response; } } ?> |
Step 5: Create Payment class file named
Order.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
<?php /** * @package Order class * * @author TechArise Team * * @email info@techarise.com * */ include("DBConnection.php"); class Order { protected $db; private $_firstName; private $_lastName; private $_email; private $_transactionID; private $_authCode; private $_responseCode; private $_paymentResponse; private $_totalAmt; private $_modifiedDate; private $_createdDate; private $_status; public function setFirstName($firstName) { $this->_firstName = $firstName; } public function setLastName($lastName) { $this->_lastName = $lastName; } public function setEmail($email) { $this->_email = $email; } public function setTransactionID($transactionID) { $this->_transactionID = $transactionID; } public function setAuthCode($authCode) { $this->_authCode = $authCode; } public function setResponseCode($responseCode) { $this->_responseCode = $responseCode; } public function setPaymentResponse($paymentResponse) { $this->_paymentResponse = $paymentResponse; } public function setTotalAmt($totalAmt) { $this->_totalAmt = $totalAmt; } public function setModifiedDate($modifiedDate) { $this->_modifiedDate = $modifiedDate; } public function setCreatedDate($createdDate) { $this->_createdDate = $createdDate; } public function setStatus($status) { $this->_status = $status; } // __construct public function __construct() { $this->db = new DBConnection(); $this->db = $this->db->returnConnection(); } // insert payment info public function Orders() { try { $sql = 'INSERT INTO anet_payment (first_name, last_name, email, transaction_id, auth_code, response_code, payment_response, total_amt, modified_date, created_date, status) VALUES (:first_name, :last_name, :email, :transaction_id, :auth_code, :response_code, :payment_response, :total_amt, :modified_date, :created_date, :status)'; $data = [ 'first_name' => $this->_firstName, 'last_name' => $this->_lastName, 'email' => $this->_email, 'transaction_id' => $this->_transactionID, 'auth_code' => $this->_authCode, 'response_code' => $this->_responseCode, 'payment_response' => $this->_paymentResponse, 'total_amt' => $this->_totalAmt, 'modified_date' => $this->_modifiedDate, 'created_date' => $this->_createdDate, 'status' => $this->_status, ]; $stmt = $this->db->prepare($sql); $stmt->execute($data); $status = $stmt->rowCount(); return $status; } catch (Exception $e) { die("Oh noes! There's an error in the query!". $e); } } } ?> |
Step 6: Create Payment Checkout Form file named
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
<?php include('templates/header.php');?> <form id="frmPayment" action="payment.php" method="post"> <section class="showcase"> <div class="container"> <div class="pb-2 mt-4 mb-2 border-bottom"> <h2>Authorize.Net Payment Gateway Integration using PHP</h2> </div> <div class="row align-items-center"> <div class="form-group col-md-12"> <label for="inputEmail4">Amount</label> <input type="text" class="form-control" id="amount" name="amount" placeholder="amount" value="1.00" readonly="readonly"> </div> </div> <div class="row align-items-center"> <div class="form-group col-md-6"> <label for="inputEmail4">First Name</label> <input type="text" class="form-control" id="first-name" name="first_name" placeholder="First Name" required=""> </div> <div class="form-group col-md-6"> <label for="inputEmail4">Last Name</label> <input type="text" class="form-control" id="last-name" name="last_name" placeholder="Last Name" required=""> </div> </div> <div class="row align-items-center"> <div class="form-group col-md-12"> <label for="inputEmail4">Email</label> <input type="email" class="form-control" id="email" name="email" placeholder="Email" required=""> </div> </div> <div class="row align-items-center"> <div class="form-group col-md-12"> <label for="inputEmail4">Card Number</label> <input type="text" class="form-control" maxlength="18" id="card_number" name="card_number" placeholder="4111111111111111" autocomplete="off" required=""> </div> </div> <div class="row align-items-center"> <div class="form-group col-md-4"> <label for="inputEmail4">Expiry Month</label> <select name="card_exp_month" id="month" class="form-control" required=""> <option value="09">09</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> </select> </div> <div class="form-group col-md-4"> <label for="inputEmail4">Expiry Year</label> <select name="card_exp_year" id="year" class="form-control" required=""> <?php echo $firstYear = (int)date('Y'); $lastYear = $firstYear + 10; for($i=$firstYear;$i<=$lastYear;$i++) { echo '<option value='.$i.'>'.$i.'</option>'; } ?> </select> </div> <div class="form-group col-md-4"> <label for="inputEmail4">CVC</label> <input type="text" name="card_cvc" maxlength="3" placeholder="CVC" class="form-control" autocomplete="off" required=""> </div> </div> <div class="row justify-content-start"> <div class="col"> <button type="submit" name="pay_now" class="btn btn-primary float-right btn-payment">Pay Now</button> </div> </div> </div> </div> </section> </form> <br> <section class="showcase"> <div class="container"> <h3>Test Card </h3> <table cellspacing="5" cellpadding="5" width="100%" border="1"> <tr> <td>4111111111111111</td> <td>Visa</td> </tr> <tr> <td>5424000000000015</td> <td>Mastercard</td> </tr> <tr> <td>370000000000002</td> <td>American Express</td> </tr> <tr> <td>6011000000000012</td> <td>Discover</td> </tr> <tr> <td>38000000000006</td> <td>Diners Club/ Carte Blanche</td> </tr> <tr> <td>3088000000000017</td> <td>JCB</td> </tr> </table> </div> </section> <?php include('templates/footer.php');?> |
Step 7: Create Payment Process file named
payment.php
- Retrieve user and card information via
$_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
- Create CustomerDataType object
- Create TransactionRequestType object
- Charge and validate credit card for transaction
- if API request success, the orde details inserted in database
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
<?php require_once "./config.php"; include('./Order.php'); $payObj = new Order(); $reponseType = ""; $message = ""; $postData = $_POST; if(!empty($postData['card_number']) && !empty($postData['card_exp_month']) && !empty($postData['card_exp_year']) && !empty($postData['card_cvc'])){ require_once './AuthorizeNetPayment.php'; $authorizeNetObj = new AuthorizeNetPayment(); $response = $authorizeNetObj->chargeCreditCard($postData); // set customer data $authorizeNetObj->customerData($postData); if ($response != null) { $transResponse = $response->getTransactionResponse(); if (($transResponse != null) && ($transResponse->getResponseCode()=="1")) { $authCode = $transResponse->getAuthCode(); $paymentResponse = $transResponse->getMessages()[0]->getDescription(); $reponseType = "success"; $message = "<div class='alert alert-success'>Your Payment has been Successful!</div> <br/> AUTH CODE : " . $transResponse->getAuthCode() . " <br/>TRANS ID : " . $transResponse->getTransId() . "\n"; } else { $authCode = ""; $paymentResponse = $transResponse->getErrors()[0]->getErrorText(); $reponseType = "failed"; $message = "<div class='alert alert-danger'>Credit Card ERROR : Invalid response</div>"; } $transactionId = $transResponse->getTransId(); $responseCode = $transResponse->getResponseCode(); $paymentStatus = $response->getMessages()->getResultCode(); // Insert tansaction data into the database $time = time(); $payObj->setFirstName($postData["first_name"]); $payObj->setLastName($postData["last_name"]); $payObj->setEmail($postData["email"]); $payObj->setTransactionID($transactionId); $payObj->setAuthCode($authCode); $payObj->setResponseCode($responseCode); $payObj->setPaymentResponse($paymentResponse); $payObj->setTotalAmt($postData["amount"]); $payObj->setModifiedDate($time); $payObj->setCreatedDate($time); $payObj->setStatus($paymentStatus); $studentInfo = $payObj->Orders(); } else { $reponseType = "error"; $message = "<div class='alert alert-danger'>Transaction Failed! No response returned</div>"; } } ?> <?php include('templates/header.php');?> <section class="showcase"> <div class="container"> <div class="text-center"> <h1 class="display-3">Thank You!</h1> <?php if(!empty($message)) { ?> <h5><?php print $message;?></h5> <?php } ?> <hr> <p> Having trouble? <a href="mailto:info@techarise.com">Contact us</a> </p> <p class="lead"> <a class="btn btn-primary btn-sm" href="http://localhost/ta/authorize-net-payment-gateway-integration-in-php" role="button">Continue to homepage</a> </p> </div> </div> </section> <br><br><br><br><br><br> <?php include('templates/footer.php');?> |
Create files named (header.php and footer.php)
This file contains the header and footer section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header and footer section.
header.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Authorize.Net Payment Gateway Integration using PHP | Tech Arise</title> <link rel="icon" type="image/ico" href="<?php print HTTP_IMAGE_PATH; ?>favicon.ico"> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" /> <!-- Custom fonts for this template --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.2/css/all.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" /> <link href="https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css"> <!-- Custom styles for this template --> <link href="css/style.css" rel="stylesheet"> </head> <body> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top header-bg-dark" style="background: ##FFFFFF!;"> <div class="container"> <a class="navbar-brand font-weight-bold" href="https://techarise.com"><h1>Tech Arise</h1></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="https://techarise.com">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="https://techarise.com/php-free-script-demos/">Live Demo</a> </li> </ul> </div> </div> </nav> |
footer.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<!-- Footer --> <footer class="footer bg-light footer-bg-dark"> <div class="container"> <div class="row"> <div class="col-lg-6 h-100 text-center text-lg-left my-auto"> <ul class="list-inline mb-2"> <li class="list-inline-item"> <a href="#">About</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Contact</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Terms of Use</a> </li> <li class="list-inline-item">⋅</li> <li class="list-inline-item"> <a href="#">Privacy Policy</a> </li> </ul> <p class="text-muted small mb-4 mb-lg-0">Copyright © 2011 - <?php print date('Y', time());?> <a href="https://techarise.com/">TECHARISE.COM</a> All rights reserved.</p> </div> <div class="col-lg-6 h-100 text-center text-lg-right my-auto"> <ul class="list-inline mb-0"> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-facebook fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item mr-3"> <a href="#"> <i class="fab fa-twitter-square fa-2x fa-fw"></i> </a> </li> <li class="list-inline-item"> <a href="#"> <i class="fab fa-instagram fa-2x fa-fw"></i> </a> </li> </ul> </div> </div> </div> </footer> <!-- Bootstrap core JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script> </body> </html> |