Midtrans-PHP

repository·master·Indexed 19 days ago

https://github.com/midtrans/midtrans-php

The official PHP wrapper library for the Midtrans Payment API. It enables the integration of Midtrans payment services into PHP applications, supporting Snap (Popup and Redirect), Core API (VT-Direct), and Snap-BI for direct debit, virtual accounts, and QRIS. The library includes tools for managing transaction statuses, handling HTTP notifications (webhooks), processing refunds, and configuring environment settings for Sandbox and Production.

Tokens
8.6K
Snippets
21
Records
22
Agent score
15%

What's inside midtrans-php

  1. Implement Snap Redirect

    master

    Snap Redirect requires the customer to be redirected to a payment page hosted by Midtrans.

    Workflow:

    1. Backend: Call \Midtrans\Snap::createTransaction($params) to get a transaction object.
    2. Redirect: Access the redirect_url property from the response and redirect the user's browser to that URL.
    $params = array(
        'transaction_details' => array(
            'order_id' => rand(),
            'gross_amount' => 10000,
        )
    );
    
    try {
      // Get Snap Payment Page URL
      $paymentUrl = \Midtrans\Snap::createTransaction($params)->redirect_url;
      
      // Redirect to Snap Payment Page
      header('Location: ' . $paymentUrl);
    }
    catch (Exception $e) {
      echo $e->getMessage();
    }
  2. Manual Installation of Midtrans-PHP

    master

    If you are not using Composer, download or clone the repository and manually require the Midtrans.php file in your project to enable autoloading.

    require_once dirname(__FILE__) . '/pathofproject/Midtrans.php';
    
    // my code goes here
  3. Configure General Midtrans Settings

    master

    Before making API calls, configure the global \Midtrans\Config settings. You must set your serverKey and decide whether to use the Sandbox (isProduction = false) or Production (isProduction = true) environment. You can also enable sanitization, 3DS for credit cards, and manage notification URLs.

    // Set your Merchant Server Key
    \Midtrans\Config::$serverKey = '<your server key>';
    // Set to Development/Sandbox Environment (default). Set to true for Production Environment (accept real transaction).
    \Midtrans\Config::$isProduction = false;
    // Set sanitization on (default)
    \Midtrans\Config::$isSanitized = true;
    // Set 3DS transaction for credit card to true
    \Midtrans\Config::$is3ds = true;
  4. Run tests with PHPUnit

    master

    You can run the project's test suite using PHPUnit.

    To run integration tests that perform real transactions in the sandbox environment, ensure you have updated the server_key and client_key in your phpunit.xml file with your own Midtrans credentials.

    Available test commands:

    • Run all tests: vendor/bin/phpunit
    • Run a specific test file: vendor/bin/phpunit tests/integration/CoreApiIntegrationTest.php
    # Run all tests
    vendor/bin/phpunit
    
    # Run specific integration tests
    vendor/bin/phpunit tests/integration/CoreApiIntegrationTest.php
  5. Implement Core API (VT-Direct)

    master

    Core API (VT-Direct) is a basic backend implementation where you customize the frontend embedded in your web/app. There is no redirection.

    Workflow:

    1. Frontend: Set the MidtransNew3ds.clientKey and use a checkout page to collect payment details and obtain a token_id.
    2. Backend: Construct a $transaction_data array containing payment_type, credit_card (with token_id), transaction_details, item_details, and customer_details.
    3. Charge: Call \Midtrans\CoreApi::charge($transaction_data) to process the payment.
    4. 3DS: If the response contains a redirect_url, handle the 3DS authentication on the frontend.
    5. Status: Check $response->transaction_status to handle capture, deny, challenge, or errors.
    // 1. Prepare transaction data
    $transaction_data = array(
        'payment_type' => 'credit_card',
        'credit_card'  => array(
            'token_id'      => $token_id,
            'authentication'=> true,
        ),
        'transaction_details' => $transaction_details,
        'item_details'        => $items,
        'customer_details'    => $customer_details
    );
    
    // 2. Charge
    $response = \Midtrans\CoreApi::charge($transaction_data);
    
    // 3. Handle Status
    if($response->transaction_status == 'capture') {
        // Success
    } else if($response->transaction_status == 'deny') {
        // Denied
    } else if($response->transaction_status == 'challenge') {
        // 3DS Challenge
    }
  6. Guidelines for developing e-commerce plug-ins

    master

    When developing new e-commerce plug-ins for Midtrans, follow these critical guidelines:

    1. Currency Handling: Midtrans v1 and v2 currently only accept payments in Indonesian Rupiah (IDR). The server validates that item prices are integers. If your system uses currencies other than IDR, convert them to IDR first. Do not round off prices before conversion; only round the price after it has been converted to IDR to ensure accuracy.
    2. Auto-sanitization: Consider utilizing the auto-sanitization feature in your implementation.
  7. Handle HTTP Notifications (Webhooks)

    master

    Midtrans sends HTTP POST notifications to your configured URL whenever a transaction status changes.

    To handle these, create a dedicated endpoint and use the \Midtrans\Notification class to parse the payload. You should check both transaction_status and fraud_status to determine the final state of the order in your database.

    $notif = new \Midtrans\Notification();
    
    $transaction = $notif->transaction_status;
    $fraud = $notif->fraud_status;
    
    if ($transaction == 'capture') {
        if ($fraud == 'challenge') {
          // Handle challenge
        }
        else if ($fraud == 'accept') {
          // Handle success
        }
    }
    // ... handle other statuses like 'cancel' or 'deny'
  8. Implement Snap Payment (Popup)

    master

    Snap provides a customizable payment popup that appears directly on your web or app without redirection.

    Workflow:

    1. Backend: Generate a Snap Token using \Midtrans\Snap::getSnapToken($params).
    2. Frontend: Include the Snap JS library (remove .sandbox from the URL for production) and call snap.pay(snapToken, options) when the user clicks the pay button.

    Available callbacks in snap.pay include onSuccess, onPending, and onError.

    // 1. Get Snap Token
    $params = array(
        'transaction_details' => array(
            'order_id' => rand(),
            'gross_amount' => 10000,
        )
    );
    $snapToken = \Midtrans\Snap::getSnapToken($params);
    <!-- 2. Frontend Implementation -->
    <script src="https://app.sandbox.midtrans.com/snap/snap.js" data-client-key="<Set your ClientKey here>"></script>
    <script type="text/javascript">
      document.getElementById('pay-button').onclick = function(){
        snap.pay('<?=$snapToken?>', {
          onSuccess: function(result){ /* handle success */ },
          onPending: function(result){ /* handle pending */ },
          onError: function(result){ /* handle error */ }
        });
      };
    </script>
  9. Install Midtrans-PHP via Composer

    master

    If you are using Composer, you can install the library using the CLI or by adding it to your composer.json file. This is the recommended method for modern PHP projects.

    Note for Laravel users: If you encounter issues with autoloading, you may need to run composer dumpautoload. Once installed, the /Midtrans object will be available in your project via autoloading.

    composer require midtrans/midtrans-php
  10. Override Notification URLs

    master

    You can customize the notification URLs sent by Midtrans for specific transactions.

    • Use Config::$appendNotifUrl to add additional URLs alongside the ones configured in the Midtrans Dashboard Portal (MAP).
    • Use Config::$overrideNotifUrl to use new URLs and disregard the settings in the Midtrans Dashboard Portal (MAP).

    Constraints:

    • You can provide a maximum of 3 URLs.
    • If both appendNotifUrl and overrideNotifUrl are used, only overrideNotifUrl will be applied.
    // Add new notification url(s) alongside the settings on Midtrans Dashboard Portal (MAP)
    Config::$appendNotifUrl = "https://example.com/test1,https://example.com/test2";
    // Use new notification url(s) disregarding the settings on Midtrans Dashboard Portal (MAP)
    Config::$overrideNotifUrl = "https://example.com/test1";
  11. Configure Snap-BI General Settings

    master

    Before using the Snap-BI feature (available from v2.6.0), you must configure the global settings using the \SnapBi\Config class. These settings include your credentials for the B2B Access Token API and Transactional API, as well as environment selection.

    Key Configuration Properties:

    • isProduction: Set to true for Production, false for Sandbox (default).
    • snapBiClientId: Your Merchant Client ID.
    • snapBiPrivateKey: Your private key (ensure \n is used for newlines).
    • snapBiClientSecret: Your Merchant Secret Key.
    • snapBiPartnerId: Your Merchant Partner ID.
    • snapBiChannelId: Your Channel ID.
    • enableLogging: Set to true to see request/response details (disable in production).
    • snapBiPublicKey: Your public key for verifying webhook notifications.
    \SnapBi\Config::$isProduction = false;
    \SnapBi\Config::$snapBiClientId = "YOUR CLIENT ID";
    \SnapBi\Config::$snapBiPrivateKey = "YOUR PRIVATE KEY";
    \SnapBi\Config::$snapBiClientSecret = "YOUR CLIENT SECRET";
    \SnapBi\Config::$snapBiPartnerId = "YOUR PARTNER ID";
    \SnapBi\Config::$snapBiChannelId = "CHANNEL ID";
    \SnapBi\Config::$enableLogging = false;
    \SnapBi\Config::$snapBiPublicKey = "YOUR PUBLIC KEY";