Site icon Tutorials Website: Upgrade Your Web Development & Coding Skills

How to Integrate 2Checkout Payment Gateway in PHP

2Checkout Payment Gateway

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 TABLE order_transaction (
 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 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?

  1. First we Get token, credit or debit card details and user info form the submitted payment form using POST Method in PHP.
  2. Include the 2Checkout PHP library
  3. Now Configure your API credentials (Private Key and SellerId).
  4. Make an array with buyer sale parameters and pass it in auth() function of Twocheckout_Charge class for authorization.
  5. Create a payment charge and retrieve the charge details.
  6. if payment charge is successful then insert the order and transaction details in database table “order_transaction” using PHP and MySql script.
  7. 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.

Conclusion

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Exit mobile version