MCPcopy Index your code
hub / github.com/Midtrans/midtrans-go

github.com/Midtrans/midtrans-go @v1.3.8

Chat with this repo
repository ↗ · DeepWiki ↗ · release v1.3.8 ↗ · + Follow
345 symbols 1,025 edges 35 files 183 documented · 53%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Midtrans Go Library

Go Report Card License: MIT

Midtrans :heart: Go !

Go is a very modern, terse, and combine aspect of dynamic and static typing that in a way very well suited for web development, among other things. Its small memory footprint is also an advantage of itself. This module will help you use Midtrans product's REST APIs in Go.

1. Installation

1.1 Using Go Module

Run this command on your project to initialize Go mod (if you haven't):

go mod init

then reference midtrans-go in your project file with import:

import (
    "github.com/midtrans/midtrans-go"
    "github.com/midtrans/midtrans-go/coreapi"
    "github.com/midtrans/midtrans-go/snap"
    "github.com/midtrans/midtrans-go/iris"
)

1.2 Using go get

Also, the alternative way you can use go get the package into your project

go get -u github.com/midtrans/midtrans-go

2. Usage

There is a type named Client (coreapi.Client, snap.Client, iris.Client) that should be instantiated through function New which holds any possible setting to the library. Any activity (charge, approve, etc) is done in the client level.

2.1 Choose Product/Method

We have 3 different products that you can use: - Snap - Customizable payment popup will appear on your web/app (no redirection). doc ref - Snap Redirect - Customer need to be redirected to payment url hosted by midtrans. doc ref - Core API (VT-Direct) - Basic backend implementation, you can customize the frontend embedded on your web/app as you like (no redirection). doc ref - Iris Disbursement - Iris is Midtrans’ cash management solution that allows you to disburse payments to any bank accounts in Indonesia securely and easily. doc ref

To learn more and understand each of the product's quick overview you can visit https://docs.midtrans.com.

2.2 Client Initialization and Configuration

Get your client key and server key from Midtrans Dashboard

Create API client object, You can also check the project's implementation for more examples. Please proceed there for more detail on how to run the example.

2.2.1 Using global config

Set a config with globally, (except for iris api)

midtrans.ServerKey = "YOUR-SERVER-KEY"
midtrans.Environment = midtrans.Sandbox

2.2.2 Using Client

//Initiate client for Midtrans CoreAPI
var c = coreapi.Client
c.New("YOUR-SERVER-KEY", midtrans.Sandbox)

//Initiate client for Midtrans Snap
var s = snap.Client
s.New("YOUR-SERVER-KEY", midtrans.Sandbox)

//Initiate client for Iris disbursement
var i = iris.Client
i.New("IRIS-API-KEY", midtrans.Sandbox)

2.3 Snap

Snap is Midtrans existing tool to help merchant charge customers using a mobile-friendly, in-page, no-redirect checkout facilities. Using snap is simple.

Available methods for Snap

// CreateTransaction : Do `/transactions` API request to SNAP API to get Snap token and redirect url with `snap.Request`
func CreateTransaction(req *snap.Request) (*Response, *midtrans.Error)

// CreateTransactionToken : Do `/transactions` API request to SNAP API to get Snap token with `snap.Request`
func CreateTransactionToken(req *snap.Request) (string, *midtrans.Error)

// CreateTransactionUrl : Do `/transactions` API request to SNAP API to get Snap redirect url with `snap.Request`
func CreateTransactionUrl(req *snap.Request) (string, *midtrans.Error)

// CreateTransactionWithMap : Do `/transactions` API request to SNAP API to get Snap token and redirect url with Map request
func CreateTransactionWithMap(req *snap.RequestParamWithMap) (ResponseWithMap, *midtrans.Error)

// CreateTransactionTokenWithMap : Do `/transactions` API request to SNAP API to get Snap token with Map request
func CreateTransactionTokenWithMap(req *snap.RequestParamWithMap) (string, *midtrans.Error)

// CreateTransactionUrlWithMap : Do `/transactions` API request to SNAP API to get Snap redirect url with Map request
func CreateTransactionUrlWithMap(req *snap.RequestParamWithMap) (string, *midtrans.Error) 

Snap usage example, create transaction with minimum Snap parameters (choose one of alternatives below):

2.3.1 Using global Config & static function

Sample usage if you prefer Midtrans global configuration & using static function. Useful if you only use 1 merchant account API key, and keep the code short.

// 1. Set you ServerKey with globally
midtrans.ServerKey = "YOUR-SERVER-KEY"
midtrans.Environment = midtrans.Sandbox

// 2. Initiate Snap request
req := & snap.RequestParam{
    TransactionDetails: midtrans.TransactionDetails{
        OrderID:  "YOUR-ORDER-ID-12345", 
        GrossAmt: 100000,
    }, 
    CreditCard: &snap.CreditCardDetails{
        Secure: true,
    },
}

// 3. Request create Snap transaction to Midtrans
snapResp, _ := CreateTransaction(req)
fmt.Println("Response :", snapResp)

2.3.2 Using Client

Sample usage if you prefer to use client instance & config. Useful if you plan to use multiple merchant account API keys, want to have multiple client instances, or prefer the code to be object-oriented.

// 1. Initiate Snap client
var s = snap.Client
s.New("YOUR-SERVER-KEY", midtrans.Sandbox)

// 2. Initiate Snap request
req := & snap.RequestParam{
        TransactionDetails: midtrans.TransactionDetails{
            OrderID:  "YOUR-ORDER-ID-12345",
            GrossAmt: 100000,
        }, 
        CreditCard: &snap.CreditCardDetails{
            Secure: true,
        },
    }

// 3. Request create Snap transaction to Midtrans
snapResp, _ := s.CreateTransaction(req)
fmt.Println("Response :", snapResp)

On the frontend side (on the HTML payment page), you will need to include snap.js library and implement the payment page.

Sample HTML payment page implementation:

<html>
  <body>
    <button id="pay-button">Pay!</button>
    <pre>

JSON result will appear here after payment:



</pre> 


    <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(){
        // SnapToken acquired from previous step
        snap.pay('PUT_TRANSACTION_TOKEN_HERE', {
          // 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);
          }
        });
      };
    </script>
  </body>
