PHPackages                             bamz3r/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. [Payment Processing](/categories/payments)
4. /
5. bamz3r/veritrans-php

ActiveLibrary[Payment Processing](/categories/payments)

bamz3r/veritrans-php
====================

PHP Wrapper for Veritrans VT-Web Payment API. PSR-4 compatible and fix some bugs

1.0.1(11y ago)013GPL-3.0PHPPHP &gt;=5.3.0

Since Nov 3Pushed 8y ago1 watchersCompare

[ Source](https://github.com/bamz3r/veritrans-php)[ Packagist](https://packagist.org/packages/bamz3r/veritrans-php)[ Docs](https://veritrans.co.id)[ RSS](/packages/bamz3r-veritrans-php/feed)WikiDiscussions master Synced 2w ago

READMEChangelogDependencies (1)Versions (7)Used By (0)

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

[](#veritrans-php)

Enchanced version feature:

- Compatible with PSR-4 autoload
- Fix some bug

If you want to use my version first remove the original of veritrans/veritrans-php and then add bamz3r/veritrans-php to your composer.json:

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

and run `composer install` on your terminal.

Original README:

[![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](https://snap-docs.midtrans.com/) - Customizable payment popup will appear on **your web/app** (no redirection)
- [VT-Web](https://docs.midtrans.com/en/vtweb/integration.html) - Customer need to be redirected to payment url **hosted by midtrans**
- [Core API (VT-Direct)](https://api-docs.midtrans.com/) - Basic backend implementation, you can customize the frontend embedded on **your web/app** as you like (no redirection)

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);
```

#### 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)

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();
}
```

#### 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 VT-Direct examples [here](examples/vt-direct).

#### Set Client Key

[](#set-client-key)

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

#### Checkout Page

[](#checkout-page)

```

  Checkout

  Checkout

      Checkout

        Card Number

        Expiration (MM/YYYY)

         /

        CVV

        Save credit card

      Submit Payment

    $(function () {
      // Sandbox URL
      Veritrans.url = "https://api.sandbox.midtrans.com/v2/token";
      // TODO: Change with your client key.
      Veritrans.client_key = "";
      var card = function () {
        return {
          "card_number": $(".card-number").val(),
          "card_exp_month": $(".card-expiry-month").val(),
          "card_exp_year": $(".card-expiry-year").val(),
          "card_cvv": $(".card-cvv").val(),
          "secure": false,
          "gross_amount": 200000
        }
      };

      function callback(response) {
        console.log(response);
        if (response.redirect_url) {
          console.log("3D SECURE");
          // 3D Secure transaction, please open this popup
          openDialog(response.redirect_url);

        }
        else if (response.status_code == "200") {
          console.log("NOT 3-D SECURE");
          // Success 3-D Secure or success normal
          closeDialog();
          // Submit form
          $("#token_id").val(response.token_id);
          $("#payment-form").submit();
        }
        else {
          // Failed request token
          console.log(response.status_code);
          alert(response.status_message);
        }
      }

      function openDialog(url) {
        $.fancybox.open({
          href: url,
          type: "iframe",
          autoSize: false,
          width: 700,
          height: 500,
          closeBtn: false,
          modal: true
        });
      }

      function closeDialog() {
        $.fancybox.close();
      }

      $(".submit-button").click(function (event) {
        console.log("SUBMIT");
        event.preventDefault();
        $(this).attr("disabled", "disabled");
        Veritrans.token(card, callback);
        return false;
      });
    });

```

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

28

—

LowBetter than 52% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity5

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor4

4 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 ~87 days

Total

2

Last Release

4085d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1755003?v=4)[Bambang Riswanto](/maintainers/bamz3r)[@bamz3r](https://github.com/bamz3r)

---

Top Contributors

[![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)")[![rizdaprasetya](https://avatars.githubusercontent.com/u/13027142?v=4)](https://github.com/rizdaprasetya "rizdaprasetya (11 commits)")[![ismailfaruqi](https://avatars.githubusercontent.com/u/1243576?v=4)](https://github.com/ismailfaruqi "ismailfaruqi (9 commits)")[![bamz3r](https://avatars.githubusercontent.com/u/1755003?v=4)](https://github.com/bamz3r "bamz3r (7 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)")[![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)")

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[omnipay/coinbase

Coinbase driver for the Omnipay payment processing library

18570.2k1](/packages/omnipay-coinbase)

PHPackages © 2026

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