2Checkout Payment Gateway Integration in PHP

2Checkout Payment Gateway provides an easy way to integrate the checkout system in the web application. The 2Checkout Payment API allows you to accept payment with credit cards on the web application. If you want to accept credit card payment from the website, 2Checkout API is the simplest solution.

With 2Checkout payment gateway, you can allow the user to make the payment through their credit or debit card. 2Checkout PHP library helps to connect the Payment API, create a charge against credit card and process the payment. In this tutorial, we will show you how to integrate 2Checkout payment gateway in PHP for collecting payment online with credit card or debit card.

In the 2Checkout payment gateway integration process, the following functionality will be implemented.

  • Create an HTML form to collect credit card and user information.
  • Create 2Checkout token to securely transmit card details.
  • Submit the credit card form.
  • Verify the card info and process charges using 2Checkout Payment API.
  • Insert the transaction details in the database and display the payment status.

2Checkout Sandbox Account

2Checkout’s sandbox provides a test environment to check the 2Checkout integration process. Before taking your 2Checkout payment gateway live, you need to test the integration on sandbox environment. Follow the below steps to generate API Keys on Sandbox account to test the credit card payment process with 2Checkout API.

  • Login to your 2Checkout Sandbox account or sign up if don’t have an account.
  • Go to the API page and generate API keys » Switch to the Settings tab. In the Key Generator section, you will see the Publishable Key and Private Key.
    2checkout-create-sandbox-account-publishable-private-key-codexworld
  • Collect the Publishable Key and Private key to use later in the script.

Before getting started to implement 2Checkout payment gateway in PHP, take a look the files structure.

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

Create Database Table

To store the transaction details, a table needs to be created in the database. The following SQL creates an orders table with some basic fields in the MySQL database.

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;

Database Configuration (dbConfig.php)

The dbConfig.php file is used to connect to the database. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per your MySQL server credentials.

<?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);
}

2Checkout Payment Form (index.html)

Include the jQuery library and 2Checkout JavaScript library to make the token request.

<!-- 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>

The following JavaScript code handles the token request call and attaches the token input to the credit card form before submission. Specify the sandbox-seller-id (Account Number) and sandbox-publishable-key (Publishable Key) as per your API credentials.

<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 basic credit card form that allows the buyer to provide their card number, expiration month and year, and CVC. This form will be submitted to the server-side script (paymentSubmit.php) for processing the payment with 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>

2Checkout PHP library

The 2Checkout PHP library is used to process the card transaction using Payment API. All the library files are included in our source code, don’t need to download it separately.

Validate and Process Payment (paymentSubmit.php)

Once the tokenized credit card information has been submitted to the server-side script (paymentSubmit.php), the charge authorization is processed using 2Checkout PHP library.

  • Get token, card details and user info from the submitted form using POST method in PHP.
  • Include the 2Checkout PHP library.
  • Set your API credentials (Private Key and SellerId).
  • Create an array with sale parameters and pass it in auth() method of Twocheckout_Charge class for authorization.
  • Create a charge and retrieve the charge details.
  • If the charge is successful, insert the order and transaction details in the database using PHP and MySQL.
  • Show the payment status to the buyer.
<?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>

Test Card Details

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

Once testing is completed with Sandbox account, make the 2Checkout payment gateway live for production use.

  • Login to your 2Checkout account and go to the API page.
  • Generate API keys and switch to the Settings tab. From the Key Generator section, collect the Publishable key and Private key.

In the index.html file,

  • Change the sellerId (Account Number) and publishableKey (Publishable key) as per the API credentials of your live 2Checkout account.
    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);
    };
  • Set production key in loadPubKey() method.
    TCO.loadPubKey('production');

In the paymentSubmit.php file,

  • Change the sellerId (Account Number) and privateKey (Private key) as per the API credentials of your live 2Checkout account.
    Twocheckout::privateKey('live-private-key');
    Twocheckout::sellerId('live-seller-id');
  • Set false in sandbox().
    Twocheckout::sandbox(false);

Stripe Payment Gateway Integration in PHP

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

3 Comments

  1. Ash Sharma Said...
  2. Hamza Ali Zahid Said...
    • CodexWorld Said...

Leave a reply

keyboard_double_arrow_up