</html>

You may want to override those onSuccess, onPending and onError functions to implement the behaviour that you want on each respective event.

Then implement Backend Notification Handler, Refer to this section

Alternativelly, more complete Snap parameter:

func GenerateSnapReq() *snap.Request {
    // Initiate Customer address
    custAddress := &midtrans.CustomerAddress{
        FName: "John",
        LName: "Doe",
        Phone: "081234567890",
        Address: "Baker Street 97th",
        City: "Jakarta",
        Postcode: "16000",
        CountryCode: "IDN",
    }

    // Initiate Snap Request
    snapReq := &snap.Request{
        TransactionDetails: midtrans.TransactionDetails{
            OrderID: "YOUR-UNIQUE-ORDER-ID-1234",
            GrossAmt: 200000,
        }, 
        CreditCard: &snap.CreditCardDetails{
            Secure: true,
        },
        CustomerDetail: &midtrans.CustomerDetails{
            FName: "John",
            LName: "Doe",
            Email: "john@doe.com",
            Phone: "081234567890",
            BillAddr: custAddress,
            ShipAddr: custAddress,
        },
        Items: &[]midtrans.ItemDetails{
            midtrans.ItemDetails{
                ID: "ITEM1",
                Price: 200000,
                Qty: 1,
                Name: "Someitem",
            },
        },
    }

 return snapReq
}

INFO: When using client, you can set config options like SetIdempotencyKey, SetContext, SetPaymentOverrideNotif, etc from Options object on the client, check the usage detail on how to configure options here

Alternative, perform Core API Charge with Map type

Snap client have ...WithMap function, which is useful if you want to send custom JSON payload that the type/struct is not defined in this module. Refer to file sample.go in folder Snap API simple sample.

2.4 CoreApi

Available methods for CoreApi

// ChargeTransaction : Do `/charge` API request to Midtrans Core API return `coreapi.Response` with `coreapi.ChargeReq`
func ChargeTransaction(req *ChargeReq) (*Response, *midtrans.Error)

// ChargeTransactionWithMap : Do `/charge` API request to Midtrans Core API return RAW MAP with Map as
func ChargeTransactionWithMap(req *ChargeReqWithMap) (ResponseWithMap, *midtrans.Error)

// CardToken : Do `/token` API request to Midtrans Core API return `coreapi.Response`,
func CardToken(cardNumber string, expMonth int, expYear int, cvv string) (*CardTokenResponse, *midtrans.Error)

// RegisterCard : Do `/card/register` API request to Midtrans Core API return `coreapi.Response`,
func RegisterCard(cardNumber string, expMonth int, expYear int, cvv string) (*CardRegisterResponse, *midtrans.Error) 

// CardPointInquiry : Do `/point_inquiry/{tokenId}` API request to Midtrans Core API return `coreapi.Response`,
func CardPointInquiry(cardToken string) (*CardTokenResponse, *midtrans.Error)

