If you have ecommerce website and you want to accept payment via credit card or debit card from your website then 2Checkout Payment Gateway is the easy solution. In this article, i will show you an easy way to integrate 2Checkout Payment Gateway in web application or ecommerce website.
The 2Checkout Payment API allows you to accept payment via credit cards or debit card on your website. With 2Checkout Gateway, your website user or customer can make payment through their credit or debit card.
If you are a Web Developer and want to integrate 2Checkout Payment Gateway, 2Checkout PHP library helps you to connect the Payment API and process the credit or debit card payment. Now i will explain you step by step process to integrate 2Checkout payment gateway in PHP for accept payment online with credit or debit card.
How to create 2Checkout Sandbox Account:
2Checkout sandbox account provide a testing environment to test 2Checkout integration process. Before make 2Checkout payment gateway live or production mode, you need to test the gateway integration in sandbox environment. you need to follow the below steps to generate 2Checkout payment Gateway API Keys in Sandbox Account. We will use this API Keys to test the credit or debit card payment process with 2Checkout Gateway API.
Step-1: Login or Signup (if you don’t have account) into your 2Checkout Sandbox account.
Step-2: After Login you will get an API tab in top bar Menu, Click on API Menu.
Step-3: Go to API Page and generate API Keys. In Key Generation section, you will get Publishable Key and Private Key. Copy both keys and save it in your notepad for later use in the script.
Now First we need to create a Database Table to store order transaction details.
Following Sql query will create “order_transaction” table with some basic field in mysql database
CREATE TABLEorder_transaction(idint(11) NOT NULL AUTO_INCREMENT,namevarchar(25) COLLATE utf8_unicode_ci NOT NULL,card_numbigint(20) NOT NULL,card_exp_monthint(2) NOT NULL,card_exp_yearyear(4) NOT NULL,card_cvvint(3) NOT NULL,item_namevarchar(255) COLLATE utf8_unicode_ci NOT NULL,item_numbervarchar(25) COLLATE utf8_unicode_ci NOT NULL,item_pricefloat(10,2) NOT NULL,currencyvarchar(10) COLLATE utf8_unicode_ci NOT NULL,paid_amountvarchar(10) COLLATE utf8_unicode_ci NOT NULL,order_numbervarchar(20) COLLATE utf8_unicode_ci NOT NULL,txn_idvarchar(50) COLLATE utf8_unicode_ci NOT NULL,payment_statusvarchar(10) COLLATE utf8_unicode_ci NOT NULL,createddatetime NOT NULL,modifieddatetime NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
To connect our database we need to create Database Configuration file (dbconfig.php).
dbconfig.php file will contain database host ($host ), username ($dbuser ), password ($dbpass) and database name ($dbname) mysql server credentials.
connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
Create 2Checkout Payment Form (index.php)
You need to create payment form that allow buyer to submit their details like email, name on card, card number, expiration month and year, and CVC.
Charge $10 USD with 2Checkout
Include the jQuery library and 2Checkout javascript library to create the token request. put below library under tag.
Also copy and paste following javascript code under tag or before tag. Following javascript code will handle the token request call and attached the token input to credit or debit card form before submission data.
2Checkout PHP Library:
The 2Checkout PHP library is required to process the card transaction using Payment Gateway API. All the library files are included in our source code, so don’t need to download ir separately.
Create (submitPayment.php) file to Validate and Process Payment:
Once the token and credit or debit card information has been submitted to server-side script (submitPayment.php), the amount charge authorization is processed using 2Checkout PHP Library.
How to Validate and Process Payment?
- First we Get token, credit or debit card details and user info form the submitted payment form using POST Method in PHP.
- Include the 2Checkout PHP library
- Now Configure your API credentials (Private Key and SellerId).
- Make an array with buyer sale parameters and pass it in auth() function of Twocheckout_Charge class for authorization.
- Create a payment charge and retrieve the charge details.
- if payment charge is successful then insert the order and transaction details in database table “order_transaction” using PHP and MySql script.
- Display the payment success status with Order ID, Order Number, order total and transaction ID to the buyer.
$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 order_transaction(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 = 'Thanks for your Order!
';
$statusMsg .= 'The transaction was successful. Order details are given below:
';
$statusMsg .= "Order ID: {$insert_id}
";
$statusMsg .= "Order Number: {$orderNumber}
";
$statusMsg .= "Transaction ID: {$transactionId}
";
$statusMsg .= "Order Total: {$total} {$currency}
";
}
} catch (Twocheckout_Error $e) {
$statusMsg = 'Transaction failed!
';
$statusMsg .= ''.$e->getMessage().'
';
}
}else{
$statusMsg = "Error with Form submission.
";
}
?>
2Checkout Payment Status
Test Card Details for 2Checkout Payment:
To test the 2Checkout payment API integration, use any of the following test credit card information.
Credit Card Number: 4000000000000002 Expiration date: 10/2020 cvv: 123
Use the following card information to test a failed authorization.
Credit Card Number: 4333433343334333 Expiration date: 10/2020 cvv: 123
Make 2Checkout Payment Gateway Live
After complete testing with Sandbox details, Make the 2Checkout payment gateway live for production mode.
- Login into your 2Checkout live account and go to API page
- Generate live API Keys (Publishable key and Private Key) and replace keys with sandbox keys details.
- Change sellerId (Account Number) and publishableKey (Publishable key) in “index.php” file as per you live 2Checkout account
- Set production key in loadPubKey() method.
TCO.loadPubKey('production'); - Also change sellerid and Private Key in submitPayment.php file as per 2Checkout Live account credentials.
Twocheckout::privateKey('live-private-key'); Twocheckout::sellerId('live-seller-id'); - Set false in sandbox() in submitPayment.php file
Twocheckout::sandbox(false);
Conclusion
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co
