Credit card payments are becoming more and more popular in the e-commerce market

This tutorial will help you to understand the mechanism of this type of payment and help you implement it correctly on your own website. This method can also be used to save a customer card by generating a token that will later bind the credit card to the merchant account and allow payment without having to re-enter the data.

The mechanism of card payment with redirection to Tpay gateway

  1. First of all, you should add the option of choosing a card payment method for your clients by, for example, displaying an additional "Quick card payment" button, e.g.

    At this stage, we assume that the store should already have customer data such as name and email and payment details - the amount and currency of the order.
  2. Then, the transaction link is generated in the background, so the customer will can be redirected to payment (automatically or after clicking the button).
    This method can also be used to automatically send transaction links to customers who do not visit our store, but only to pay a fee.
  3. Tpay.com provides ready programming libraries in PHP that support the process of generating transactions automatically and do not require a lot of developers' work. All you need to do is adjust the ready files to your needs.
  4. In the Tpay transaction panel, the customer enters his card details and approves the payment.
  5. After successful payment, the customer will be redirected to the store's success page. In case of failure, the client should be able to re-pay by redirecting to the same link from the failure page or by generating a new one. Once generated, the link can be used until the transaction is paid correctly.
  6. The notification of payment will be sent to the store's address, configured in the seller's account settings.

Technical explanation of card payment with redirection

  1. The card transaction is carried out by sending an API request. Access data such as a key, password and verification code are required to start the integration and should be generated in accordance with the instruction.
  2. The second step is to call the register_sale, method, which is used to send the necessary data to the Tpay server.
    To generate transactions we recommend the ready to use PHP library as in this example. The mentioned example will redirect you to the Tpay transaction panel. You only need to complete the amount, currency and customer data depending on your solution - eg download from the database.

    An example of this method can be found on the GitHub site in the PHP tpay-com PHP library, and you can also do a test call by clicking "Try" in the documentation.
    The minimum set of parameters to be sent in this method is:
    {
      "name": "john doe",
      "email": "[email protected]",
      "desc": "payment for order xyz",
      "amount": 10.99,
      "api_password": "XtCns9OAue8zSFJ",
      "sign": "25bd2eb0bd6e6ad2c570bcf9ecb2156b35d31dff",
      "currency": 985
    }​

    The additional "onetimer" parameter decides about saving the payment card. If this method is not to be used to memorize the credit card you should always send the "onetimer" parameter. If you wish to do so, this method can be used to implement recursive payments. The generated token will be returned in the "cli_auth" parameter in the system notification.

  3. The result of the query returns the "sale_auth" parameter, which is the generated transaction identifier to which the payer should be redirected.
  4. After successful payment confirmation by the client, an asynchronous payment notification will be sent to the shop result address (defined in the account settings), just like in the case of bank transfers.
    Read the documentation describing card transaction notifications. On github.com, we've provided the ready to use example that automatically verifies the notification and returns its validated content.
  5. The URL to which the payer will be redirected after payment confirmation can be defined statically in the seller's account settings or sent dynamically in the appropriate parameters.

