Skip to Content
PHPCODE
2Checkout payment Gateway integration in PHP
php code / September 26, 2021

The 2Checkout Payment Gateway makes it simple to include a checkout system into a web application. The 2Checkout Payment API enables you to take credit card payments through your web application. The 2Checkout API is the simplest way to take credit card payments from your website.

You can allow users to pay with their credit or debit card using the 2Checkout payment gateway. The 2Checkout PHP library facilitates the connection to the Payment API, the creation of a charge against a credit card, and the payment processing. In this tutorial, we’ll teach you how to use PHP to connect the 2Checkout payment gateway for accepting credit card and debit card payments online.

The following features will be added throughout the 2Checkout payment gateway integration procedure.

To collect payment card and user information, create an HTML form.
To securely transfer card details, create a 2Checkout token.
Fill out the credit card form and submit it.
Using the 2Checkout Payment API, verify the card information and process charges.
Display the payment status after entering the transaction details into the database.

2Login to your Sandbox Account
The sandbox provided by 2Checkout is a testing environment for the 2Checkout integration process. You should test your 2Checkout payment gateway integration in a sandbox environment before going live. To test the credit card payment process with the 2Checkout API, follow the steps below to generate API Keys on a Sandbox account.

Log in to your 2Checkout Sandbox account, or create one if you don’t already have one.
Generate API keys from the API page » Toggle over to the Settings tab. The Publishable Key and Private Key can be found in the Key Generator section.

To utilise later in the script, collect the Publishable Key and Private Key.
Examine the file structure before beginning to construct the 2Checkout payment gateway in PHP.

2checkout_integration_php/
├── index.html
├── paymentSubmit.php
├── dbConfig.php
└── 2checkout-php/

 

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 with some basic fields.

CREATE TABLE `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`card_num` bigint(20) NOT NULL,
`card_exp_month` int(2) NOT NULL,
`card_exp_year` year(4) NOT NULL,
`card_cvv` int(3) NOT NULL,
`item_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`item_number` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`item_price` float(10,2) NOT NULL,
`currency` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`paid_amount` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`order_number` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`txn_id` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`payment_status` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Configuring the Database (dbConfig.php)

To connect to the database, use the dbConfig.php file. According to your MySQL server credentials, specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName).

<?php
// Database configuration
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "codexworld";
// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}

2Payment Form for Checkout (index.html)

To make the token request, use the jQuery library and the 2Checkout JavaScript module.

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- 2Checkout JavaScript library -->
<script src="https://www.2checkout.com/checkout/api/2co.min.js"></script>

Before submitting the credit card form, the following JavaScript code processes the token request call and binds the token input to it. Specify your API credentials for sandbox-seller-id (Account Number) and sandbox-publishable-key (Publishable Key).

<script>
// Called when token created successfully.
var successCallback = function(data) {
var myForm = document.getElementById('paymentFrm');

// Set the token as the value for the token input
myForm.token.value = data.response.token.token;

// Submit the form
myForm.submit();
};
// Called when token creation fails.
var errorCallback = function(data) {
if (data.errorCode === 200) {
tokenRequest();
} else {
alert(data.errorMsg);
}
};
var tokenRequest = function() {
// Setup token request arguments
var args = {
sellerId: "sandbox-seller-id",
publishableKey: "sandbox-publishable-key",
ccNo: $("#card_num").val(),
cvv: $("#cvv").val(),
expMonth: $("#exp_month").val(),
expYear: $("#exp_year").val()
};
// Make the token request
TCO.requestToken(successCallback, errorCallback, args);
};
$(function() {
// Pull in the public encryption key for our environment
TCO.loadPubKey('sandbox');
$("#paymentFrm").submit(function(e) {
// Call our token request function
tokenRequest();
// Prevent form from submitting
return false;
});
});
</script>

Create a simple credit card form that asks for the buyer’s card number, expiration month and year, and CVC. This form will be sent to the paymentSubmit.php server-side script, which will process the payment using the 2Checkout API.

<div class="payment-frm">
<h5>Charge $25 USD with 2Checkout</h5>
<!-- credit card form -->
<form id="paymentFrm" method="post" action="paymentSubmit.php">
<div>
<label>NAME</label>
<input type="text" name="name" id="name" placeholder="Enter name" required autofocus>
</div>
<div>
<label>EMAIL</label>
<input type="email" name="email" id="email" placeholder="Enter email" required>
</div>
<div>
<label>CARD NUMBER</label>
<input type="text" name="card_num" id="card_num" placeholder="Enter card number" autocomplete="off" required>
</div>
<div>
<label><span>EXPIRY DATE</span></label>
<input type="number" name="exp_month" id="exp_month" placeholder="MM" required>
<input type="number" name="exp_year" id="exp_year" placeholder="YY" required>
</div>
<div>
<label>CVV</label>
<input type="number" name="cvv" id="cvv" autocomplete="off" required>
</div>
<!-- hidden token input -->
<input id="token" name="token" type="hidden" value="">
<!-- submit button -->
<input type="submit" class="btn btn-success" value="Submit Payment">
</form>
</div>

2ch. the PHP library

The Payment API is used to handle the card transaction using the 2Checkout PHP library. There is no need to download the library files individually because they are all included in our source code.

Payment Validation and Processing (paymentSubmit.php)
The charge authorization is done using the 2Checkout PHP library after the tokenized credit card information has been provided to the server-side script (paymentSubmit.php).