// GetBIN : Do `/v1/bins/{bin}` API request to Midtrans Core API return `coreapi.BinResponse`,
func GetBIN(binNumber string) (*BinResponse, *midtrans.Error)

// CheckTransaction : Do `/{orderId}/status` API request to Midtrans Core API return `coreapi.Response`,
func CheckTransaction(param string) (*Response, *midtrans.Error)

// ApproveTransaction : Do `/{orderId}/approve` API request to Midtrans Core API return `coreapi.Response`,
func ApproveTransaction(param string) (*Response, *midtrans.Error)

// DenyTransaction : Do `/{orderId}/deny` API request to Midtrans Core API return `coreapi.Response`,
func DenyTransaction(param string) (*Response, *midtrans.Error)

// CancelTransaction : Do `/{orderId}/cancel` API request to Midtrans Core API return `coreapi.Response`,
func CancelTransaction(param string) (*Response, *midtrans.Error)

// ExpireTransaction : Do `/{orderId}/expire` API request to Midtrans Core API return `coreapi.Response`,
func ExpireTransaction(param string) (*Response, *midtrans.Error)

// RefundTransaction : Do `/{orderId}/refund` API request to Midtrans Core API return `coreapi.Response`,
// with `coreapi.RefundReq` as body parameter, will be converted to JSON,
func RefundTransaction(param string, req *RefundReq) (*Response, *midtrans.Error)

// DirectRefundTransaction : Do `/{orderId}/refund/online/direct` API request to Midtrans Core API return `coreapi.Response`,
// with `coreapi.RefundReq` as body parameter, will be converted to JSON,
func DirectRefundTransaction(param string, req *RefundReq) (*Response, *midtrans.Error)

// CaptureTransaction : Do `/{orderId}/capture` API request to Midtrans Core API return `coreapi.Response`,
// with `coreapi.CaptureReq` as body parameter, will be converted to JSON,
func CaptureTransaction(req *CaptureReq) (*Response, *midtrans.Error)

// GetStatusB2B : Do `/{orderId}/status/b2b` API request to Midtrans Core API return `coreapi.Response`,
func GetStatusB2B(param string) (*Response, *midtrans.Error)

2.4.1 Using global Config & static function

Sample usage if you prefer Midtrans global configuration & using static function. Useful if you only use 1 merchant account API key, and keep the code short.

// 1. Set you ServerKey with globally
midtrans.ServerKey = "YOUR-SERVER-KEY"
midtrans.Environment = midtrans.Sandbox

// 2. Initiate charge request
chargeReq := &coreapi.ChargeReq{
    PaymentType: coreapi.PaymentTypeCreditCard,
    TransactionDetails: midtrans.TransactionDetails{
        OrderID:  "12345",
        GrossAmt: 200000,
    },
    CreditCard: &coreapi.CreditCardDetails{
        TokenID:        "YOUR-CC-TOKEN",
        Authentication: true,
    },
    Items: &[]midtrans.ItemDetails{
        {
            ID:    "ITEM1",
            Price: 200000,
            Qty:   1,
            Name:  "Someitem",
        },
    },
}

// 3. Request to Midtrans using global config
coreApiRes, _ := coreapi.ChargeTransaction(chargeReq)
fmt.Println("Response :", coreApiRes)

2.4.2 Using Client

Sample usage if you prefer to use client instance & config. Useful if you plan to use multiple merchant account API keys, want to have multiple client instances, or prefer the code to be object-oriented.

```go // 1. Initiate coreapi client
c := coreapi.Client{} c.New("YOUR-SERVER-KEY", midtrans.Sandbox)

// 2. Initiate charge request chargeReq := &coreapi.ChargeReq{ PaymentType: midtrans.SourceCreditCard, TransactionDetails: midtrans.TransactionDetails{ OrderID: "12345", GrossAmt: 200000, }, CreditCard: &coreapi.CreditCardDetails{ TokenID: "YOUR-CC-TOKEN", Authentication: true, }, It

Extension points exported contracts — how you extend this code

Core symbols most depended-on inside this repo

Shape

Function 170
Struct 93
Method 70
TypeAlias 10
Interface 2

Languages

Go100%

Modules by API surface

coreapi/request.go25 symbols
coreapi/response.go20 symbols
coreapi/client_test.go20 symbols
coreapi/clienttransaction.go18 symbols
iris/response.go16 symbols
iris/client.go16 symbols
example/simple/iris/sample.go16 symbols
snap/request.go15 symbols
snap/client.go15 symbols
iris/client_test.go15 symbols
coreapi/client.go15 symbols
midtrans.go14 symbols

For agents

$ claude mcp add midtrans-go \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page