### Install Midtrans Go Library with go get Source: https://github.com/midtrans/midtrans-go/blob/main/README.md Installs or updates the `midtrans-go` library using the `go get` command. This command fetches the package and its dependencies, making them available for use in your Go project. ```Go go get -u github.com/midtrans/midtrans-go ``` -------------------------------- ### Initialize Midtrans Iris Client and Fetch Beneficiary Banks in Go Source: https://github.com/midtrans/midtrans-go/blob/main/README.md This Go example shows how to initialize the Midtrans Iris client using a specific Iris API key and the desired environment. It then demonstrates calling the `GetBeneficiaryBanks` method to retrieve a list of banks supported by the Iris platform. ```go var i iris.Client i.New("YOUR-IRIS-API-KEY", midtrans.Sandbox) res, _ := i.GetBeneficiaryBanks() fmt.Println("Response: ", res) ``` -------------------------------- ### Implement Midtrans Snap Payment Page on Frontend (HTML/JavaScript) Source: https://github.com/midtrans/midtrans-go/blob/main/README.md Provides an example of an HTML payment page integrating the Midtrans Snap.js library. It shows how to initialize the Snap payment flow using a transaction token and handle payment outcomes (success, pending, error) with JavaScript callbacks. ```html
JSON result will appear here after payment:
``` -------------------------------- ### Perform Various Transaction Actions with Midtrans Go SDK Source: https://github.com/midtrans/midtrans-go/blob/main/README.md This section provides Go code examples for interacting with Midtrans to manage transaction lifecycles. It includes functions for checking transaction status (both general and B2B VA), approving, denying, canceling, capturing, expiring, and refunding transactions. These functions typically take an order or transaction ID and return a response object, with some requiring additional request bodies for capture and refund operations. ```go // get status of transaction that already recorded on midtrans (already `charge`-ed) res, _ := c.CheckTransaction("YOUR_ORDER_ID OR TRANSACTION_ID") if res != nil { // do something to `res` object } ``` ```go // get transaction status of VA b2b transaction res, _ := c.GetStatusB2B("YOUR_ORDER_ID OR TRANSACTION_ID") if res != nil { // do something to `res` object } ``` ```go // approve a credit card transaction with `challenge` fraud status res, _ := c.ApproveTransaction("YOUR_ORDER_ID OR TRANSACTION_ID") if res != nil { // do something to `res` object } ``` ```go // deny a credit card transaction with `challenge` fraud status res, _ := c.DenyTransaction("YOUR_ORDER_ID OR TRANSACTION_ID") if res != nil { // do something to `res` object } ``` ```go // cancel a credit card transaction or pending transaction res, _ := c.CancelTransaction("YOUR_ORDER_ID OR TRANSACTION_ID") if res != nil { // do something to `res` object } ``` ```go // Capture an authorized transaction for card payment refundRequest := &coreapi.CaptureReq{ TransactionID: "TRANSACTION-ID", GrossAmt: 10000, } res, _ := c.CaptureTransaction(refundRequest) if res != nil { // do something to `res` object } ``` ```go // expire a pending transaction res, _ := c.ExpireTransaction("YOUR_ORDER_ID OR TRANSACTION_ID") if res != nil { // do something to `res` object } ``` ```go refundRequest := &coreapi.RefundReq{ Amount: 5000, Reason: "Item out of stock", } res, _ := c.RefundTransaction("YOUR_ORDER_ID OR TRANSACTION_ID", refundRequest) if res != nil { // do something to `res` object } ``` ```go refundRequest := &coreapi.RefundReq{ RefundKey: "order1-ref1", Amount: 5000, Reason: "Item out of stock", } res, _ := c.DirectRefundTransaction("YOUR_ORDER_ID OR TRANSACTION_ID", refundRequest) if res != nil { // do something to `res` object } ``` -------------------------------- ### Initialize Midtrans API Clients Source: https://github.com/midtrans/midtrans-go/blob/main/README.md Demonstrates how to initialize specific Midtrans API clients for CoreAPI, Snap, and Iris Disbursement. Each client requires a server key (or Iris API key) and an environment setting (Sandbox or Production) to establish a connection with the Midtrans API. ```Go //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) ``` -------------------------------- ### Integrate Midtrans Snap API with Client Instance (Go) Source: https://github.com/midtrans/midtrans-go/blob/main/README.md Illustrates how to integrate with the Midtrans Snap API using a client instance in Go. This method is recommended for applications requiring multiple merchant account API keys, offering an object-oriented approach for managing transactions. ```go // 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) ``` -------------------------------- ### Integrate Midtrans Snap API with Global Configuration (Go) Source: https://github.com/midtrans/midtrans-go/blob/main/README.md Demonstrates how to integrate with the Midtrans Snap API using a global configuration and static functions in Go. This approach is suitable for applications using a single merchant account API key, providing a concise way to create Snap transactions. ```go // 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) ``` -------------------------------- ### Configure Midtrans Go Globally and Charge Transaction Source: https://github.com/midtrans/midtrans-go/blob/main/README.md Demonstrates how to set up global server key and environment for the Midtrans Go library, followed by initiating and executing a credit card charge request using the `ChargeTransaction` static function. This approach is useful for single merchant accounts and simplifies code by leveraging global configuration. ```Go // 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) ``` -------------------------------- ### Import Midtrans Go Packages Source: https://github.com/midtrans/midtrans-go/blob/main/README.md Imports the necessary Midtrans Go packages into your project. This includes the main `midtrans-go` package and specific client packages for CoreAPI, Snap, and Iris, allowing access to their functionalities. ```Go import ( "github.com/midtrans/midtrans-go" "github.com/midtrans/midtrans-go/coreapi" "github.com/midtrans/midtrans-go/snap" "github.com/midtrans/midtrans-go/iris" ) ``` -------------------------------- ### Go: Midtrans Server and Client Key Configuration Source: https://github.com/midtrans/midtrans-go/blob/main/example/simple/coreapi-card-3ds/views/index.html Instructions for setting up Midtrans API keys (server key and client key) in the `main.go` file. These keys are essential for authenticating requests to the Midtrans API from your backend. ```Go SERVER_KEY = "" CLIENT_KEY = "" ``` -------------------------------- ### Perform Midtrans Core API Charge using Go Client Source: https://github.com/midtrans/midtrans-go/blob/main/README.md This Go snippet demonstrates how to initialize the Midtrans Core API client with a server key and environment. It then constructs a `ChargeReq` for a credit card transaction, including transaction details, item details, and credit card token, and executes the charge. ```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, }, Items: &[]midtrans.ItemDetail{ coreapi.ItemDetail{ ID: "ITEM1", Price: 200000, Qty: 1, Name: "Someitem", }, }, } // 3. Request to Midtrans coreApiRes, _ := c.ChargeTransaction(chargeReq) fmt.Println("Response :", coreApiRes) ``` -------------------------------- ### Midtrans Go CoreAPI Method Reference Source: https://github.com/midtrans/midtrans-go/blob/main/README.md Comprehensive reference for all available methods within the `CoreApi` of the `midtrans-go` library, detailing functions for transaction management, card operations, and inquiry services. Each method signature includes parameters and return types, derived from the Go function definitions and their preceding comments. ```APIDOC ChargeTransaction(req *ChargeReq) (*Response, *midtrans.Error) - Description: Do `/charge` API request to Midtrans Core API, returns `coreapi.Response` with `coreapi.ChargeReq`. - Parameters: - req: Pointer to `ChargeReq` containing transaction details. - Returns: Pointer to `Response` and `*midtrans.Error`. ChargeTransactionWithMap(req *ChargeReqWithMap) (ResponseWithMap, *midtrans.Error) - Description: Do `/charge` API request to Midtrans Core API, returns RAW MAP. - Parameters: - req: Pointer to `ChargeReqWithMap`. - Returns: `ResponseWithMap` and `*midtrans.Error`. CardToken(cardNumber string, expMonth int, expYear int, cvv string) (*CardTokenResponse, *midtrans.Error) - Description: Do `/token` API request to Midtrans Core API. - Parameters: - cardNumber: Credit card number. - expMonth: Expiration month. - expYear: Expiration year. - cvv: Card Verification Value. - Returns: Pointer to `CardTokenResponse` and `*midtrans.Error`. RegisterCard(cardNumber string, expMonth int, expYear int, cvv string) (*CardRegisterResponse, *midtrans.Error) - Description: Do `/card/register` API request to Midtrans Core API. - Parameters: - cardNumber: Credit card number. - expMonth: Expiration month. - expYear: Expiration year. - cvv: Card Verification Value. - Returns: Pointer to `CardRegisterResponse` and `*midtrans.Error`. CardPointInquiry(cardToken string) (*CardTokenResponse, *midtrans.Error) - Description: Do `/point_inquiry/{tokenId}` API request to Midtrans Core API. - Parameters: - cardToken: The token ID of the card. - Returns: Pointer to `CardTokenResponse` and `*midtrans.Error`. GetBIN(binNumber string) (*BinResponse, *midtrans.Error) - Description: Do `/v1/bins/{bin}` API request to Midtrans Core API. - Parameters: - binNumber: The BIN (Bank Identification Number) to inquire. - Returns: Pointer to `BinResponse` and `*midtrans.Error`. CheckTransaction(param string) (*Response, *midtrans.Error) - Description: Do `/{orderId}/status` API request to Midtrans Core API. - Parameters: - param: The order ID of the transaction. - Returns: Pointer to `Response` and `*midtrans.Error`. ApproveTransaction(param string) (*Response, *midtrans.Error) - Description: Do `/{orderId}/approve` API request to Midtrans Core API. - Parameters: - param: The order ID of the transaction. - Returns: Pointer to `Response` and `*midtrans.Error`. DenyTransaction(param string) (*Response, *midtrans.Error) - Description: Do `/{orderId}/deny` API request to Midtrans Core API. - Parameters: - param: The order ID of the transaction. - Returns: Pointer to `Response` and `*midtrans.Error`. CancelTransaction(param string) (*Response, *midtrans.Error) - Description: Do `/{orderId}/cancel` API request to Midtrans Core API. - Parameters: - param: The order ID of the transaction. - Returns: Pointer to `Response` and `*midtrans.Error`. ExpireTransaction(param string) (*Response, *midtrans.Error) - Description: Do `/{orderId}/expire` API request to Midtrans Core API. - Parameters: - param: The order ID of the transaction. - Returns: Pointer to `Response` and `*midtrans.Error`. RefundTransaction(param string, req *RefundReq) (*Response, *midtrans.Error) - Description: Do `/{orderId}/refund` API request to Midtrans Core API with `coreapi.RefundReq` as body parameter, converted to JSON. - Parameters: - param: The order ID of the transaction. - req: Pointer to `RefundReq` containing refund details. - Returns: Pointer to `Response` and `*midtrans.Error`. DirectRefundTransaction(param string, req *RefundReq) (*Response, *midtrans.Error) - Description: Do `/{orderId}/refund/online/direct` API request to Midtrans Core API with `coreapi.RefundReq` as body parameter, converted to JSON. - Parameters: - param: The order ID of the transaction. - req: Pointer to `RefundReq` containing refund details. - Returns: Pointer to `Response` and `*midtrans.Error`. CaptureTransaction(req *CaptureReq) (*Response, *midtrans.Error) - Description: Do `/{orderId}/capture` API request to Midtrans Core API with `coreapi.CaptureReq` as body parameter, converted to JSON. - Parameters: - req: Pointer to `CaptureReq` containing capture details. - Returns: Pointer to `Response` and `*midtrans.Error`. GetStatusB2B(param string) (*Response, *midtrans.Error) - Description: Do `/{orderId}/status/b2b` API request to Midtrans Core API. - Parameters: - param: The order ID of the transaction. - Returns: Pointer to `Response` and `*midtrans.Error`. ``` -------------------------------- ### Initialize Go Module Source: https://github.com/midtrans/midtrans-go/blob/main/README.md Initializes a new Go module in your project directory. This command creates a `go.mod` file, which is essential for managing dependencies in Go applications. ```Go go mod init ``` -------------------------------- ### Configure Midtrans Globally Source: https://github.com/midtrans/midtrans-go/blob/main/README.md Sets the Midtrans server key and environment globally for all Midtrans API calls (except Iris API). This approach simplifies configuration by applying settings across different client instances. ```Go midtrans.ServerKey = "YOUR-SERVER-KEY" midtrans.Environment = midtrans.Sandbox ``` -------------------------------- ### Midtrans Snap API Methods Source: https://github.com/midtrans/midtrans-go/blob/main/README.md Provides an overview of the available methods for interacting with the Midtrans Snap API. These functions allow you to create transactions, retrieve Snap tokens, and obtain redirect URLs, supporting both structured requests and map-based parameters. ```APIDOC // 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) ``` -------------------------------- ### Run Go Package Unit Tests Source: https://github.com/midtrans/midtrans-go/blob/main/maintaining.md These commands execute the unit tests for specific modules within the Midtrans Go package, ensuring the stability and correctness of coreapi, snap, and iris functionalities. ```Shell go test github.com/midtrans/midtrans-go/coreapi ``` ```Shell go test github.com/midtrans/midtrans-go/snap ``` ```Shell go test github.com/midtrans/midtrans-go/iris ``` -------------------------------- ### Set Go Context for Midtrans API Requests (Go) Source: https://github.com/midtrans/midtrans-go/blob/main/README.md Explains how to associate a Go `context.Context` with Midtrans API requests using the client's options. This enables context-aware operations such as cancellation and deadlines for underlying HTTP calls. ```go c.Options.SetContext(context.Background()) ``` -------------------------------- ### Utilize Go Standard Error Interface for Midtrans Errors (Go) Source: https://github.com/midtrans/midtrans-go/blob/main/README.md Explains how to leverage Go's standard error handling features, specifically `errors.As` and `errors.Unwrap`, with `midtrans.Error` objects. This enables type-safe error inspection and the ability to unwrap nested errors for more robust error management. ```go // sample using errors.As _, err := c.chargeTransaction(param) var Err *midtrans.Error if errors.As(err, &Err) { fmt.Println(Err.Message) fmt.Println(Err.StatusCode) } // sample using unwrap _, err := c.chargeTransaction(param) if err != nil { log.Print(errors.Unwrap(err)) fmt.Print(err) } ``` -------------------------------- ### Generate Comprehensive Midtrans Snap Request (Go) Source: https://github.com/midtrans/midtrans-go/blob/main/README.md Shows how to construct a more complete Midtrans Snap request payload in Go, including detailed customer address information and multiple item details. This function can be used to generate a rich transaction request for the Snap API. ```go 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 } ``` -------------------------------- ### Midtrans: Testing Card Numbers for Various Scenarios Source: https://github.com/midtrans/midtrans-go/blob/main/example/simple/coreapi-card-3ds/views/index.html A reference list of test credit card numbers provided by Midtrans to simulate different transaction outcomes, including successful transactions, denials by bank, denials by Fraud Detection System (FDS), and transactions requiring FDS challenge. ```APIDOC Testing cards: For 3D Secure: Visa success 4811 1111 1111 1114 Visa deny by bank 4711 1111 1111 1115 Visa deny by FDS 4611 1111 1111 1116 MasterCard success 5211 1111 1111 1117 MasterCard deny by bank 5111 1111 1111 1118 MasterCard deny by FDS 5411 1111 1111 1115 Challenge by FDS 4511 1111 1111 1117 ``` -------------------------------- ### Handle Midtrans API Errors and Extract Details (Go) Source: https://github.com/midtrans/midtrans-go/blob/main/README.md Demonstrates how to handle errors returned by Midtrans API calls, specifically focusing on the `midtrans.Error` object. It shows how to extract general messages, HTTP status codes, raw API responses, and the underlying Go error object for detailed error analysis. ```go _, err = c.chargeTransaction(param) if err != nil { msg := err.Error() // general message error stsCode := err.GetStatusCode() // HTTP status code e.g: 400, 401, etc. rawApiRes := err.GetRawApiResponse() // raw Go HTTP response object rawErr := err.Unwrap() // raw Go err object } ``` -------------------------------- ### Set Midtrans Payment Notification URLs via Client Options (Go) Source: https://github.com/midtrans/midtrans-go/blob/main/README.md Shows how to set append or override notification URLs for specific Midtrans API requests using client options. This allows for per-request customization, providing flexibility to override any global settings. ```go // 1. Initiate Gateway var c = coreapi.Client c.New("YOUR-SERVER-KEY", midtrans.Sandbox) // 2. Set Payment Override or Append via gateway options for specific request c.Options.SetPaymentAppendNotification("YOUR-APPEND-NOTIFICATION-ENDPOINT") c.Options.SetPaymentOverrideNotification("YOUR-APPEND-NOTIFICATION-ENDPOINT") // 3. Then request to Midtrans API res, _ := c.ChargeRequest("YOUR-REQUEST") ``` -------------------------------- ### JavaScript: Midtrans 3D Secure Client-Side Checkout Flow Source: https://github.com/midtrans/midtrans-go/blob/main/example/simple/coreapi-card-3ds/views/index.html Client-side JavaScript implementation for handling the Midtrans 3D Secure payment flow. This includes capturing card details, obtaining a card token, sending the token to the backend for charging, handling 3D Secure authentication redirects, and processing transaction results. It uses `MidtransNew3ds` and `fetch` API. ```JavaScript document.querySelector(".submit-button").onclick = function (event) { console.log("SUBMIT button clicked"); // prepare cardData var cardData = { "card_number": document.querySelector(".card-number").value, "card_exp_month": document.querySelector(".card-expiry-month").value, "card_exp_year": document.querySelector(".card-expiry-year").value, "card_cvv": document.querySelector(".card-cvv").value }; console.log('[1] Use card data to get card token on the callback'); MidtransNew3ds.getCardToken(cardData, getCardTokenCallback); event.preventDefault(); return false; }; // getCardTokenCallback triggered when `MidtransNew3ds.getCardToken` completed. var getCardTokenCallback = { onSuccess: function(response){ // success to get card token // send token_id, secure params // we send secure param for sample, in production, you should define transaction is secure/not in backend // we recommend always use secure=true console.log('[2] Send AJAX to let backend charge the card using the card token_id'); fetch("/charge_core_api_ajax", { method : "POST", body: JSON.stringify({ "token_id" : response.token_id, "authenticate_3ds" : document.querySelector('.authenticate_3ds').checked }), headers: {'Content-Type': 'application/json'} }) .then(function(response) { return response.json(); }) .then(function(responseObj) { console.log('[3] response charge from backend:', responseObj); if (responseObj.status_code == "201"){ console.log('[3.1] Transaction need 3DS authentication'); MidtransNew3ds.authenticate(responseObj.redirect_url, callback3dsAuthentication); } else { // Transaction do not need 3DS Authentication, transaction is complete with result transactionComplete(responseObj); } }) }, onFailure: function(response){ console.log(response); alert(response.status_message); transactionComplete(response); } }; var callback3dsAuthentication = { performAuthentication: function(redirect_url){ // [3.2] 3ds authentication redirect_url received, open iframe to display to customer popupModal.openPopup(redirect_url); }, // [3.3] When 3DS authentication result received, which contains transaction result // it will trigger one of function below, according to status: success/failure/pending onSuccess: function(response){ transactionComplete(response); }, onFailure: function(response){ transactionComplete(response); }, onPending: function(response){ transactionComplete(response); } }; function transactionComplete(responseObj){ // Close 3DS popup, then display the result (for example) console.log("transactionComplete with status: ",responseObj); popupModal.closePopup(); document.querySelector("#result").innerText = JSON.stringify(responseObj, null, 2); document.querySelector("#result").scrollIntoView(); if (responseObj.transaction_id){ // [4] Inform the result to backend update DB status and verify to Midtrans // Check backend implementation on `web.js` file, section `[4]` fetch('/check_transaction_status', { method : "POST", body: JSON.stringify({ "transaction_id" : responseObj.transaction_id }), headers: {'Content-Type': 'application/json'} }) .then(function(statusResponse) { return statusResponse.json(); } ) .then(function(statusResponseObj) { // Transaction status received after being verified console.log("Check transaction response:",statusResponseObj); // transactionComplete(statusResponseObj); document.querySelector("#status-result").innerText = JSON.stringify(statusResponseObj, null, 2); }) } } // helper functions below let popupModal = (function(){ let modal = null; return { openPopup(url){ modal = picoModal({ content:'', width: "75%", closeButton: false, overlayClose: false, escCloses: false }).show(); }, closePopup: function() { try { if (modal) { // Ensure modal instance exists before trying to close modal.close(); } } catch(e) { // Error handling for modal close } } }; })(); ``` -------------------------------- ### Handle Midtrans HTTP Notification Callback in Go Source: https://github.com/midtrans/midtrans-go/blob/main/README.md This Go function demonstrates how to set up an HTTP endpoint to receive and process Midtrans transaction status notifications. It parses the JSON payload, retrieves the order ID, checks the transaction status with Midtrans, and provides a structure for updating the local database based on the response. It handles various transaction statuses like capture, settlement, deny, cancel, expire, and pending. ```go func notification(w http.ResponseWriter, r *http.Request) { // 1. Initialize empty map var notificationPayload map[string]interface{} // 2. Parse JSON request body and use it to set json to payload err := json.NewDecoder(r.Body).Decode(¬ificationPayload) if err != nil { // do something on error when decode return } // 3. Get order-id from payload orderId, exists := notificationPayload["order_id"].(string) if !exists { // do something when key `order_id` not found return } // 4. Check transaction to Midtrans with param orderId transactionStatusResp, e := c.CheckTransaction(orderId) if e != nil { http.Error(w, e.GetMessage(), http.StatusInternalServerError) return } else { if transactionStatusResp != nil { // 5. Do set transaction status based on response from check transaction status if transactionStatusResp.TransactionStatus == "capture" { if transactionStatusResp.FraudStatus == "challenge" { // TODO set transaction status on your database to 'challenge' // e.g: 'Payment status challenged. Please take action on your Merchant Administration Portal } else if transactionStatusResp.FraudStatus == "accept" { // TODO set transaction status on your database to 'success' } } else if transactionStatusResp.TransactionStatus == "settlement" { // TODO set transaction status on your databaase to 'success' } else if transactionStatusResp.TransactionStatus == "deny" { // TODO you can ignore 'deny', because most of the time it allows payment retries // and later can become success } else if transactionStatusResp.TransactionStatus == "cancel" || transactionStatusResp.TransactionStatus == "expire" { // TODO set transaction status on your databaase to 'failure' } else if transactionStatusResp.TransactionStatus == "pending" { // TODO set transaction status on your databaase to 'pending' / waiting payment } } } w.Header().Set("Content-Type", "application/json") w.Write([]byte("ok")) } ``` -------------------------------- ### Manage Go Module Dependencies Source: https://github.com/midtrans/midtrans-go/blob/main/maintaining.md This command is used to add missing modules to go.mod and remove unused modules, ensuring the project's dependencies are correctly managed. ```Shell go mod tidy ``` -------------------------------- ### Override Default HTTP Client Timeout for Midtrans (Go) Source: https://github.com/midtrans/midtrans-go/blob/main/README.md Shows how to customize the default HTTP client timeout for Midtrans API calls. This allows developers to adjust the maximum time allowed for network operations, preventing indefinite waits. ```go t := 300 * time.Millisecond midtrans.DefaultGoHttpClient = &http.Client{ Timeout: t, } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.