The 2Checkout Payment Gateway makes it simple to incorporate the checkout system into a web application. The 2Checkout Payment API enables you to accept credit card payments on your web application. If you wish to take credit card payments from your website, the 2Checkout API is the most straightforward method.
You may allow users to pay with their credit or debit card using the 2Checkout payment gateway. The 2Checkout PHP library facilitates connecting to the Payment API, creating a charge against a credit card, and processing the payment. In this article, we will teach you how to integrate the 2Checkout payment gateway in PHP to accept credit card or debit card payments online.
The following features will be added throughout the 2Checkout payment gateway integration procedure.
- To gather payment card and user information, create an HTML form.
- To securely transfer card information, create a 2Checkout token.
- Fill out the credit card form and submit it.
- Using the 2Checkout Payment API, verify the card information and process the charges.
- Insert the transaction information into the database and show the payment status.
The 2Checkout sandbox is a testing environment for the 2Checkout integration process. Before going live with your 2Checkout payment gateway, you should test the integration in a sandbox environment. To test the credit card payment process using the 2Checkout API, follow the steps below to generate API Keys on your Sandbox account.
1. Sign in to your 2Checkout Sandbox account, or create one if you don't already have one.
2. Navigate to the API page and create API keys « Navigate to the Settings tab. The Publishable Key and Private Key may be found in the Key Generator section.
3. Gather the Publishable Key and Private Key for subsequent usage in the script.
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/
A table in the database must be built to record the transaction details. In the MySQL database, the following SQL generates an orders table with some simple columns.
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;
To connect to the database, use the dbConfig.php file. As per your MySQL server credentials, provide 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); }
To make the token request, include 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. As per your API credentials, enter the 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>
Build a simple credit card form that asks the buyer for their card number, expiry month and year, and CVC. This form will be sent to the server-side script (paymentSubmit.php) for payment processing 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>
The Payment API is utilised by the 2Checkout PHP framework to process the card transaction. There is no need to download any of the library files individually because they are all included in our source code.
The charge authorisation is handled by the 2Checkout PHP framework when the entered credit card data is given to the server script (paymentSubmit.php).
- Using the POST method in PHP, get the token, card data, and user information from the going through this process.
- Include the PHP library 2Checkout.
- Configure your API details (Sellerid and Private Key).
- Create an array with the sale parameters and provide it to the Twocheckout Charge class's auth() function for authorisation.
- Make a charge and get the charge information.
- f the charge is successful, use PHP and MySQL to save the order and transaction information 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>
Once testing with the Sandbox account is complete, activate the 2Checkout payment gateway for production use.
1. Go to the API page after logging into your 2Checkout account.
2. Create API keys and navigate to the Settings tab. Take the Publishable key and Private key from the Key Generator section.
Included in the index.html file.
- Change the sellerId (Account Number) and publishableKey (Publishable Key) to match your actual 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() function, specify the production key.
TCO.loadPubKey('production');
In the paymentSubmit.php
file,
- Change the sellerId (Account Number) and privateKey (Private Key) to match your actual 2Checkout account's API credentials.
Twocheckout::privateKey('live-private-key'); Twocheckout::sellerId('live-seller-id');
- In the sandbox, set false ().
Twocheckout::sandbox(false);
© ThemesGiant Copyright @2015-2022 | All rights reserved.