Using PHP’s POST method, retrieve the token, card details, and user information from the submitted form.

Include the PHP library 2Checkout.
Configure your API credentials (Private Key and SellerId).
Create an array of sale parameters and provide it to the Twocheckout Charge class’s auth() method for authorisation.
Create a charge and get the details about it.
If the charge is successful, use PHP and MySQL to save the order and transaction details in the database.
Show the buyer the payment status.

<?php
// Check whether token is not empty
if(!empty($_POST['token'])){
// Token info
$token = $_POST['token'];
// Card info
$card_num = $_POST['card_num'];
$card_cvv = $_POST['cvv'];
$card_exp_month = $_POST['exp_month'];
$card_exp_year = $_POST['exp_year'];
// Buyer info
$name = $_POST['name'];
$email = $_POST['email'];
$phoneNumber = '555-555-5555';
$addrLine1 = '123 Test St';
$city = 'Columbus';
$state = 'OH';
$zipCode = '43123';
$country = 'USA';
// Item info
$itemName = 'Premium Script CodexWorld';
$itemNumber = 'PS123456';
$itemPrice = '25.00';
$currency = 'USD';
$orderID = 'SKA92712382139';
// Include 2Checkout PHP library
require_once("2checkout-php/Twocheckout.php");
// Set API key
Twocheckout::privateKey('sandbox-private-key');
Twocheckout::sellerId('sandbox-seller-id');
Twocheckout::sandbox(true);
try {
// Charge a credit card
$charge = Twocheckout_Charge::auth(array(
"merchantOrderId" => $orderID,
"token" => $token,
"currency" => $currency,
"total" => $itemPrice,
"billingAddr" => array(
"name" => $name,
"addrLine1" => $addrLine1,
"city" => $city,
"state" => $state,
"zipCode" => $zipCode,
"country" => $country,
"email" => $email,
"phoneNumber" => $phoneNumber
)
));
// Check whether the charge is successful
if ($charge['response']['responseCode'] == 'APPROVED') {
// Order details
$orderNumber = $charge['response']['orderNumber'];
$total = $charge['response']['total'];
$transactionId = $charge['response']['transactionId'];
$currency = $charge['response']['currencyCode'];
$status = $charge['response']['responseCode'];
// Include database config file
include_once 'dbConfig.php';
// Insert order info to database
$sql = "INSERT INTO orders(name, email, card_num, card_cvv, card_exp_month, card_exp_year, item_name, item_number, item_price, currency, paid_amount, order_number, txn_id, payment_status, created, modified) VALUES('".$name."', '".$email."', '".$card_num."', '".$card_cvv."', '".$card_exp_month."', '".$card_exp_year."', '".$itemName."', '".$itemNumber."','".$itemPrice."', '".$currency."', '".$total."', '".$orderNumber."', '".$transactionId."', '".$status."', NOW(), NOW())";
$insert = $db->query($sql);
$insert_id = $db->insert_id;
$statusMsg = '<h2>Thanks for your Order!</h2>';
$statusMsg .= '<h4>The transaction was successful. Order details are given below:</h4>';
$statusMsg .= "<p>Order ID: {$insert_id}</p>";
$statusMsg .= "<p>Order Number: {$orderNumber}</p>";
$statusMsg .= "<p>Transaction ID: {$transactionId}</p>";
$statusMsg .= "<p>Order Total: {$total} {$currency}</p>";
}
} catch (Twocheckout_Error $e) {
$statusMsg = '<h2>Transaction failed!</h2>';
$statusMsg .= '<p>'.$e->getMessage().'</p>';
}
}else{
$statusMsg = "<p>Form submission error...</p>";
}
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>2Checkout Payment Status</title>
<meta charset="utf-8">
</head>
<body>
<div class="container">
<!-- Display payment status -->
<?php echo $statusMsg; ?>

<p><a href="index.html">Back to Payment</a></p>
</div>
</body>
</html>

Details on the Test Card

Use any of the following test credit card details to test the 2Checkout payment API integration.

Credit Card Number: 4000000000000003
Expiration date: 10/2021
cvv: 1235

Activate the 2Checkout Payment Gateway
Make the 2Checkout payment gateway live for production use once the Sandbox account has been thoroughly tested.

Go to the API page after logging into your 2Checkout account.
Switch to the Settings tab after generating API keys. Collect the Publishable key and Private key from the Key Generator section.
The index.html file contains the following information:

Change the sellerId (Account Number) and publishableKey (Publishable Key) to match your live 2Checkout account’s API credentials.

var tokenRequest = function() {
// Setup token request arguments
var args = {
sellerId: "live-seller-id",
publishableKey: "live-publishable-key",
ccNo: $("#card_num").val(),
cvv: $("#cvv").val(),
expMonth: $("#exp_month").val(),
expYear: $("#exp_year").val()
};
// Make the token request
TCO.requestToken(successCallback, errorCallback, args);
};

In the loadPubKey() method, set the production key.

TCO.loadPubKey('production');

paymentSubmit.php is a PHP file that accepts payments.

Change the sellerId (Account Number) and privateKey (Private Key) to match your live 2Checkout account’s API credentials.

Twocheckout::privateKey('live-private-key');
Twocheckout::sellerId('live-seller-id');

In the sandbox, set false ().

Twocheckout::sandbox(false);

 

 

 

 

 

PHPCODE © 2023