Giter Site home page Giter Site logo

veritrans-laravel5's Introduction

Veritrans Laravel library

Veritrans ❤️ Laravel!

This is the all new Laravel client library for Veritrans 2.0. Visit https://www.veritrans.co.id for more information about the product and see documentation at http://docs.veritrans.co.id for more technical details.

Requirements

The following plugin is tested under following environment:

  • PHP v5.4.x or greater
  • Laravel 5

Installation

  • Download the library and extract the .zip
  • Merge all the files.
  • install from composer (Soon :) )

Using Veritrans Library

Use Veritrans Class

Add this following line in your controller
//before 
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class YourController extends Controller
{
...

// after 
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Veritrans\Veritrans;

class YourController extends Controller
{
...
Add/Edit this following line in your __construct() function
//set $isproduction to true for prodution environment
//before 
class YourController extends Controller
{

...

// after 
use App\Veritrans\Veritrans;
class YourController extends Controller
{
    public function __construct(){   
        Veritrans::$serverKey = 'your-server-key';
        Veritrans::$isProduction = false;
    }
...

SNAP

You can see how to get snap token by reading the controller here.

Get Snap Token

public function token() 
    {
        error_log('masuk ke snap token adri ajax');
        $midtrans = new Midtrans;
        $transaction_details = array(
            'order_id'          => uniqid(),
            'gross_amount'  => 200000
        );
        // Populate items
        $items = [
            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'                     => "[email protected]",
            'phone'                     => "081322311801",
            'billing_address' => $billing_address,
            'shipping_address'=> $shipping_address
            );
        // Data yang akan dikirim untuk request redirect_url.
        $transaction_data = array(
            'transaction_details'=> $transaction_details,
            'item_details'           => $items,
            'customer_details'   => $customer_details
        );
    
        try
        {
            $snap_token = $midtrans->getSnapToken($transaction_data);
            //return redirect($vtweb_url);
            echo $snap_token;
        } 
        catch (Exception $e) 
        {   
            return $e->getMessage;
        }
    }

SNAP UI

In this section you could see the code, how to get snap token with ajax and open the snap pop up on the page. Please refer here

For sandbox use https://app.sandbox.midtrans.com/snap/snap.js For production use https://app.midtrans.com/snap/snap.js

<html>
<title>Checkout</title>
  <head>
    <script type="text/javascript"
            src="https://app.sandbox.midtrans.com/snap/snap.js"
            data-client-key="<CLIENT-KEY>"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  </head>
  <body>

    
    <form id="payment-form" method="post" action="snapfinish">
      <input type="hidden" name="_token" value="{!! csrf_token() !!}">
      <input type="hidden" name="result_type" id="result-type" value=""></div>
      <input type="hidden" name="result_data" id="result-data" value=""></div>
    </form>
    
    <button id="pay-button">Pay!</button>
    <script type="text/javascript">
  
    $('#pay-button').click(function (event) {
      event.preventDefault();
      $(this).attr("disabled", "disabled");
    
    $.ajax({
      
      url: './snaptoken',
      cache: false,
      success: function(data) {
        //location = data;
        console.log('token = '+data);
        
        var resultType = document.getElementById('result-type');
        var resultData = document.getElementById('result-data');
        function changeResult(type,data){
          $("#result-type").val(type);
          $("#result-data").val(JSON.stringify(data));
          //resultType.innerHTML = type;
          //resultData.innerHTML = JSON.stringify(data);
        }
        snap.pay(data, {
          
          onSuccess: function(result){
            changeResult('success', result);
            console.log(result.status_message);
            console.log(result);
            $("#payment-form").submit();
          },
          onPending: function(result){
            changeResult('pending', result);
            console.log(result.status_message);
            $("#payment-form").submit();
          },
          onError: function(result){
            changeResult('error', result);
            console.log(result.status_message);
            $("#payment-form").submit();
          }
        });
      }
    });
  });
  </script>


</body>
</html>

VT-Web

You can see some more details of VT-Web examples here.

Get Redirection URL of a Charge

//you don't have to use the function name 'vtweb', it's just an example
public function vtweb() 
    {
        $vt = new Veritrans;
        $transaction_details = array(
            'order_id'          => uniqid(),
            'gross_amount'  => 200000
        );
        // Populate items
        $items = [
            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'                     => "[email protected]",
            'phone'                     => "081322311801",
            'billing_address' => $billing_address,
            'shipping_address'=> $shipping_address
            );
        // Data yang akan dikirim untuk request redirect_url.
        // Uncomment 'credit_card_3d_secure' => true jika transaksi ingin diproses dengan 3DSecure.
        $transaction_data = array(
            'payment_type'          => 'vtweb', 
            'vtweb'                         => array(
                //'enabled_payments'    => [],
                'credit_card_3d_secure' => true
            ),
            'transaction_details'=> $transaction_details,
            'item_details'           => $items,
            'customer_details'   => $customer_details
        );
    
        try
        {
            $vtweb_url = $vt->vtweb_charge($transaction_data);
            return redirect($vtweb_url);
        } 
        catch (Exception $e) 
        {   
            return $e->getMessage;
        }
    }

Handle Notification Callback

Create a route in the route.php. The route must be post, since we're getting http post notification.

Route::post('/vt_notif', 'VtwebController@notification');

You need to exclude the notification route from CsrfToken Verification Edit VerifyCsrfToken.php which located in App/http/middleware/VerifyCsrfToken.php

//before
    class VerifyCsrfToken extends BaseVerifier
    {
        protected $except = [
            //
        ];
    }
    
//after
    class VerifyCsrfToken extends BaseVerifier
    {
        protected $except = [
            //
        'vt_notif'
        ];
    }

You can see some more details of notification handler examples here (line 101).

//you don't have to use the function name 'notification', it's just an example
public function notification()
{
        $vt = new Veritrans;
        echo 'test notification handler';
        $json_result = file_get_contents('php://input');
        $result = json_decode($json_result);
        if($result){
        $notif = $vt->status($result->order_id);
        }
        /*
        $transaction = $notif->transaction_status;
        $type = $notif->payment_type;
        $order_id = $notif->order_id;
        $fraud = $notif->fraud_status;

        if ($transaction == 'capture') {
          // For credit card transaction, we need to check whether transaction is challenge by FDS or not
          if ($type == 'credit_card'){
            if($fraud == 'challenge'){
              // TODO set payment status in merchant's database to 'Challenge by FDS'
              // TODO merchant should decide whether this transaction is authorized or not in MAP
              echo "Transaction order_id: " . $order_id ." is challenged by FDS";
              } 
              else {
              // TODO set payment status in merchant's database to 'Success'
              echo "Transaction order_id: " . $order_id ." successfully captured using " . $type;
              }
            }
          }
        else if ($transaction == 'settlement'){
          // TODO set payment status in merchant's database to 'Settlement'
          echo "Transaction order_id: " . $order_id ." successfully transfered using " . $type;
          } 
          else if($transaction == 'pending'){
          // TODO set payment status in merchant's database to 'Pending'
          echo "Waiting customer to finish transaction order_id: " . $order_id . " using " . $type;
          } 
          else if ($transaction == 'deny') {
          // TODO set payment status in merchant's database to 'Denied'
          echo "Payment using " . $type . " for transaction order_id: " . $order_id . " is denied.";
        }*/

VT-Direct

You can see VT-Direct form here.

you can see VT-Direct process here.

Checkout Page

<html>
<head>
    <title>Checkout</title>
    <!-- Include PaymentAPI  -->
    <link href="{{ URL::to('css/jquery.fancybox.css') }}" rel="stylesheet"> 
</head>
<body>
    <script type="text/javascript" src="https://api.sandbox.veritrans.co.id/v2/assets/js/veritrans.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
    <script type="text/javascript" src="{{ URL::to('js/jquery.fancybox.pack.js') }}"></script>

    <h1>Checkout</h1>
    <form action="vtdirect" method="POST" id="payment-form">
        <fieldset>
            <legend>Checkout</legend>
            <p>
                <label>Card Number</label>
                <input class="card-number" value="4811111111111114" size="20" type="text" autocomplete="off"/>
            </p>
            <p>
                <label>Expiration (MM/YYYY)</label>
                <input class="card-expiry-month" value="12" placeholder="MM" size="2" type="text" />
                <span> / </span>
                <input class="card-expiry-year" value="2018" placeholder="YYYY" size="4" type="text" />
            </p>
            <p>
                <label>CVV</label>
                <input class="card-cvv" value="123" size="4" type="password" autocomplete="off"/>
            </p>

            <p>
                <label>Save credit card</label>
                <input type="checkbox" name="save_cc" value="true">
            </p>

            <input id="token_id" name="token_id" type="hidden" />
            <button class="submit-button" type="submit">Submit Payment</button>
        </fieldset>
    </form>

    <!-- Javascript for token generation -->
    <script type="text/javascript">
    $(function(){
        // Sandbox URL
        Veritrans.url = "https://api.sandbox.veritrans.co.id/v2/token";
        // TODO: Change with your client key.
        Veritrans.client_key = "<your client key>";
        
        //Veritrans.client_key = "d4b273bc-201c-42ae-8a35-c9bf48c1152b";
        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'            : true,
                        'bank'              : 'bni',
                        'gross_amount'      : 10000
                         }
        };

        function callback(response) {
            if (response.redirect_url) {
                // 3dsecure transaction, please open this popup
                openDialog(response.redirect_url);

            } else if (response.status_code == '200') {
                // success 3d secure or success normal
                closeDialog();
                // submit form
                $(".submit-button").attr("disabled", "disabled"); 
                $("#token_id").val(response.token_id);
                $("#payment-form").submit();
            } else {
                // failed request token
                console.log('Close Dialog - failed');
                //closeDialog();
                //$('#purchase').removeAttr('disabled');
                // $('#message').show(FADE_DELAY);
                // $('#message').text(response.status_message);
                //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){
            event.preventDefault();
            //$(this).attr("disabled", "disabled"); 
            Veritrans.token(card, callback);
            return false;
        });
    });

    </script>
</body>
</html>

Checkout Process

1. Create Transaction Details
$transaction_details = array(
  'order_id'    => time(),
  'gross_amount'  => 10000
);
2. Create Item Details, Billing Address, Shipping Address, and Customer Details (Optional)
// Populate items
$items = array(
    array(
      'id'       => 'item1',
      'price'    => 5000,
      'quantity' => 1,
      'name'     => 'Adidas f50'
    ),
    array(
      'id'       => 'item2',
      'price'    => 2500,
      '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'            => "[email protected]",
    'phone'            => "081322311801",
    'billing_address'  => $billing_address,
    'shipping_address' => $shipping_address
  );
3. Get Token ID from Checkout Page
// Token ID from checkout page
$token_id = $request->input('token_id');
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
//create new object from Veritrans class
$vt = new Veritrans;
$response= $vt->vtdirect_charge($transaction_data);
6. Handle Transaction Status
// Success
if($response->transaction_status == 'capture') {
  echo "<p>Transaksi berhasil.</p>";
  echo "<p>Status transaksi untuk order id $response->order_id: " .
      "$response->transaction_status</p>";

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

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

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

  echo "<pre>";
  var_dump($response);
  echo "</pre>";
}

Process Transaction

More details can be found here

Don't forget to create new veritrans object

//creating new veritrans object
$vt = new Veritrans;
Get a Transaction Status
$status = $vt->status($order_id);
var_dump($status);
Approve a Transaction
$approve = $vt->approve($order_id);
var_dump($approve);
Cancel a Transaction
$cancel = $vt->cancel($order_id);
var_dump($cancel);

veritrans-laravel5's People

Contributors

harrypujianto avatar trollid avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

veritrans-laravel5's Issues

Payment types differences

Hi,

I was testing SNAP well there was token issues such as #27 and some others so I've decided to test other options as well.

Currently I am testing vtweb and it appears that users are require to fill their card data twice (not sure if I've done something wrong or it's nature behavior of vtweb)

Let's have a closer look

As a user I fill my card data once at the host website then popup iframe shows (so far so good)

m1

And one more time after that in Midtrans website

m2

Well if I was a user of a website which asks me my credit cards data twice I wouldn't trust them and immediately cancel my transaction (serious concern as a seller)

So my question here is:

Q1

Is it nature behavior of VTWeb or I've done something wrong?

Q2

Is Vtdirect behave same as VTweb or differently? (I mean asking data twice)

Thanks in advance.

Class '\App\Veritrans\Exception' not found

Hi,

I try to use snap, if I use sample codes static ones it will work, but as soon as i change my data to dynamic in order to get my real data pass to midtrans i get error 500 - Class '\App\Veritrans\Exception' not found on my network and no popup appears.

error comes from this line:

throw new Exception($message, $info['http_code']);

PS: I also tried This but no luck.

here is my function:

public function payonline(Request $request){
        //   midtrans
        error_log('masuk ke snap token dri ajax');
        $midtrans = new Midtrans;

        $transaction_details = array(
            'order_id'      => uniqid(),
            'gross_amount'  => $request->input('totalPriceInTotal')
        );

        
        $items = Cart::getContent();
        $item_details = array();
        foreach($items as $item)
        {
            $item_details[] = array(
                'id'        => $item->id,
                'price'     => $item->getPriceWithConditions(),
                'quantity'  => $item->quantity,
                'name'      => $item->name,
            );
        }
       

        // Populate customer's shipping address
        $shipping_address = array(
            'first_name'    => $request->input('buyer_name'),
            'last_name'     => $request->input('buyer_name'),
            'phone'         => $request->input('phone'),
            'country_code'  => 'IDN'
            );

        // Populate customer's Info
        $customer_details = array(
            'first_name'      => $request->input('buyer_name'),
            'last_name'       => $request->input('buyer_name'),
            'email'           => $request->input('buyer_email'),
            'phone'           => $request->input('phone'),
            'billing_address' => $shipping_address,
            'shipping_address'=> $shipping_address
            );

        // Data yang akan dikirim untuk request redirect_url.
        $credit_card['secure'] = true;
        //ser save_card true to enable oneclick or 2click
        //$credit_card['save_card'] = true;

        $time = time();
        $custom_expiry = array(
            'start_time' => date("Y-m-d H:i:s O",$time),
            'unit'       => 'hour', 
            'duration'   => 2
        );
        
        $transaction_data = array(
            'transaction_details'=> $transaction_details,
            'item_details'       => $item_details,
            'customer_details'   => $customer_details,
            'credit_card'        => $credit_card,
            'expiry'             => $custom_expiry
        );

        try
        {
            $snap_token = $midtrans->getSnapToken($transaction_data);
            //return redirect($vtweb_url);
            echo $snap_token;
        } 
        catch (Exception $e) 
        {   
            return $e->getMessage;
        }
    }

Nembak $vt->status($result->order_id). Keluaran nya gak dapet.

Saat post notification, lalu akses $vt->status($result->order_id) ini apa gak dikasih handle om?

soalnya pas saya tembak, hasil curl itu seperti ini:

> [2016-12-22 03:35:32] local.INFO: <!DOCTYPE html>
> <html class="no-js">
> <head>
>     <meta charset="utf-8">
>     <!-- Cross compatibility -->
>     <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
>     <title>Midtrans</title>
>     <meta name="description" content=""/>
> 
>     <link rel="stylesheet" href="//v2/assets/css/all.css"/>
> 
> </head>
> <body>
> <div class="container">
>     <div class="center desc"><p>404</p></div>
>     <div class="center click"><h3>
>         <a href="#">&#45; Ups &#45;</a>
>     </h3></div>
> </div>
> <footer>
>     <p class="center">&copy; 2016 PT Midtrans. All Rights Reserved</p>
> </footer>
> </body>
> </html>
>   
> [2016-12-22 03:35:32] local.ERROR: ErrorException: Trying to get property of non-object in /var/www/html/front/app/Veritrans/Veritrans.php:129
> Stack trace:

Ini kenapa ya?

Push Notification Redirection Error 302

Hello, semua sudah berjalan baik..
tetapi kenapa push notificationnya memberikan status error ya?

Redirection status code 301, 302 and 303 are not supported. Use 307 or 308 instead. Redirection status code 301, 302 and 303 are not supported. Use 307 or 308 instead

note : IP sudah whitelist melalui trustedproxy

Failed response 500 not 200 SNAP

saya sudah melakukan route::post ke controller saya dan mengarahkan ke function notification sebagai berikut :
Route::post('/notification' , 'TransactionController@notification');

dengan function notification sebagai berikut :

public function notification()
    {
        $midtrans = new Midtrans;
        echo 'test notification handler';
        $json_result = file_get_contents('php://input');
        $result = json_decode($json_result);
        if($result){
        $notif = $midtrans->status($result->order_id);
        }
        error_log(print_r($result,TRUE));
        
        $transaction = $notif->transaction_status;
        $type = $notif->payment_type;
        $order_id = $notif->order_id;
        $fraud = $notif->fraud_status;
        if ($transaction == 'capture') {
          // For credit card transaction, we need to check whether transaction is challenge by FDS or not
          if ($type == 'credit_card'){
            if($fraud == 'challenge'){
              // TODO set payment status in merchant's database to 'Challenge by FDS'
              // TODO merchant should decide whether this transaction is authorized or not in MAP
              echo "Transaction order_id: " . $order_id ." is challenged by FDS";
              } 
              else {
              // TODO set payment status in merchant's database to 'Success'
              echo "Transaction order_id: " . $order_id ." successfully captured using " . $type;
              }
            }
          }
        else if ($transaction == 'settlement'){
          // TODO set payment status in merchant's database to 'Settlement'
          echo "Transaction order_id: " . $order_id ." successfully transfered using " . $type;
          } 
          else if($transaction == 'pending'){
          // TODO set payment status in merchant's database to 'Pending'
          echo "Waiting customer to finish transaction order_id: " . $order_id . " using " . $type;
          } 
          else if ($transaction == 'deny') {
          // TODO set payment status in merchant's database to 'Denied'
          echo "Payment using " . $type . " for transaction order_id: " . $order_id . " is denied.";
        }
   
    }

namun saya selalu mendapatkan status 500 saat test di midtrans endpoint untuk check url , apa ada langkah yang kurang ? karena semua sudah berjalan sampai step memberi notifikasi via email.

Veritrans Error (400): transaction_details.gross_amount harus sama atau lebih besar dari 0.01

mohon bantuannya pas saya mau buat transaksi saya dapat error Veritrans Error (400): transaction_details.gross_amount harus sama atau lebih besar dari 0.01 itu kenapa ya padahal pas gross amount nya saya udah d cobain ganti" angkanya tetep aja

public function addPenumpang(Request $request){
$kursi = implode(" ", $request->get('no_kursi'));
$perjalanan = Perjalanan::where('id',$request->perjalanan_id)->first();
$user = User::where('id',$request->user_id)->first();
$jumlahKursi=0;
if(in_array('1', $request->get('no_kursi'))){
$perjalanan->no_kursi1 = 1;
$jumlahKursi+=1;
}
if(in_array('2', $request->get('no_kursi'))){
$perjalanan->no_kursi2 = 1;
$jumlahKursi+=1;
}
if(in_array('3', $request->get('no_kursi'))){
$perjalanan->no_kursi3 = 1;
$jumlahKursi+=1;
}
if (in_array('4', $request->get('no_kursi'))) {
$perjalanan->no_kursi4 = 1;
$jumlahKursi+=1;
}
if (in_array('5', $request->get('no_kursi'))) {
$perjalanan->no_kursi5 = 1;
$jumlahKursi+=1;
}
$jumlahOrder=$user->jumlahOrder+1;
$keuntungan = ($request->tambahan + 120000)*$jumlahKursi;
$perjalanan->keuntungan += $keuntungan;
$perjalanan->jumlahPenumpang += $jumlahKursi;
$user->jumlahOrder+=$jumlahOrder;
$penumpang = new Penumpang;
$penumpang->perjalanan_id = $request->perjalanan_id;
$penumpang->no_kursi = $kursi;
$penumpang->nama = $request->nama;
$penumpang->no_telp = $request->no_telp;
$penumpang->email = $request->email;
$penumpang->layanan = $request->layanan;
$penumpang->tambahan = $request->tambahan;
$penumpang->alamat_jemput = $request->alamat_jemput;
$penumpang->alamat_antar = $request->alamat_antar;
$penumpang->user_id = $request->user_id;
$penumpang->kode_tiket = $request->kode_tiket;
$penumpang->jumlahOrder += $jumlahOrder;
//$penumpang->save();

    // Buat transaksi ke midtrans kemudian save snap tokennya.
        $payload = [
            'transaction_details' => [
                'order_id'      => $request->kode_tiket,
                'gross_amount'  => $keuntungan
            ],
            'customer_details' => [
                'first_name'    => $penumpang->nama,
                'email'         => $penumpang->email,
                'phone'         => $penumpang->no_telp
            ],
            'item_details' => [
                [
                    'id'       => $request->kode_tiket,
                    'price'    => $keuntungan,
                    'quantity' => $jumlahKursi,
                    'name'     => $penumpang->nama
                ]
            ]
        ];
    $snapToken = Veritrans_Snap::getSnapToken($payload);
    $penumpang->snap_token = $snapToken;
    $penumpang->save();
    $user->save();
    $perjalanan->save();    
    $this->response['kode_tiket'] = $request->kode_tiket;
    return response()->json($this->response);
}

itu kodingan nya

snap issue

Hi,

I get status 200 on SNAP but there is no popup in my page, why is that?

55

Veritrans Error (400): Validation Error

I try to use VtdirectController methods in my controller, the result i get is:

Veritrans Error (400): Validation Error

Codes

js

<script type="text/javascript" src="https://api.sandbox.veritrans.co.id/v2/assets/js/veritrans.min.js"></script>
<script type="text/javascript" src="{{ asset('js/jquery.fancybox.pack.js') }}"></script>
<script type="text/javascript">
		$(function(){
			Veritrans.url = "https://api.sandbox.veritrans.co.id/v2/token";
			Veritrans.client_key = "VT-client-xxx-xxxx";

			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,
							'bank'				: 'bni',
							'gross_amount'		: 10000
							}
			};

			function callback(response) {
				if (response.redirect_url) {
					// 3dsecure transaction, please open this popup
					openDialog(response.redirect_url);

				} else if (response.status_code == '200') {
					// success 3d secure or success normal
					closeDialog();
					// submit form
					// $(".submit-button").attr("disabled", "disabled");
					$("#token_id").val(response.token_id);
					$("#payment-form").submit();
				} else {
					// failed request token
					console.log('Close Dialog - failed');
					//closeDialog();
					//$('#purchase').removeAttr('disabled');
					// $('#message').show(FADE_DELAY);
					// $('#message').text(response.status_message);
					//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){
				event.preventDefault();
				//$(this).attr("disabled", "disabled"); 
				Veritrans.token(card, callback);
				return false;
			});
		});
</script>

html

<form id="payment-form" class="" action="{{url('payonline')}}" method="POST">
                          {{csrf_field()}}
                          <fieldset>
                            <legend>Checkout</legend>
                            <p>
                              <label>Card Number</label>
                              <input class="card-number" value="4011111111111112" size="20" type="text" autocomplete="off"/>
                            </p>
                            <p>
                              <label>Expiration (MM/YYYY)</label>
                              <input class="card-expiry-month" value="12" placeholder="MM" size="2" type="text" />
                                <span> / </span>
                                <input class="card-expiry-year" value="2018" placeholder="YYYY" size="4" type="text" />
                            </p>
                            <p>
                                <label>CVV</label>
                                <input class="card-cvv" value="123" size="4" type="password" autocomplete="off"/>
                            </p>

                            <p>
                                <label>Save credit card</label>
                                <input type="checkbox" name="save_cc" value="true">
                            </p>

                            <input id="token_id" name="token_id" type="hidden" />
                            <button class="submit-button" type="submit">Submit Payment</button>
                          </fieldset>
                        </form>

route

Route::post('/payonline', 'CartController@payonline');

controller

public function payonline(Request $request){
        //   midtrans
        $token = $request->input('token_id');
        $vt = new Veritrans;

        $transaction_details = array(
            'order_id'      => uniqid(),
            'gross_amount'  => $request->input('totalPriceInTotal')
        );

        
        $items = Cart::getContent();
        $item_details = array();
        foreach($items as $item)
        {
            $item_details[] = array(
                'id'        => $item->id,
                'price'     => $item->getPriceWithConditions(),
                'quantity'  => $item->quantity,
                'name'      => $item->name,
            );
        }
       

        // Populate customer's shipping address
        $shipping_address = array(
            'first_name'    => $request->input('buyer_name'),
            'last_name'     => $request->input('buyer_name'),
            'phone'         => $request->input('phone'),
            'country_code'  => 'IDN'
            );

        // Populate customer's Info
        $customer_details = array(
            'first_name'      => $request->input('buyer_name'),
            'last_name'       => $request->input('buyer_name'),
            'email'           => $request->input('buyer_email'),
            'phone'           => $request->input('phone'),
            'billing_address' => $shipping_address,
            'shipping_address'=> $shipping_address
            );


        $transaction_data = array(
            'payment_type'      => 'credit_card', 
            'credit_card'       => array(
               'token_id'  => $token,
               'bank'    => 'bni'
               ),
            'transaction_details'   => $transaction_details,
            'item_details'           => $item_details
        );

        
        $response = null;
        try
        {
            $response= $vt->vtdirect_charge($transaction_data);
        } 
        catch (Exception $e) 
        {
            return $e->getMessage; 
        }

        var_dump($response);
        if($response)
        {
            if($response->transaction_status == "capture")
            {
                //success
                echo "Transaksi berhasil. <br />";
                echo "Status transaksi untuk order id ".$response->order_id.": ".$response->transaction_status;

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

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

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

                echo "<h3>Response:</h3>";
                var_dump($response);
            }
        }
    }

Any idea why that might be?

Something went wrong while processing this payment

Ketika saya mau lanjutkan pembayaran pakai snap tiba-tiba muncul alert "Error! Something went wrong while processing this payment. Please try again later." dan status order otomatis menjadi deny. itu kenapa ya? Apa ada kodingan saya yang salah atau memang sedang ada gangguan? Padahal sebelumnya lancar-lancar aja dipake transaksi. Mohon pencerahannya terimakasih.
(Saya pakai mode production)

CURL Error: Could not resolve host: app.sandbox.midtrans.com; Name or service not known

ketika digunakan dalam iframe, selalu keluar tampiran error.

"Kami tidak menemukan transaksi Anda
Transaksi Anda tidak tersedia, atau URL yang Anda masukkan salah."

dan saat saya cek di firebug, keterangan error nya adalah :

"CURL Error: Could not resolve host: app.sandbox.midtrans.com; Name or service not known"

kemudian, setelah saya refresh via javascript (location.reload()), dan saya coba lagi, hasil nya sukses keluar form pembayarannya.
Apakah ada yg harus disesuaikan ketika digunakan di dalam iframe?

terima kasih banyak.

Configuration problem

Hi,

I'm trying to get this application work on laravel 5.5, but I'm not sure how to do it exactly!
Your document seems to mostly repeat whats in the files and not exactly helping to run the application. Here are my questions:

  1. How use production mode (which one of your controllers handle that?)

  2. How is structure of production form? because it seems button doesn't work on for example <form action="vtdirect" method="POST" id="payment-form">

  3. How do you store data on Database when user click on payment button (no matter payment is successful or not) it has to be stored in in orders (whatevere the name is) table how that will handle in your application forms?

Thanks.

POST Notification :killed :killed

Post notification tiba-tiba error ya sebelum-sebelumnya lancar saja. Pesan error di riwayat HTTP notification cuman :killed :killed. Tapi pas tak coba di mode sanbox lancar-lancar aja.

Terimkasih, ada solusi?

Originally posted by @syahidfrd in #19 (comment)

Difference Midtrans & Veritrans

Hi!

I see from your libs, you have 2 class. Midtrans and Veritrans. What's the different between both of them? Can I use only one of them? Or should both?

Also, from original documentation, there's isSanitized and is3ds options. But, I see form your libs there's nothing I can find this. Is that not important here or there's another way to perform that kinda option.

Thank you!

Exception Class Not Found

Modify this line
use App\Exceptions\VeritransException as Exception;

error debug
PHP message: PHP Fatal error: Class 'App\Veritrans\Exception' not found in

Tidak ada composer support, tidak sinkron dengan upstream (Midtrans-PHP)

Saya pertama kali menggunakan midtrans dengan library ini, sangat membantu sekali. Sayang sekali tidak sinkron dengan library Midtrans-PHP yang saya perhatikan terus diupdate, juga tidak support dengan package manager PHP modern seperti composer.

Oleh karena itu saya berinisiatif membuat package laravel: https://github.com/firmantr3/laravel-midtrans. Mungkin dapat menjadi pertimbangan sebagai alternatif library untuk laravel.

Looping item dinamis pada controller pada saat checkout process

Hi, saya mau tanya untuk looping item dinamis bagaimana ya saat checkout proses pada controller, kondisi sekarang hanya bisa submit 1 item (lebih dari 1 item gagal)

disini saya menggunakan LaravelShoppingcart untuk fitur cart

Untuk inputannya :

@foreach($cart as $item)
    <input type="text" name="id{{$item->id}}" value="item{{$item->id}}">
    <input type="text" name="name{{$item->id}}" value="{{$item->name}}">
    <input type="text" name="price{{$item->id}}" value="{{$item->price}}">
@endforeach

Untuk controller nya :

$cart = Cart::content();
......
foreach ($cart as $item) {
            ${'item'.$item->id} = array(
                'id' => $request->input('id'.$item->id),
                'price' => $request->input('price'.$item->id),
                'quantity' => 1,
                'name' => $request->input('name'.$item->id),
                );
}

        $item_details = array();

            foreach ($cart as $item_array) {

                $item_details[] = ${'item'.$item_array->id};

            }

Maaf masih newbie, minta bantuannya kalo ada referensi. Trima kasih

Error 404

Semua berjalan baik, tetapi saat saya mencoba checkout, popup payment snap tidak muncul, walau di console sudah loading dan muncul token snap-nya

Get info from midtrans and save to database

Hi,
I have working snap where I can purchase successfully but on redirect i go to another page and receive error while my transaction was successful.

Here is how my url's are:

domain/orders (I pay here with snap)
domain/orderspayonline/7 (here is where i redirect and receive error)

ERROR:

Class 'App\Veritrans\Exception' not found

on

      else {
        $result_array = json_decode($result);
        if ($info['http_code'] != 201) {
        $message = 'Midtrans Error (' . $info['http_code'] . '): '
            . implode(',', $result_array->error_messages);
        throw new Exception($message, $info['http_code']);  //on this line
 
      }

What I NEED:

  1. Redirect back to my domain/orders page and show some Session::flash
  2. Get Order ID and transaction result (which is success) so I can save in my orders table in order to change status of my order in DB.

Thank you.

Status Library

halo terima kasih untuk library ini

mau nanya statusnya ini udah stabilkah? bisa dipake di production?

saya ngelihat kaya di file SnapController masih banyak yang dikomentarin

terima kasih!

Midtrans Status Error

Halo,
Saya coba untuk midtrans->status dan berhasil mendapatkan return resultnya.
Tetapi pada Midtrans.php line 135 memberikan error, hanya karena http_codenya return 200

if ($info['http_code'] != 201) { $message = 'Midtrans Error (' . $info['http_code'] . '): ' . implode(',', $result_array->error_messages); throw new Exception($message, $info['http_code']);

Apakah ini bugs atau kesalahan logic ?
Sebelum $result_array->error_messages apakah tidak lebih baik diberikan pengecekan dulu, untuk menghindari exception 'ErrorException' with message 'Undefined property: stdClass::$error_messages'

token issue

Hi,

When I try to return results in specific route or page i'm getting error 400 but receiving token as well!

try
{
            $snap_token = $midtrans->getSnapToken($transaction_data);
            $project->payment_verified = 'y';
            $project->save();

            //return redirect($vtweb_url);
            return redirect()->back()->with('success', 'Done '.$snap_token);
} 
catch (Exception $e) 
{   
            return $e->getMessage;
}

400

but if i use default echo $snap_token; everything works just fine.

what is the issue with it?

VeritransException

Tidak ada class VeritransException di 'App\Veritrans\Exception'.. mohon pencerahannya

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.