PHPackages                             hengky-sandy/veritrans-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. hengky-sandy/veritrans-php

ActiveLibrary

hengky-sandy/veritrans-php
==========================

PHP Wraper for Veritrans VT-Web Payment API.

1.6.0(7y ago)0174GPL-3.0PHPPHP &gt;=5.4

Since Nov 3Pushed 7y agoCompare

[ Source](https://github.com/hengky-sandy/veritrans-php)[ Packagist](https://packagist.org/packages/hengky-sandy/veritrans-php)[ Docs](https://midtrans.com)[ RSS](/packages/hengky-sandy-veritrans-php/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)Dependencies (2)Versions (12)Used By (0)

Veritrans-PHP
=============

[](#veritrans-php)

[![Build Status](https://camo.githubusercontent.com/f588c86dc1c081d114c37da473bb40958ce8ad2d76cdbf088e7593ebdb0fb29f/68747470733a2f2f7472617669732d63692e6f72672f766572697472616e732f766572697472616e732d7068702e737667)](https://travis-ci.org/veritrans/veritrans-php)

Veritrans is now ➡️ [Midtrans](https://midtrans.com)

Midtrans ❤️ PHP!

This is the Official PHP wrapper/library for Midtrans Payment API. Visit  for more information about the product and see documentation at [http://docs.midtrans.com](http://docs.midtrans) for more technical details.

1. Installation
---------------

[](#1-installation)

### 1.a Composer Installation

[](#1a-composer-installation)

If you are using [Composer](https://getcomposer.org), add this require line to your `composer.json` file:

```
{
	"require": {
		"veritrans/veritrans-php": "dev-master"
	}
}
```

and run `composer install` on your terminal.

### 1.b Manual Instalation

[](#1b-manual-instalation)

If you are not using Composer, you can clone or [download](https://github.com/veritrans/veritrans-php/archive/master.zip) this repository.

2. How to Use
-------------

[](#2-how-to-use)

### 2.1 General Settings

[](#21-general-settings)

```
// Set your Merchant Server Key
Veritrans_Config::$serverKey = '';
// Set to Development/Sandbox Environment (default). Set to true for Production Environment (accept real transaction).
Veritrans_Config::$isProduction = false;
// Set sanitization on (default)
Veritrans_Config::$isSanitized = true;
// Set 3DS transaction for credit card to true
Veritrans_Config::$is3ds = true;
```

### 2.2 Choose Product/Method

[](#22-choose-productmethod)

We have [3 different products](https://docs.midtrans.com/en/welcome/index.html) of payment that you can use:

- [Snap](#22a-snap) - Customizable payment popup will appear on **your web/app** (no redirection). [doc ref](https://snap-docs.midtrans.com/)
- [Snap Redirect](#22b-snap-redirect) - Customer need to be redirected to payment url **hosted by midtrans**. [doc ref](https://snap-docs.midtrans.com/)
- [Core API (VT-Direct)](#22c-core-api-vt-direct) - Basic backend implementation, you can customize the frontend embedded on **your web/app** as you like (no redirection). [doc ref](https://api-docs.midtrans.com/)

Choose one that you think best for your unique needs.

### 2.2.a Snap

[](#22a-snap)

You can see Snap example [here](examples/snap).

#### Get Snap Token

[](#get-snap-token)

```
$params = array(
    'transaction_details' => array(
      'order_id' => rand(),
      'gross_amount' => 10000,
    )
  );

$snapToken = Veritrans_Snap::getSnapToken($params);
```

#### Get Snap Token in Yii2

[](#get-snap-token-in-yii2)

```

    //install library from composer
    //in your controller no need to include anything
    //make sure call class with \Class_name::method()

    public function actionSnapToken() {

        \Veritrans_Config::$serverKey = 'Secret Server Key Goes Here';
        // Set to Development/Sandbox Environment (default). Set to true for Production Environment (accept real transaction).
        \Veritrans_Config::$isProduction = false;
        // Set sanitization on (default)
        \Veritrans_Config::$isSanitized = true;
        // Set 3DS transaction for credit card to true
        \Veritrans_Config::$is3ds = true;

        $complete_request = [
            "transaction_details" => [
                "order_id" => "1234",
                "gross_amount" => 10000
            ]
        ];

        $snap_token = \Veritrans_Snap::getSnapToken($complete_request);
        return ['snap_token' => $snap_token];

    }
```

#### Initialize Snap JS when customer click pay button

[](#initialize-snap-js-when-customer-click-pay-button)

```

    Pay!
    JSON result will appear here after payment:

      document.getElementById('pay-button').onclick = function(){
        // SnapToken acquired from previous step
        snap.pay('', {
          // Optional
          onSuccess: function(result){
            /* You may add your own js here, this is just example */ document.getElementById('result-json').innerHTML += JSON.stringify(result, null, 2);
          },
          // Optional
          onPending: function(result){
            /* You may add your own js here, this is just example */ document.getElementById('result-json').innerHTML += JSON.stringify(result, null, 2);
          },
          // Optional
          onError: function(result){
            /* You may add your own js here, this is just example */ document.getElementById('result-json').innerHTML += JSON.stringify(result, null, 2);
          }
        });
      };

```

#### Implement Notification Handler

[](#implement-notification-handler)

[Refer to this section](#23-handle-http-notification)

### 2.2.b VT-Web

[](#22b-vt-web)

> !!! VT-Web is DEPRECATED !!!

> Please use [Snap Redirect](#22b-snap-redirect), it has the same functionality, but better. [Refer to this section](#22b-snap-redirect)

You can see some VT-Web examples [here](examples/vt-web).

#### Get Redirection URL of a Charge

[](#get-redirection-url-of-a-charge)

```
$params = array(
    'transaction_details' => array(
      'order_id' => rand(),
      'gross_amount' => 10000,
    ),
    'vtweb' => array()
  );

try {
  // Redirect to Veritrans VTWeb page
  header('Location: ' . Veritrans_Vtweb::getRedirectionUrl($params));
}
catch (Exception $e) {
  echo $e->getMessage();
}
```

### 2.2.b Snap Redirect

[](#22b-snap-redirect)

You can see some Snap Redirect examples [here](examples/snap-redirect).

#### Get Redirection URL of a Payment Page

[](#get-redirection-url-of-a-payment-page)

```
$params = array(
    'transaction_details' => array(
      'order_id' => rand(),
      'gross_amount' => 10000,
    ),
    'vtweb' => array()
  );

try {
  // Get Snap Payment Page URL
  $paymentUrl = Veritrans_Snap::createTransaction($params)->redirect_url;

  // Redirect to Snap Payment Page
  header('Location: ' . $paymentUrl);
}
catch (Exception $e) {
  echo $e->getMessage();
}
```

#### Implement Notification Handler

[](#implement-notification-handler-1)

[Refer to this section](#23-handle-http-notification)

### 2.2.c Core API (VT-Direct)

[](#22c-core-api-vt-direct)

You can see some Core API examples [here](examples/core-api).

#### Set Client Key

[](#set-client-key)

```
Veritrans.client_key = "";
```

#### Checkout Page

[](#checkout-page)

Please refer to [this file](examples/core-api/checkout.php)

#### Checkout Process

[](#checkout-process)

##### 1. Create Transaction Details

[](#1-create-transaction-details)

```
$transaction_details = array(
  'order_id'    => time(),
  'gross_amount'  => 200000
);
```

##### 2. Create Item Details, Billing Address, Shipping Address, and Customer Details (Optional)

[](#2-create-item-details-billing-address-shipping-address-and-customer-details-optional)

```
// Populate items
$items = array(
    array(
      'id'       => 'item1',
      'price'    => 100000,
      'quantity' => 1,
      'name'     => 'Adidas f50'
    ),
    array(
      'id'       => 'item2',
      'price'    => 50000,
      'quantity' => 2,
      'name'     => 'Nike N90'
    ));

// Populate customer's billing address
$billing_address = array(
    'first_name'   => "Andri",
    'last_name'    => "Setiawan",
    'address'      => "Karet Belakang 15A, Setiabudi.",
    'city'         => "Jakarta",
    'postal_code'  => "51161",
    'phone'        => "081322311801",
    'country_code' => 'IDN'
  );

// Populate customer's shipping address
$shipping_address = array(
    'first_name'   => "John",
    'last_name'    => "Watson",
    'address'      => "Bakerstreet 221B.",
    'city'         => "Jakarta",
    'postal_code'  => "51162",
    'phone'        => "081322311801",
    'country_code' => 'IDN'
  );

// Populate customer's info
$customer_details = array(
    'first_name'       => "Andri",
    'last_name'        => "Setiawan",
    'email'            => "test@test.com",
    'phone'            => "081322311801",
    'billing_address'  => $billing_address,
    'shipping_address' => $shipping_address
  );
```

##### 3. Get Token ID from Checkout Page

[](#3-get-token-id-from-checkout-page)

```
// Token ID from checkout page
$token_id = $_POST['token_id'];
```

##### 4. Create Transaction Data

[](#4-create-transaction-data)

```
// Transaction data to be sent
$transaction_data = array(
    'payment_type' => 'credit_card',
    'credit_card'  => array(
      'token_id'      => $token_id,
      'bank'          => 'bni',
      'save_token_id' => isset($_POST['save_cc'])
    ),
    'transaction_details' => $transaction_details,
    'item_details'        => $items,
    'customer_details'    => $customer_details
  );
```

##### 5. Charge

[](#5-charge)

```
$response = Veritrans_VtDirect::charge($transaction_data);
```

##### 6. Handle Transaction Status

[](#6-handle-transaction-status)

```
// Success
if($response->transaction_status == 'capture') {
  echo "Transaksi berhasil.";
  echo "Status transaksi untuk order id $response->order_id: " .
      "$response->transaction_status";

  echo "Detail transaksi:";
  echo "";
  var_dump($response);
  echo "";
}
// Deny
else if($response->transaction_status == 'deny') {
  echo "Transaksi ditolak.";
  echo "Status transaksi untuk order id .$response->order_id: " .
      "$response->transaction_status";

  echo "Detail transaksi:";
  echo "";
  var_dump($response);
  echo "";
}
// Challenge
else if($response->transaction_status == 'challenge') {
  echo "Transaksi challenge.";
  echo "Status transaksi untuk order id $response->order_id: " .
      "$response->transaction_status";

  echo "Detail transaksi:";
  echo "";
  var_dump($response);
  echo "";
}
// Error
else {
  echo "Terjadi kesalahan pada data transaksi yang dikirim.";
  echo "Status message: [$response->status_code] " .
      "$response->status_message";

  echo "";
  var_dump($response);
  echo "";
}
```

#### 7. Implement Notification Handler

[](#7-implement-notification-handler)

[Refer to this section](#23-handle-http-notification)

### 2.3 Handle HTTP Notification

[](#23-handle-http-notification)

Create separated web endpoint (notification url) to receive HTTP POST notification callback/webhook. HTTP notification will be sent whenever transaction status is changed. Example also available [here](examples/notification-handler.php)

```
$notif = new Veritrans_Notification();

$transaction = $notif->transaction_status;
$fraud = $notif->fraud_status;

error_log("Order ID $notif->order_id: "."transaction status = $transaction, fraud staus = $fraud");

  if ($transaction == 'capture') {
    if ($fraud == 'challenge') {
      // TODO Set payment status in merchant's database to 'challenge'
    }
    else if ($fraud == 'accept') {
      // TODO Set payment status in merchant's database to 'success'
    }
  }
  else if ($transaction == 'cancel') {
    if ($fraud == 'challenge') {
      // TODO Set payment status in merchant's database to 'failure'
    }
    else if ($fraud == 'accept') {
      // TODO Set payment status in merchant's database to 'failure'
    }
  }
  else if ($transaction == 'deny') {
      // TODO Set payment status in merchant's database to 'failure'
  }
}
```

### 2.4 Process Transaction

[](#24-process-transaction)

#### Get Transaction Status

[](#get-transaction-status)

```
$status = Veritrans_Transaction::status($orderId);
var_dump($status);
```

#### Approve Transaction

[](#approve-transaction)

If transaction fraud\_status == [CHALLENGE](https://support.midtrans.com/hc/en-us/articles/202710750-What-does-CHALLENGE-status-mean-What-should-I-do-if-there-is-a-CHALLENGE-transaction-), you can approve the transaction from Merchant Dashboard, or API :

```
$approve = Veritrans_Transaction::approve($orderId);
var_dump($approve);
```

#### Cancel Transaction

[](#cancel-transaction)

You can Cancel transaction with `fraud_status == CHALLENGE`, or credit card transaction with `transaction_status == CAPTURE` (before it become SETTLEMENT)

```
$cancel = Veritrans_Transaction::cancel($orderId);
var_dump($cancel);
```

#### Expire Transaction

[](#expire-transaction)

You can Expire transaction with `transaction_status == PENDING` (before it become SETTLEMENT or EXPIRE)

```
$cancel = Veritrans_Transaction::cancel($orderId);
var_dump($cancel);
```

Contributing
------------

[](#contributing)

### Developing e-commerce plug-ins

[](#developing-e-commerce-plug-ins)

There are several guides that must be taken care of when you develop new plugins.

1. **Handling currency other than IDR.** Veritrans `v1` and `v2` currently accepts payments in Indonesian Rupiah only. As a corrolary, there is a validation on the server to check whether the item prices are in integer or not. As much as you are tempted to round-off the price, DO NOT do that! Always prepare when your system uses currencies other than IDR, convert them to IDR accordingly, and only round the price AFTER that.
2. Consider using the **auto-sanitization** feature.

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor3

3 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~383 days

Total

5

Last Release

2588d ago

PHP version history (2 changes)1.0.0PHP &gt;=5.3.0

1.2.0PHP &gt;=5.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/af97934fddf791ab2571a1e1fa06f43693d74d4bb085e5e11babf349cd93b32d?d=identicon)[hengky-sandy](/maintainers/hengky-sandy)

---

Top Contributors

[![rizdaprasetya](https://avatars.githubusercontent.com/u/13027142?v=4)](https://github.com/rizdaprasetya "rizdaprasetya (44 commits)")[![Paxa](https://avatars.githubusercontent.com/u/26019?v=4)](https://github.com/Paxa "Paxa (21 commits)")[![yocki-s](https://avatars.githubusercontent.com/u/6572247?v=4)](https://github.com/yocki-s "yocki-s (19 commits)")[![danieljl](https://avatars.githubusercontent.com/u/1947204?v=4)](https://github.com/danieljl "danieljl (17 commits)")[![robeth](https://avatars.githubusercontent.com/u/1451171?v=4)](https://github.com/robeth "robeth (16 commits)")[![harrypujianto](https://avatars.githubusercontent.com/u/9349240?v=4)](https://github.com/harrypujianto "harrypujianto (14 commits)")[![ismailfaruqi](https://avatars.githubusercontent.com/u/1243576?v=4)](https://github.com/ismailfaruqi "ismailfaruqi (9 commits)")[![hengky-sandy](https://avatars.githubusercontent.com/u/43033829?v=4)](https://github.com/hengky-sandy "hengky-sandy (6 commits)")[![niteshpawar](https://avatars.githubusercontent.com/u/1705764?v=4)](https://github.com/niteshpawar "niteshpawar (3 commits)")[![mul14](https://avatars.githubusercontent.com/u/113989?v=4)](https://github.com/mul14 "mul14 (2 commits)")[![alvinlitani](https://avatars.githubusercontent.com/u/5961507?v=4)](https://github.com/alvinlitani "alvinlitani (2 commits)")[![davidsuryaputra](https://avatars.githubusercontent.com/u/20022496?v=4)](https://github.com/davidsuryaputra "davidsuryaputra (2 commits)")[![hafizh-vt](https://avatars.githubusercontent.com/u/13637010?v=4)](https://github.com/hafizh-vt "hafizh-vt (2 commits)")[![wendy0402](https://avatars.githubusercontent.com/u/4647969?v=4)](https://github.com/wendy0402 "wendy0402 (2 commits)")[![adisetiawan](https://avatars.githubusercontent.com/u/73311?v=4)](https://github.com/adisetiawan "adisetiawan (1 commits)")[![shaddiqa](https://avatars.githubusercontent.com/u/3852646?v=4)](https://github.com/shaddiqa "shaddiqa (1 commits)")[![jrean](https://avatars.githubusercontent.com/u/5646128?v=4)](https://github.com/jrean "jrean (1 commits)")[![pascalalfadian](https://avatars.githubusercontent.com/u/5976057?v=4)](https://github.com/pascalalfadian "pascalalfadian (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/hengky-sandy-veritrans-php/health.svg)

```
[![Health](https://phpackages.com/badges/hengky-sandy-veritrans-php/health.svg)](https://phpackages.com/packages/hengky-sandy-veritrans-php)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