Example of implementation based on PHP Tpay libraries

  1. Download Tpay libraries from Github.com
  2. Create a file (eg in the examples folder) extending the PaymentCardForms class, in which the constructor should provide its access data to the payment card API:
    <?php
    
    namespace tpayLibs\examples;
    
    use tpayLibs\src\_class_tpay\PaymentForms\PaymentCardForms;
    use tpayLibs\src\_class_tpay\Utilities\TException;
    
    include_once 'config.php';
    include_once 'loader.php';
    
    class CardBasic extends PaymentCardForms
    {
        public function __construct()
        {
            $this->cardApiKey = 'bda5eda723bf1ae71a82e90a249803d3f852248d';
            $this->cardApiPass = 'IhZVgraNcZoWPLgA';
            $this->cardKeyRSA = 'LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0NCk1JR2ZNQTBHQ1NxR1NJYjNEUUVCQVFVQUE0R05BRENCaVFLQmdRQ2NLRTVZNU1Wemd5a1Z5ODNMS1NTTFlEMEVrU2xadTRVZm1STS8NCmM5L0NtMENuVDM2ekU0L2dMRzBSYzQwODRHNmIzU3l5NVpvZ1kwQXFOVU5vUEptUUZGVyswdXJacU8yNFRCQkxCcU10TTVYSllDaVQNCmVpNkx3RUIyNnpPOFZocW9SK0tiRS92K1l1YlFhNGQ0cWtHU0IzeHBhSUJncllrT2o0aFJDOXk0WXdJREFRQUINCi0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQ';
            $this->cardVerificationCode = '6680181602d396e640cb091ea5418171';
            $this->cardHashAlg = 'sha1';
            parent::__construct();
        }
    }​
  3. Add the function which generates a transaction and redirects your customer to Tpay transaction panel:
    public function getRedirectTransaction()
    {
        try {
            $config = [
                'name' => 'John Doe',
                'email' => '[email protected]',
                'desc' => 'Transaction description',
            ];
            $this
                ->setAmount(123.00)
                ->setCurrency(985)
                ->setReturnUrls('https://shop.com/success', 'https://shop.com/error');
            $transaction =  $this->registerSale($config['name'], $config['email'], $config['desc']);
            if (isset($transaction['sale_auth']) === false) {
                throw new TException('Error generating transaction: ' . $transaction['err_desc']);
            }
            $transactionId = $transaction['sale_auth'];
            header("Location: https://secure.tpay.com/cards/?sale_auth=$transactionId");
        } catch (TException $e) {
            echo 'Unable to generate transaction. Reason: ' . $e->getMessage();
        }
    }

    Some data should be downloaded from your database. In this tutorial, we have provided an example values (amount, currency etc.).

  4. Executing MakeCardPayment() function returns a result, containing "sale_auth" parameter, to which is made redirection.
    Example set of parameters returned from API call:
    $transaction = [
      'result' => '1',
      'sale_auth' => 't59c28295aeb071b0cf6471b24f727f6456998de',
    ];​
  5. This class can be run by adding this simple line:
    (new CardBasic())->getRedirectTransaction();
  6. Remember that a notification of correct payment will be sent to your store only after the transaction has been finalized.
    To receive such a notification, create a CardNotification.php file that extends the CardNotificationHandler class. In the merchant configuration panel, enter the URL address leading to this file in accordance with the documentation.
    Add the constructor of the new class:
    <?php
    
    namespace tpayLibs\examples;
    
    use tpayLibs\src\_class_tpay\Notifications\CardNotificationHandler;
    
    include_once 'config.php';
    include_once 'loader.php';
    
    class CardNotification extends CardNotificationHandler
    {
        public function __construct()
        {
            $this->cardApiKey = 'bda5eda723bf1ae71a82e90a249803d3f852248d';
            $this->cardApiPass = 'IhZVgraNcZoWPLgA';
            $this->cardKeyRSA = 'LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0NCk1JR2ZNQTBHQ1NxR1NJYjNEUUVCQVFVQUE0R05BRENCaVFLQmdRQ2NLRTVZNU1Wemd5a1Z5ODNMS1NTTFlEMEVrU2xadTRVZm1STS8NCmM5L0NtMENuVDM2ekU0L2dMRzBSYzQwODRHNmIzU3l5NVpvZ1kwQXFOVU5vUEptUUZGVyswdXJacU8yNFRCQkxCcU10TTVYSllDaVQNCmVpNkx3RUIyNnpPOFZocW9SK0tiRS92K1l1YlFhNGQ0cWtHU0IzeHBhSUJncllrT2o0aFJDOXk0WXdJREFRQUINCi0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQ';
            $this->cardVerificationCode = '6680181602d396e640cb091ea5418171';
            $this->cardHashAlg = 'sha1';
            parent::__construct();
        }
    
    }​
  7. Then add the function call checking the system notification (built into the Tpay library) and the function getOrderDetailsFromDatabase, which will return the amount and currency of the order stored in the database for the validation purpose of the notification:
    private function getTpayNotification()
    {
        //If you want to disable Tpay server IP address checking, execute this command:
        $this->disableValidationServerIP();
        //If you use a proxy, run this command to check the IP address in the HTTP_X_FORWARDED_FOR array:
        $this->enableForwardedIPValidation();
    
        $notification =  $this->handleNotification();
        //Download order details from the store database
        $shopOrderData = $this->getOrderDetailsFromDatabase($notification['order_id']);
        //Check the validity of the notification signature
        $this
            ->setAmount($shopOrderData['amount'])
            ->setCurrency($shopOrderData['currency'])
            ->setOrderID($notification['order_id']);
        $this->validateCardSign($notification['sign'], $notification['sale_auth'],
            $notification['card'], $notification['date'], $notification['status']);
    
        return $notification;
    }​
    private function getOrderDetailsFromDatabase($orderId)
    {
        //Code downloading of order details from the store database based on OrderId
        //Example data returned from function:
        return [
            'amount' => 123.00,
            'currency' => 985,
        ];
    }
  8. Add the init() class control function and your own setOrderAsConfirmed() function, which based on the returned data will mark the order as paid and save useful data - e.g. a returned client token (cli_auth) and a transaction title (sale_auth).
    public function init()
    {
        $notification = $this->getTpayNotification();
        if (isset($notification['status']) && $notification['status'] === 'correct') {
            $this->setOrderAsConfirmed($notification);
        }
    }​

    The $notification variable will contain an array of data described in documentation.

  9. Add class call at the end of file:
    (new CardNotification())->init();​