Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Integrate 2Checkout Payment Gateway using PHP

#1
How to Integrate 2Checkout Payment Gateway using PHP

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2020/01/how-to-integrate-2checkout-payment-gateway-using-php.png" width="940" height="788" title="" alt="" /></div><div><p>Last modified on November 27th, 2019 by Vincy.</p>
<p>Sales, revenue, ROI are the key metrics to measure a business growth. The payment gateway is a sensitive factor that affects these metrics directly. It is the first and foremost item on the checklist for any eCommerce business.</p>
<p>There are many Payment Gateway providers. PayPal being the popular provider and 2Checkout is catching out fast. Earlier I wrote about&nbsp;<a href="https://phppot.com/php/how-to-integrate-paypal-checkout-in-ecommerce-website/">how to integrate PayPal checkout in ecommerce website</a>. In this payment gateway integration series, now it is time to see about 2Checkout.&nbsp;</p>
<p><img class="alignnone size-full wp-image-10762" src="https://phppot.com/wp-content/uploads/2019/11/2Checkout-payment-gateway-integration-using-php.png" alt="2Checkout Payment Gateway Integration using-php PHP" width="940" height="788" srcset="https://phppot.com/wp-content/uploads/2019/11/2Checkout-payment-gateway-integration-using-php.png 940w, https://phppot.com/wp-content/uploads/20...00x251.png 300w, https://phppot.com/wp-content/uploads/20...68x644.png 768w, https://phppot.com/wp-content/uploads/20...50x461.png 550w" sizes="(max-width: 940px) 100vw, 940px"></p>
<p>2Checkout is one of the best payment gateway provider to support card payments. It works similar to Stripe payment gateway. Card payments has less friction and will enable to increase the conversion rate in your eCommerce business.</p>
<p>2Checkout is growing everyday in popularity. It is available in more than 180 countries and used by 17,000 firms.</p>
<p>To integrate 2Checkout to your ecommerce application there are few simple steps. I have described those steps in this article to make your job easier.</p>
<p>Also, we will see the <a href="https://phppot.com/jquery/jquery-credit-card-validator/">card validator script</a>, payment request-response handlers and more.</p>
<h2>What is inside?</h2>
<ol>
<li><a href="https://phppot.com/php/how-to-integrate-2checkout-payment-gateway-using-php/#other-payment-gateways-of-card-payments">Existing payment gateway methods supporting card payment</a></li>
<li><a href="https://phppot.com/php/how-to-integrate-2checkout-payment-gateway-using-php/#advantages-of-2checkout-payment">Advantages of 2Checkout payment</a></li>
<li><a href="https://phppot.com/php/how-to-integrate-2checkout-payment-gateway-using-php/#file-structure">File structure</a></li>
<li><a href="https://phppot.com/php/how-to-integrate-2checkout-payment-gateway-using-php/#integrate-2Checkout-Payment-Gateway-in-PHP">Steps to integrate 2Checkout payment gateway using PHP</a></li>
<li><a href="https://phppot.com/php/how-to-integrate-2checkout-payment-gateway-using-php/#database-script">Database script</a></li>
<li><a href="https://phppot.com/php/how-to-integrate-2checkout-payment-gateway-using-php/#go-live">Go live</a></li>
<li><a href="https://phppot.com/php/how-to-integrate-2checkout-payment-gateway-using-php/#2checkout-payment-form-output">2Checkout Payment gateway example output</a></li>
</ol>
<h2 id="other-payment-gateways-of-card-payments">Existing payment gateway methods supporting card payment</h2>
<p>I have been writing about payment gateways for a while We have already seen many types of payment gateway integration using PHP. I already written tutorials for CCAvenue, PayPal, Stripe, SagePay and <a href="https://phppot.com/php/authorize-net-payment-gateway-integration-using-php/">Authorize.Net</a>.&nbsp;</p>
<p>2Checkout, <a href="https://phppot.com/php/stripe-payment-gateway-integration-using-php/">Stripe</a>, CCAvenue are some of the examples for the methods supporting card-payments. There are many methods like InstaMojo, Cashfree, EBS and Paytm support card-payments.</p>
<h2 id="advantages-of-2checkout-payment">Advantages of 2Checkout payment</h2>
<ul>
<li>Easy to integrate using payment API libraries in PHP, PYTHON and more languages.</li>
<li>It allows customers to opt for a variety of <a href="https://phppot.com/php/paypal-payment-gateway-integration-in-php/">payment methods via PayPal account</a> or debit/credit cards.</li>
<li>2Checkout is a secured fraud-proof for selling products or subscription plans online.</li>
<li>It provides a localized buying experience for the customer.</li>
<li>It supports many currencies that supports global payments.</li>
<li><a href="https://phppot.com/php/shopify-like-sticky-shopping-cart-in-php/">Integratable with the eCommerce tools like Shopify</a>, Bigcommerce.</li>
</ul>
<h2 id="file-structure">File structure</h2>
<p>This image shows the file structure of the 2Checkout payment gateway PHP example. The root files&nbsp;<em>index.php, payment.php, return.php</em>&nbsp;are in a sequential flow during the payment.</p>
<p>While running this example, it lands with the index.php to show the payment form. Form targets payment.php that processes payment and redirects to the return page.</p>
<p>The redirect URL will have the payment response status parameter. It helps to create a response HTML on the return page.&nbsp;</p>
<p>The&nbsp;<em>assets&nbsp;</em>folder has the CSS, JS created for this example.&nbsp;<em>TwoCheckoutService.php&nbsp;</em>contains&nbsp;the library includes to verify card details and process payment.</p>
<p>You can see all the third-party components in the&nbsp;<em>vendor&nbsp;</em>directory.</p>
<p><img class="alignnone wp-image-10753 size-full" src="https://phppot.com/wp-content/uploads/2019/11/2checkout-payment-file-structure.jpg" alt="2Checkout Payment File Structure" width="400" height="608" srcset="https://phppot.com/wp-content/uploads/2019/11/2checkout-payment-file-structure.jpg 400w, https://phppot.com/wp-content/uploads/20...97x300.jpg 197w" sizes="(max-width: 400px) 100vw, 400px"></p>
<h2 id="integrate-2Checkout-Payment-Gateway-in-PHP">Steps to integrate 2Checkout payment gateway using PHP</h2>
<ol>
<li>Download the 2Checkout payment API library in PHP.</li>
<li>Create a 2Checkout account and generate API keys.</li>
<li>Create a payment form to collect the card details from the customer.</li>
<li>Generate payment API token and transfer the card details in a secure way.</li>
<li>Verify card details and process charges with 2Checkout Payment API.</li>
</ol>
<h3 id="about-2checkout-payment-gateway">Step 1: Download 2Checkout payment gateway</h3>
<p>2Checkout payment API library has many features. It helps to manage purchase flow, orders, invoices, billing and more. It simplifies the integration process and reduces the developer’s effort.</p>
<p><a href="https://github.com/2Checkout/2checkout-php" target="_blank" rel="noopener noreferrer">Download the 2Checkout payment API library from GitHub</a>. And then, put it into your application vendor directory.</p>
<p>While <a href="https://phppot.com/php/manage-recurring-payments-using-stripe-billing-in-php/">integrating Stripe Billing</a>, we saw how to integrate third-party API for payment.</p>
<p>Include the TwoCheckout.php service before verifying card details and process payments. This file includes all other library dependencies. It handles card validation and charges on the server-side.&nbsp;&nbsp;</p>
<p>In this example, the Checkout.php use this library file to perform the payment operations.</p>
<h3 id="Creating-2Checkout-Sandbox-accounts">Step 2: Creating 2Checkout sandbox account and generate API keys</h3>
<p>2Checkout provides a sandbox environment to check payment flow using the API functions.&nbsp;</p>
<p>This is a common practice to go with a sandbox mode for testing purposes. Then we can go live after verifying the payment flow with this mode.</p>
<p>Let us create a 2Checkout sandbox account via the developer console. By logging into the console, we can get our API keys.</p>
<ol>
<li><a href="https://sandbox.2checkout.com/sandbox/signup" target="_blank" rel="noopener noreferrer">Register and log in to the 2Checkout sandbox</a> account.</li>
<li>Select the <strong>API</strong> menu from the header and click the&nbsp;<strong>Start Integrating </strong>button.</li>
<li>Go to the&nbsp;<strong>Settings&nbsp;</strong>tab to get the API keys.</li>
<li>Copy the <strong>Publishable Key</strong> and <strong>Private Key</strong> in the key generation section of the page.</li>
</ol>
<p><img class="alignnone size-large wp-image-10748" src="https://phppot.com/wp-content/uploads/2019/11/2checkout-payment-api-keys-550x388.jpg" alt="2Checkout Payment API Keys" width="550" height="388" srcset="https://phppot.com/wp-content/uploads/2019/11/2checkout-payment-api-keys-550x388.jpg 550w, https://phppot.com/wp-content/uploads/20...00x212.jpg 300w, https://phppot.com/wp-content/uploads/20...68x541.jpg 768w" sizes="(max-width: 550px) 100vw, 550px"></p>
<p>Click the <strong>Generate</strong> button if you are not able to see the API keys.</p>
<p>I have added the keys and seller account id in the application config name Config.php.</p>
<p>After configuring the API keys, use the test data to make the payment in the sandbox mode. You can get the test data from the API page as shown below.</p>
<p><img class="alignnone size-medium wp-image-10749" src="https://phppot.com/wp-content/uploads/2019/11/2checkout-sandbox-card-details-241x300.jpg" alt="2Checkout Sandbox Card Details" width="241" height="300" srcset="https://phppot.com/wp-content/uploads/2019/11/2checkout-sandbox-card-details-241x300.jpg 241w, https://phppot.com/wp-content/uploads/20...50x684.jpg 550w, https://phppot.com/wp-content/uploads/20...etails.jpg 666w" sizes="(max-width: 241px) 100vw, 241px"></p>
<h3 id="html-2checkout-payment-form">Step 3: Create 2Checkout payment form in HTML</h3>
<p>This form contains input fields to get the basic credit card details from the buyer. Those are the cardholder’s name and email, card number, CVC, card expiry tenure.</p>
<p>It will also ask the billing address from the buyer.</p>
<p>In this payment form, it has hidden fields for keeping the seller account id and product price, code.</p>
<pre class="prettyprint lang-php">&lt;?php namespace Phppot; use Phppot\Config; require_once "Config.php"; $productCode = "WWPS235"; ?&gt; &lt;html&gt; &lt;head&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;link href="./assets/css/style.css" rel="stylesheet" type="text/css"&gt; &lt;title&gt;2checkout-payment-gateway-integration-using-PHP&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="formContainer"&gt; &lt;?php $productDetail = Config::productDetail(); $itemName = $productDetail[$productCode]["itemName"]; $itemPrice = $productDetail[$productCode]["itemPrice"]; ?&gt; &lt;div class="product-row"&gt; &lt;p class="product"&gt;&lt;?php echo $itemName; ?&gt;&lt;/p&gt; &lt;div class="price float-right"&gt;&lt;?php echo $itemPrice; ?&gt; &lt;?php echo Config::CURRENCY; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;form id="paymentForm" novalidate method="post" action="payment.php"&gt; &lt;input type="hidden" id="itemNumber" name="itemNumber" value="&lt;?php echo $productCode; ?&gt;" /&gt; &lt;input type="hidden" id="itemPrice" name="itemPrice" value="&lt;?php echo $itemPrice; ?&gt;" /&gt; &lt;input type="hidden" id="seller_id" value="&lt;?php echo Config::SELLER_ID; ?&gt;" /&gt; &lt;input type="hidden" id="publishable_key" value="&lt;?php echo Config:TongueUBLISHABLE_KEY; ?&gt;" /&gt; &lt;div class="field-row col2 float-left"&gt; &lt;label&gt;Card Holder Name&lt;/label&gt; &lt;input type="text" class="demoInputBox required" name="cardHolderName" id="cardHolderName"&gt; &lt;/div&gt; &lt;div class="field-row col2 float-right"&gt; &lt;label&gt;Email&lt;/label&gt; &lt;input type="email" class="demoInputBox required" name="cardHolderEmail" id="cardHolderEmail"&gt; &lt;/div&gt; &lt;div class="field-row"&gt; &lt;label&gt;Card Number&lt;/label&gt; &lt;input type="text" class="demoInputBox required" name="cardNumber" id="cardNumber"&gt; &lt;/div&gt; &lt;div class="field-row col2 float-left"&gt; &lt;label&gt;Expiry Month / Year&lt;/label&gt; &lt;br /&gt; &lt;select name="expiryMonth" id="expiryMonth" class="demoSelectBox required"&gt; &lt;?php $months = Config::monthArray(); $count = count($months); for ($i = 0; $i &lt; $count; $i ++) { $monthValue = $i + 1; if (strlen($i) &lt; 2) { $monthValue = "0" . $monthValue; } ?&gt; &lt;option value="&lt;?php echo $monthValue; ?&gt;"&gt;&lt;?php echo $months[$i]; ?&gt;&lt;/option&gt; &lt;?php } ?&gt; &lt;/select&gt; &lt;select name="expiryYear" id="expiryYear" class="demoSelectBox required"&gt; &lt;?php for ($i = date("Y"); $i &lt;= 2030; $i ++) { $yearValue = substr($i, 2); ?&gt; &lt;option value="&lt;?php echo $yearValue; ?&gt;"&gt;&lt;?php echo $i; ?&gt;&lt;/option&gt; &lt;?php } ?&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="field-row"&gt; &lt;label&gt;CVV&lt;/label&gt;&lt;br /&gt; &lt;input type="text" name="cvv" id="cvv" class="demoInputBox cvv-input required"&gt; &lt;/div&gt; &lt;p class="sub-head"&gt;Billing Address:&lt;/p&gt; &lt;div class="field-row col2 float-left"&gt; &lt;label&gt;Address Line1&lt;/label&gt; &lt;input type="text" class="demoInputBox required" name="addressLine1" id="addressLine1"&gt; &lt;/div&gt; &lt;div class="field-row col2 float-right"&gt; &lt;label&gt;Address Line2&lt;/label&gt; &lt;input type="email" class="demoInputBox" name="addressLine2" id="addressLine2"&gt; &lt;/div&gt; &lt;div class="field-row col2 float-left"&gt; &lt;label&gt;Country&lt;/label&gt; &lt;input type="text" class="demoInputBox required" name="country" id="country"&gt; &lt;/div&gt; &lt;div class="field-row col2 float-right"&gt; &lt;label&gt;State&lt;/label&gt; &lt;input type="text" class="demoInputBox required" name="state" id="state"&gt; &lt;/div&gt; &lt;div class="field-row col2 float-left"&gt; &lt;label&gt;City&lt;/label&gt; &lt;input type="text" class="demoInputBox required" name="city" id="city"&gt; &lt;/div&gt; &lt;div class="field-row col2 float-right"&gt; &lt;label&gt;Zip&lt;/label&gt; &lt;input type="text" class="demoInputBox required" name="zip" id="zip"&gt; &lt;/div&gt; &lt;div class="clear-float"&gt; &lt;input id="token" name="token" type="hidden" value=""&gt; &lt;input type="button" id="submit-btn" class="btnAction" value="Send Payment"&gt; &lt;div id="loader"&gt; &lt;img alt="loader" src="./images/LoaderIcon.gif" /&gt; &lt;/div&gt; &lt;/div&gt;&lt;div id="error-message"&gt;&lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </pre>
<h4>Javascript for credit card validation</h4>
<p>Most of the fields are mandatory. The form validation script helps to verify user’s input before payment.</p>
<p>I have used the jQuery CreditCardValidator script to validate the card details. It will check the card number format, CVC, card expiration and more.&nbsp;</p>
<p><strong>Note:</strong> To pass the card validation, any three-digit code for CVC and a future date for card expiry.</p>
<pre class="prettyprint lang-php">function validate() { var valid = true; $(".demoInputBox").css('background-color', ''); var message = ""; var cardHolderNameRegex = /^[a-z ,.'-]+$/i; var cvvRegex = /^[0-9]{3,3}$/; var cardHolderName = $("#cardHolderName").val(); var cardHolderEmail = $("#cardHolderEmail").val(); var cardNumber = $("#cardNumber").val(); var cvv = $("#cvv").val(); $(".required").each(function() { if($(this).val()=='') { $(this).css('background-color', '#FFFFDF'); valid = false; } }); if(!valid) { message += "&lt;div&gt; Highlighted fields are required.&lt;/div&gt;"; } if (cardHolderName != "" &amp;&amp; !cardHolderNameRegex.test(cardHolderName)) { message += "&lt;div&gt;Card Holder Name is invalid&lt;/div&gt;"; $("#cardHolderName").css('background-color', '#FFFFDF'); valid = false; } if (!cardHolderEmail.match( /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/)) { message += "&lt;div&gt;Email is invalid&lt;/div&gt;"; $("#cardHolderEmail").css('background-color', '#FFFFDF'); valid = false; } if (cardNumber != "") { $('#cardNumber').validateCreditCard(function(result) { if (!(result.valid)) { message += "&lt;div&gt;Card Number is Invalid&lt;/div&gt;"; $("#card-number").css('background-color', '#FFFFDF'); valid = false; } }); } if (cvv != "" &amp;&amp; !cvvRegex.test(cvv)) { message += "&lt;div&gt;CVV is Invalid&lt;/div&gt;"; $("#cvv").css('background-color', '#FFFFDF'); valid = false; } if (message != "") { $("#error-message").show(); $("#error-message").html(message); $("#submit-btn").show(); $("#loader").hide(); } return valid; } </pre>
<h3>Step 4: 2Checkout JS to request&nbsp;token</h3>
<p>This HTML code contains the <em>2co.js</em>&nbsp;include at the end. This JS script is for getting TCO token by hitting the API’s <em>tokenRequestURL.&nbsp;</em></p>
<p>This request requires card details with seller account id, sandbox publishable key. It also specifies the name of the success/error callback functions.</p>
<p>The success callback gets the token and includes it to the HTML form. f anything went wrong, the error-callback handles the case and acknowledge the customer.</p>
<p>This token helps to authenticate the request before processing the payment. Without this token, the payment request will return error by saying&nbsp;<em>unauthorized.</em></p>
<pre class="prettyprint lang-php">&lt;!-- jQuery library --&gt; &lt;script src="vendor/jquery/jquery-3.2.1.min.js"&gt;&lt;/script&gt; &lt;script src="vendor/jquery-creditcardvalidator/jquery.creditCardValidator.js"&gt;&lt;/script&gt; &lt;script src="./assets/js/validation.js"&gt;&lt;/script&gt; &lt;!-- 2Checkout JavaScript library --&gt; &lt;script src="https://www.2checkout.com/checkout/api/2co.min.js"&gt;&lt;/script&gt; &lt;script&gt; // A success callback of TCO token request var success = function (data) { // Set the token in the payment form $('#paymentForm #token').val(data.response.token.token); $("#error-message").hide(); $("#error-message").html(""); // Submit the form with TCO token $('#paymentForm').submit(); }; // A Error callback of TCO token request. var error = function (data) { var errorMsg = ""; if (data.errorCode === 200) { tokenRequest(); } else { errorMsg = data.errorMsg; $("#error-message").show(); $("#error-message").html(errorMsg); $("#submit-btn").show(); $("#loader").hide(); } }; function tokenRequest() { var valid = validate(); if (valid == true) { $("#submit-btn").hide(); $("#loader").css("display", "inline-block"); var args = { sellerId: $('#seller_id').val(), publishableKey: $('#publishable_key').val(), ccNo: $("#cardNumber").val(), cvv: $("#cvv").val(), expMonth: $("#expiryMonth").val(), expYear: $("#expiryYear").val() }; // Request 2Checkout token TCO.requestToken(success, error, args); } } $(function () { TCO.loadPubKey('sandbox'); $("#submit-btn").on('click', function (e) { tokenRequest(); return false; }); }); &lt;/script&gt; </pre>
<h3>Step 5: Verify card details and process charges with 2Checkout payment API</h3>
<p>After submitting the tokenized form data, then PHP will handle the payment process. There are two major steps during the payment process authorization and charging card.</p>
<p>The payment.php file is the endpoint that verifies payment and charges the card. The below code states how to receive payment form data and request payment.</p>
<p>Before processing payment, this PHP code inserts order into the database table. In this step, it saves the product, currency, customer and billing data into the database.</p>
<p>After placing the order, the&nbsp;<em>inserOrder&nbsp;</em>method will return a unique reference ID. This refers to the&nbsp;<em>merchantOrderId</em> parameter while charging the card.</p>
<p>With a success response, it will update the transaction id and payment status in the order table.</p>
<p>In case of error, the error message returned by the API will acknowledge the customers.</p>
<pre class="prettyprint lang-php">&lt;?php use Phppot\Config; use Phppot\Model\Checkout; session_start(); require_once 'Config.php'; // Check if token is not empty if (! empty($_POST['token'])) { $token = $_POST['token']; $currency = Config::CURRENCY; // Card information $card_num = $_POST['cardNumber']; $card_cvv = $_POST['cvv']; $card_exp_month = $_POST['expiryMonth']; $card_exp_year = $_POST['expiryYear']; // Customer information $customerDetail['name'] = $_POST['cardHolderName']; $customerDetail['email'] = $_POST['cardHolderEmail']; $billingAddress['addrLine1'] = $_POST['addressLine1']; $billingAddress['addrLine2'] = $_POST['addressLine2']; $billingAddress['city'] = $_POST['city']; $billingAddress['state'] = $_POST['state']; $billingAddress['zipCode'] = $_POST['zip']; $billingAddress['country'] = $_POST['country']; // Product information $product['itemNumber'] = $_POST["itemNumber"]; $product['itemPrice'] = $_POST["itemPrice"]; require_once 'Model/Checkout.php'; $checkout = new Checkout(); $orderID = $checkout-&gt;insertOrder($customerDetail, $billingAddress, $product); require_once 'Model/TwoCheckoutService.php'; $twoCheckoutService = new TwoCheckoutService(); $twoCheckoutService-&gt;verifyAuthentication(); $successMessage = ""; $errorMessage = ""; $paymentResponse = $twoCheckoutService-&gt;chargeCard($orderID, $token, $currency, $customerDetail, $billingAddress, $product['itemPrice']); if (! empty($paymentResponse["charge"])) { $charge = $paymentResponse["charge"]; if ($charge['response']['responseCode'] == 'APPROVED') { $transactionId = $charge['response']['transactionId']; $status = $charge['response']['responseCode']; $checkout-&gt;updatePayment($transactionId, $status, $orderID); header("Location: return.php?status=success&amp;itemNumber=".$orderID); } else { $_SESSION["transaction_error"] = "Payment is waiting for approval."; header("Location: return.php?status=transaction_failed"); } } else if($paymentResponse["message"]) { if(!empty($paymentResponse["message"])) { $_SESSION["transaction_error"] = $paymentResponse["message"]; } header("Location: return.php?status=transaction_failed"); } } else { header("Location: return.php?status=invalid_token"); } ?&gt; </pre>
<h4>Model/Checkout.php</h4>
<pre class="prettyprint lang-php">&lt;?php /** * Copyright © 2019 Phppot * * Distributed under MIT license with an exception that, * you don’t have to include the full MIT License in your code. * In essense, you can use it on commercial software, modify and distribute free. * Though not mandatory, you are requested to attribute this URL in your code or website. */ namespace Phppot\Model; use Phppot\DataSource; use Phppot\Config; class Checkout { private $ds; function __construct() { require_once __DIR__ . './../lib/DataSource.php'; $this-&gt;ds = new DataSource(); } /** * to get the member record based on the subscription_key * * @param string $subscriptionKey * @return array result record */ public function getOrder($orderId) { $query = 'SELECT * FROM tbl_order where id = ?'; $paramType = 'i'; $paramValue = array( $orderId ); $result = $this-&gt;ds-&gt;select($query, $paramType, $paramValue); return $result; } public function insertOrder($customerDetail, $billingAddress, $product) { $current_time = date("Y-m-d H:iConfused"); $query = 'INSERT INTO tbl_order (name, email, item_code, item_price, currency, address_line_1, address_line_2, country, state, city, zip, create_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; $paramType = 'sssissssssss'; $paramValue = array( $customerDetail["name"], $customerDetail["email"], $product["itemNumber"], $product["itemPrice"], Config::CURRENCY, $billingAddress['addrLine1'], $billingAddress['addrLine2'], $billingAddress['country'], $billingAddress['state'], $billingAddress['city'], $billingAddress['zipCode'], $current_time ); $insertStatus = $this-&gt;ds-&gt;insert($query, $paramType, $paramValue); return $insertStatus; } public function updatePayment($transactionId, $paymentStatus, $orderID) { $query = "UPDATE tbl_order set txn_id = ?, payment_status = ? WHERE id = ?"; $paramType = 'ssi'; $paramValue = array( $transactionId, $paymentStatus, $orderID ); $this-&gt;ds-&gt;execute($query, $paramType, $paramValue); } } </pre>
<h4>Model/TwoCheckoutService.php</h4>
<pre class="prettyprint lang-php">&lt;?php use Phppot\Config; require_once("vendor/2checkout-php-master/lib/Twocheckout.php"); class TwoCheckoutService { function verifyAuthentication() { Twocheckout::verifySSL(false); // Set API key Twocheckout::privateKey(Config:TongueRIVATE_KEY); // PRIVATE_KEY defined in config.php Twocheckout:ConfusedellerId(Config::SELLER_ID); // SELLER_ID defined in config.php Twocheckout:Confusedandbox(true); } function chargeCard($orderID, $token, $currency, $customerDetail, $billingAddress, $itemPrice) { $successMessage = ""; $errorMessage = ""; try { // an array is created with customer sale parameters and passed it in auth() function of Twocheckout_Charge class for authorization. $charge = Twocheckout_Charge::auth(array( "merchantOrderId" =&gt; $orderID, "token" =&gt; $token, "currency" =&gt; $currency, "total" =&gt; $itemPrice, "billingAddr" =&gt; array( "name" =&gt; $customerDetail['name'], "addrLine1" =&gt; $billingAddress['addrLine1'], "city" =&gt; $billingAddress['city'], "state" =&gt; $billingAddress['state'], "zipCode" =&gt; $billingAddress['zipCode'], "country" =&gt; $billingAddress['country'], "email" =&gt; $customerDetail['email'] ) )); $paymentResponse = array( "message" =&gt; "", "charge" =&gt; $charge ); } catch (Twocheckout_Error $e) { $paymentResponse = array( "message" =&gt; $e-&gt;getMessage(), "charge" =&gt; "" ); } return $paymentResponse; } } </pre>
<h4>Config.php</h4>
<pre class="prettyprint lang-php">&lt;?php namespace Phppot; class Config { const CURRENCY = 'USD'; const SELLER_ID = ''; const PUBLISHABLE_KEY = ''; const PRIVATE_KEY = ''; public function productDetail() { $product = array( 'WWPS235' =&gt; array( "itemName" =&gt; 'Kindle Paperwhite (10th gen) - 6" 8GB, WiFi', 'itemPrice' =&gt; '130.00' ) ); return $product; } public function monthArray() { $months = array( 'January', 'February', 'March', 'April', 'May', 'June', 'July ', 'August', 'September', 'October', 'November', 'December' ); return $months; } } </pre>
<h2 id="database-script">Database script</h2>
<p>This is a SQL with the CREATE statement of the tbl_order table. Import this script for your PHP environment to run this example.</p>
<pre class="prettyprint lang-php">-- -- Table structure for table `tbl_order` -- CREATE TABLE `tbl_order` ( `id` int(11) NOT NULL, `name` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `item_code` varchar(25) COLLATE utf8_unicode_ci NOT NULL, `item_price` float(10,2) NOT NULL, `currency` varchar(10) COLLATE utf8_unicode_ci NOT NULL, `address_line_1` text COLLATE utf8_unicode_ci NOT NULL, `address_line_2` text COLLATE utf8_unicode_ci NOT NULL, `country` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `city` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `state` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `zip` 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, `create_at` datetime NOT NULL, `edit_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ); ALTER TABLE `tbl_order` ADD PRIMARY KEY (`id`); ALTER TABLE `tbl_order` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=110; </pre>
<h2 id="go-live">Go Live</h2>
<p>After testing the payment flow in the Sandbox mode, we can move to production mode.</p>
<p>To go live, change the mode from&nbsp;<em>sandbox</em>&nbsp;to <em>production</em> in the following line.</p>
<pre class="prettyprint lang-php">TCO.loadPubKey('production');</pre>
<p>Replace all the test API keys with the live keys in the application config. Also, disable the sandbox mode by setting it as&nbsp;<em>false</em>&nbsp;as shown below.</p>
<pre class="prettyprint lang-php">Twocheckout::privateKey('production-private-key'); Twocheckout:ConfusedellerId('production-seller-id'); Twocheckout:Confusedandbox(false); </pre>
<h2 id="2checkout-payment-form-output">2Checkout Payment Form Output</h2>
<p>The below screenshot shows the 2Checkout payment form. Most of the form fields are mandatory and so validated by JavaScript before payment.</p>
<p>The product name and price above the form are from the config. We can link your product database to display this information.</p>
<p><img class="alignnone size-large wp-image-10735" src="https://phppot.com/wp-content/uploads/2019/11/2checkout-payment-form-output-550x699.jpg" alt="2Checkout Payment Form Output" width="550" height="699" srcset="https://phppot.com/wp-content/uploads/2019/11/2checkout-payment-form-output-550x699.jpg 550w, https://phppot.com/wp-content/uploads/20...36x300.jpg 236w, https://phppot.com/wp-content/uploads/20...68x977.jpg 768w, https://phppot.com/wp-content/uploads/20...output.jpg 1082w" sizes="(max-width: 550px) 100vw, 550px"></p>
<p>This screenshot shows the success response. The table shown in this screenshot has the basic details about the order placed.</p>
<p><img class="alignnone size-full wp-image-10754" src="https://phppot.com/wp-content/uploads/2019/11/2checkout-success-response.jpg" alt="2Checkout Success Response" width="500" height="292" srcset="https://phppot.com/wp-content/uploads/2019/11/2checkout-success-response.jpg 500w, https://phppot.com/wp-content/uploads/20...00x175.jpg 300w" sizes="(max-width: 500px) 100vw, 500px"></p>
<p><a class="download" href="https://phppot.com/downloads/how-to-integrate-2checkout-payment-gateway-using-php.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/how-to-integrate-2checkout-payment-gateway-using-php/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2019/11/...using-php/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016