{"id":21878077,"url":"https://github.com/midtrans/midtrans-go","last_synced_at":"2025-04-07T05:13:31.455Z","repository":{"id":41371725,"uuid":"372425997","full_name":"Midtrans/midtrans-go","owner":"Midtrans","description":"This is the Official Go API client/library for Midtrans Payment API. More information about the product and see documentation at http://docs.midtrans.com for more technical details","archived":false,"fork":false,"pushed_at":"2024-03-28T10:32:33.000Z","size":161,"stargazers_count":105,"open_issues_count":3,"forks_count":28,"subscribers_count":7,"default_branch":"main","last_synced_at":"2025-03-30T22:11:09.499Z","etag":null,"topics":["go","golang","golang-lib","midtrans-go","payment-gateway"],"latest_commit_sha":null,"homepage":"https://pkg.go.dev/github.com/midtrans/midtrans-go","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Midtrans.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-05-31T07:51:08.000Z","updated_at":"2025-03-13T14:23:21.000Z","dependencies_parsed_at":"2024-03-28T11:38:55.483Z","dependency_job_id":null,"html_url":"https://github.com/Midtrans/midtrans-go","commit_stats":null,"previous_names":[],"tags_count":13,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Midtrans%2Fmidtrans-go","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Midtrans%2Fmidtrans-go/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Midtrans%2Fmidtrans-go/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Midtrans%2Fmidtrans-go/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Midtrans","download_url":"https://codeload.github.com/Midtrans/midtrans-go/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247595335,"owners_count":20963943,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["go","golang","golang-lib","midtrans-go","payment-gateway"],"created_at":"2024-11-28T08:11:37.267Z","updated_at":"2025-04-07T05:13:31.426Z","avatar_url":"https://github.com/Midtrans.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Midtrans Go Library\n[![Go Report Card](https://goreportcard.com/badge/github.com/midtrans/midtrans-go)](https://goreportcard.com/report/github.com/midtrans/midtrans-go)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\nMidtrans :heart: Go !\n\nGo 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.\nIts small memory footprint is also an advantage of itself. This module will help you use Midtrans product's REST APIs in Go.\n\n## 1. Installation\n### 1.1 Using Go Module\nRun this command on your project to initialize Go mod (if you haven't):\n```go\ngo mod init\n```\nthen reference midtrans-go in your project file with `import`:\n```go\nimport (\n    \"github.com/midtrans/midtrans-go\"\n    \"github.com/midtrans/midtrans-go/coreapi\"\n    \"github.com/midtrans/midtrans-go/snap\"\n    \"github.com/midtrans/midtrans-go/iris\"\n)\n```\n\n### 1.2 Using go get\nAlso, the alternative way you can use `go get` the package into your project\n```go\ngo get -u github.com/midtrans/midtrans-go\n```\n## 2. Usage\nThere is a type named `Client` (`coreapi.Client`, `snap.Client`, `iris.Client`) that should be instantiated through\nfunction `New` which holds any possible setting to the library. Any activity (charge, approve, etc) is done in the client level.\n\n### 2.1 Choose Product/Method\nWe have [3 different products](https://beta-docs.midtrans.com/) that you can use:\n- [Snap](#22A-snap) - Customizable payment popup will appear on **your web/app** (no redirection). [doc ref](https://snap-docs.midtrans.com/)\n- [Snap Redirect](#22B-snap-redirect) - Customer need to be redirected to payment url **hosted by midtrans**. [doc ref](https://snap-docs.midtrans.com/)\n- [Core API (VT-Direct)](#22C-core-api-vt-direct) - Basic backend implementation, you can customize the frontend embedded on **your web/app** as you like (no redirection). [doc ref](https://api-docs.midtrans.com/)\n- [Iris Disbursement](#22D-iris-api) - Iris is Midtrans’ cash management solution that allows you to disburse payments to any bank accounts in Indonesia securely and easily. [doc ref](https://iris-docs.midtrans.com/)\n\nTo learn more and understand each of the product's quick overview you can visit https://docs.midtrans.com.\n\n\n### 2.2 Client Initialization and Configuration\nGet your client key and server key from [Midtrans Dashboard](https://dashboard.midtrans.com)\n\nCreate API client object, You can also check the [project's implementation](example/simple) for more examples. Please proceed there for more detail on how to run the example.\n\n#### 2.2.1 Using global config\nSet a config with globally, (except for iris api)\n\n```go\nmidtrans.ServerKey = \"YOUR-SERVER-KEY\"\nmidtrans.Environment = midtrans.Sandbox\n```\n\n#### 2.2.2 Using Client\n```go\n//Initiate client for Midtrans CoreAPI\nvar c = coreapi.Client\nc.New(\"YOUR-SERVER-KEY\", midtrans.Sandbox)\n\n//Initiate client for Midtrans Snap\nvar s = snap.Client\ns.New(\"YOUR-SERVER-KEY\", midtrans.Sandbox)\n\n//Initiate client for Iris disbursement\nvar i = iris.Client\ni.New(\"IRIS-API-KEY\", midtrans.Sandbox)\n```\n### 2.3 Snap\nSnap is Midtrans existing tool to help merchant charge customers using a mobile-friendly, in-page,\nno-redirect checkout facilities. [Using snap is simple](https://docs.midtrans.com/en/snap/overview).\n\nAvailable methods for Snap\n```go\n// CreateTransaction : Do `/transactions` API request to SNAP API to get Snap token and redirect url with `snap.Request`\nfunc CreateTransaction(req *snap.Request) (*Response, *midtrans.Error)\n\n// CreateTransactionToken : Do `/transactions` API request to SNAP API to get Snap token with `snap.Request`\nfunc CreateTransactionToken(req *snap.Request) (string, *midtrans.Error)\n\n// CreateTransactionUrl : Do `/transactions` API request to SNAP API to get Snap redirect url with `snap.Request`\nfunc CreateTransactionUrl(req *snap.Request) (string, *midtrans.Error)\n\n// CreateTransactionWithMap : Do `/transactions` API request to SNAP API to get Snap token and redirect url with Map request\nfunc CreateTransactionWithMap(req *snap.RequestParamWithMap) (ResponseWithMap, *midtrans.Error)\n\n// CreateTransactionTokenWithMap : Do `/transactions` API request to SNAP API to get Snap token with Map request\nfunc CreateTransactionTokenWithMap(req *snap.RequestParamWithMap) (string, *midtrans.Error)\n\n// CreateTransactionUrlWithMap : Do `/transactions` API request to SNAP API to get Snap redirect url with Map request\nfunc CreateTransactionUrlWithMap(req *snap.RequestParamWithMap) (string, *midtrans.Error) \n```\nSnap usage example, create transaction with minimum Snap parameters (choose **one** of alternatives below):\n#### 2.3.1 Using global Config \u0026 static function\nSample usage if you prefer Midtrans global configuration \u0026 using static function. Useful if you only use 1 merchant account API key, and keep the code short.\n```go\n// 1. Set you ServerKey with globally\nmidtrans.ServerKey = \"YOUR-SERVER-KEY\"\nmidtrans.Environment = midtrans.Sandbox\n\n// 2. Initiate Snap request\nreq := \u0026 snap.RequestParam{\n\tTransactionDetails: midtrans.TransactionDetails{\n\t\tOrderID:  \"YOUR-ORDER-ID-12345\", \n\t\tGrossAmt: 100000,\n\t}, \n\tCreditCard: \u0026snap.CreditCardDetails{\n\t\tSecure: true,\n\t},\n}\n\n// 3. Request create Snap transaction to Midtrans\nsnapResp, _ := CreateTransaction(req)\nfmt.Println(\"Response :\", snapResp)\n```\n#### 2.3.2 Using Client\nSample usage if you prefer to use client instance \u0026 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.\n\n```go\n// 1. Initiate Snap client\nvar s = snap.Client\ns.New(\"YOUR-SERVER-KEY\", midtrans.Sandbox)\n\n// 2. Initiate Snap request\nreq := \u0026 snap.RequestParam{\n\t\tTransactionDetails: midtrans.TransactionDetails{\n\t\t\tOrderID:  \"YOUR-ORDER-ID-12345\",\n\t\t\tGrossAmt: 100000,\n\t\t}, \n\t\tCreditCard: \u0026snap.CreditCardDetails{\n\t\t\tSecure: true,\n\t\t},\n\t}\n\n// 3. Request create Snap transaction to Midtrans\nsnapResp, _ := s.CreateTransaction(req)\nfmt.Println(\"Response :\", snapResp)\n```\n\nOn the frontend side (on the HTML payment page), you will [need to include snap.js library and implement the payment page](https://docs.midtrans.com/en/snap/integration-guide?id=_2-displaying-snap-payment-page-on-frontend).\n\nSample HTML payment page implementation:\n```html\n\u003chtml\u003e\n  \u003cbody\u003e\n    \u003cbutton id=\"pay-button\"\u003ePay!\u003c/button\u003e\n    \u003cpre\u003e\u003cdiv id=\"result-json\"\u003eJSON result will appear here after payment:\u003cbr\u003e\u003c/div\u003e\u003c/pre\u003e \n\n\u003c!-- TODO: Remove \".sandbox\" from script src URL for production environment. Also input your client key in \"data-client-key\" --\u003e\n    \u003cscript src=\"https://app.sandbox.midtrans.com/snap/snap.js\" data-client-key=\"\u003cSet your ClientKey here\u003e\"\u003e\u003c/script\u003e\n    \u003cscript type=\"text/javascript\"\u003e\n      document.getElementById('pay-button').onclick = function(){\n        // SnapToken acquired from previous step\n        snap.pay('PUT_TRANSACTION_TOKEN_HERE', {\n          // Optional\n          onSuccess: function(result){\n            /* You may add your own js here, this is just example */ document.getElementById('result-json').innerHTML += JSON.stringify(result, null, 2);\n          },\n          // Optional\n          onPending: function(result){\n            /* You may add your own js here, this is just example */ document.getElementById('result-json').innerHTML += JSON.stringify(result, null, 2);\n          },\n          // Optional\n          onError: function(result){\n            /* You may add your own js here, this is just example */ document.getElementById('result-json').innerHTML += JSON.stringify(result, null, 2);\n          }\n        });\n      };\n    \u003c/script\u003e\n  \u003c/body\u003e\n\u003c/html\u003e\n```\n\nYou may want to override those `onSuccess`, `onPending` and `onError` functions to implement the behaviour that you want on each respective event.\n\nThen implement Backend Notification Handler, [Refer to this section](README.md#26-handle-http-notification)\n\nAlternativelly, more complete Snap parameter:\n\n```go\nfunc GenerateSnapReq() *snap.Request {\n\t// Initiate Customer address\n\tcustAddress := \u0026midtrans.CustomerAddress{\n\t\tFName: \"John\",\n\t\tLName: \"Doe\",\n\t\tPhone: \"081234567890\",\n\t\tAddress: \"Baker Street 97th\",\n\t\tCity: \"Jakarta\",\n\t\tPostcode: \"16000\",\n\t\tCountryCode: \"IDN\",\n\t}\n\t\n\t// Initiate Snap Request\n\tsnapReq := \u0026snap.Request{\n\t\tTransactionDetails: midtrans.TransactionDetails{\n\t\t\tOrderID: \"YOUR-UNIQUE-ORDER-ID-1234\",\n\t\t\tGrossAmt: 200000,\n\t\t}, \n\t\tCreditCard: \u0026snap.CreditCardDetails{\n\t\t\tSecure: true,\n\t\t},\n\t\tCustomerDetail: \u0026midtrans.CustomerDetails{\n\t\t\tFName: \"John\",\n\t\t\tLName: \"Doe\",\n\t\t\tEmail: \"john@doe.com\",\n\t\t\tPhone: \"081234567890\",\n\t\t\tBillAddr: custAddress,\n\t\t\tShipAddr: custAddress,\n\t\t},\n\t\tItems: \u0026[]midtrans.ItemDetails{\n\t\t\tmidtrans.ItemDetails{\n\t\t\t\tID: \"ITEM1\",\n\t\t\t\tPrice: 200000,\n\t\t\t\tQty: 1,\n\t\t\t\tName: \"Someitem\",\n\t\t\t},\n\t\t},\n\t}\n\n return snapReq\n}\n```\n\n\u003e**INFO:**\n\u003e When using client, you can set config options like `SetIdempotencyKey`, `SetContext`, `SetPaymentOverrideNotif`, etc\n\u003e from Options object on the client, [check the usage detail on how to configure options here](README.md#3-advance-usage)\n\n#### Alternative, perform Core API Charge with Map type\nSnap 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](example/simple/snap/sample.go).\n\n### 2.4 CoreApi\nAvailable methods for `CoreApi`\n```go\n// ChargeTransaction : Do `/charge` API request to Midtrans Core API return `coreapi.Response` with `coreapi.ChargeReq`\nfunc ChargeTransaction(req *ChargeReq) (*Response, *midtrans.Error)\n\n// ChargeTransactionWithMap : Do `/charge` API request to Midtrans Core API return RAW MAP with Map as\nfunc ChargeTransactionWithMap(req *ChargeReqWithMap) (ResponseWithMap, *midtrans.Error)\n\n// CardToken : Do `/token` API request to Midtrans Core API return `coreapi.Response`,\nfunc CardToken(cardNumber string, expMonth int, expYear int, cvv string) (*CardTokenResponse, *midtrans.Error)\n\n// RegisterCard : Do `/card/register` API request to Midtrans Core API return `coreapi.Response`,\nfunc RegisterCard(cardNumber string, expMonth int, expYear int, cvv string) (*CardRegisterResponse, *midtrans.Error) \n\n// CardPointInquiry : Do `/point_inquiry/{tokenId}` API request to Midtrans Core API return `coreapi.Response`,\nfunc CardPointInquiry(cardToken string) (*CardTokenResponse, *midtrans.Error)\n\n// GetBIN : Do `/v1/bins/{bin}` API request to Midtrans Core API return `coreapi.BinResponse`,\nfunc GetBIN(binNumber string) (*BinResponse, *midtrans.Error)\n\n// CheckTransaction : Do `/{orderId}/status` API request to Midtrans Core API return `coreapi.Response`,\nfunc CheckTransaction(param string) (*Response, *midtrans.Error)\n\n// ApproveTransaction : Do `/{orderId}/approve` API request to Midtrans Core API return `coreapi.Response`,\nfunc ApproveTransaction(param string) (*Response, *midtrans.Error)\n\n// DenyTransaction : Do `/{orderId}/deny` API request to Midtrans Core API return `coreapi.Response`,\nfunc DenyTransaction(param string) (*Response, *midtrans.Error)\n\n// CancelTransaction : Do `/{orderId}/cancel` API request to Midtrans Core API return `coreapi.Response`,\nfunc CancelTransaction(param string) (*Response, *midtrans.Error)\n\n// ExpireTransaction : Do `/{orderId}/expire` API request to Midtrans Core API return `coreapi.Response`,\nfunc ExpireTransaction(param string) (*Response, *midtrans.Error)\n\n// RefundTransaction : Do `/{orderId}/refund` API request to Midtrans Core API return `coreapi.Response`,\n// with `coreapi.RefundReq` as body parameter, will be converted to JSON,\nfunc RefundTransaction(param string, req *RefundReq) (*Response, *midtrans.Error)\n\n// DirectRefundTransaction : Do `/{orderId}/refund/online/direct` API request to Midtrans Core API return `coreapi.Response`,\n// with `coreapi.RefundReq` as body parameter, will be converted to JSON,\nfunc DirectRefundTransaction(param string, req *RefundReq) (*Response, *midtrans.Error)\n\n// CaptureTransaction : Do `/{orderId}/capture` API request to Midtrans Core API return `coreapi.Response`,\n// with `coreapi.CaptureReq` as body parameter, will be converted to JSON,\nfunc CaptureTransaction(req *CaptureReq) (*Response, *midtrans.Error)\n\n// GetStatusB2B : Do `/{orderId}/status/b2b` API request to Midtrans Core API return `coreapi.Response`,\nfunc GetStatusB2B(param string) (*Response, *midtrans.Error)\n```\n#### 2.4.1 Using global Config \u0026 static function\nSample usage if you prefer Midtrans global configuration \u0026 using static function. Useful if you only use 1 merchant account API key, and keep the code short.\n\n```go\n// 1. Set you ServerKey with globally\nmidtrans.ServerKey = \"YOUR-SERVER-KEY\"\nmidtrans.Environment = midtrans.Sandbox\n\n// 2. Initiate charge request\nchargeReq := \u0026coreapi.ChargeReq{\n\tPaymentType: coreapi.PaymentTypeCreditCard,\n\tTransactionDetails: midtrans.TransactionDetails{\n\t\tOrderID:  \"12345\",\n\t\tGrossAmt: 200000,\n\t},\n\tCreditCard: \u0026coreapi.CreditCardDetails{\n\t\tTokenID:        \"YOUR-CC-TOKEN\",\n\t\tAuthentication: true,\n\t},\n\tItems: \u0026[]midtrans.ItemDetails{\n\t\t{\n\t\t\tID:    \"ITEM1\",\n\t\t\tPrice: 200000,\n\t\t\tQty:   1,\n\t\t\tName:  \"Someitem\",\n\t\t},\n\t},\n}\n\t\n// 3. Request to Midtrans using global config\ncoreApiRes, _ := coreapi.ChargeTransaction(chargeReq)\nfmt.Println(\"Response :\", coreApiRes)\n```\n#### 2.4.2 Using Client\nSample usage if you prefer to use client instance \u0026 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.\n\n```go\n// 1. Initiate coreapi client  \nc := coreapi.Client{}\nc.New(\"YOUR-SERVER-KEY\", midtrans.Sandbox)\n\n// 2. Initiate charge request\nchargeReq := \u0026coreapi.ChargeReq{\n\tPaymentType: midtrans.SourceCreditCard,\n\tTransactionDetails: midtrans.TransactionDetails{\n\t\tOrderID:  \"12345\",\n\t\tGrossAmt: 200000,\n\t},\n\tCreditCard: \u0026coreapi.CreditCardDetails{\n\t\tTokenID:        \"YOUR-CC-TOKEN\",\n\t\tAuthentication: true,\n\t},\n\tItems: \u0026[]midtrans.ItemDetail{\n\t\tcoreapi.ItemDetail{\n\t\t\tID:    \"ITEM1\",\n\t\t\tPrice: 200000,\n\t\t\tQty:   1,\n\t\t\tName:  \"Someitem\",\n\t\t},\n\t},\n}\n\n// 3. Request to Midtrans\ncoreApiRes, _ := c.ChargeTransaction(chargeReq)\nfmt.Println(\"Response :\", coreApiRes)\n```\n\u003e**INFO:**\n\u003e When using client, you can set config options like `SetIdempotencyKey`, `SetContext`, `SetPaymentOverrideNotif`, etc\n\u003e from Options object on the client, [check the usage detail on how to configure options here](README.md#3-advance-usage)\n\n#### Alternative, perform Core API Charge with Map type\nCoreApi client have `ChargeTransactionWithMap` 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 [Core API simple sample](example/simple/coreapi/sample.go).\n\n### 2.5 Iris Client\nIris is Midtrans cash management solution that allows you to disburse payments to any supported bank accounts securely and easily. Iris connects to the banks’ hosts to enable seamless transfer using integrated APIs.\nAvailable methods for `Iris`\n```go\n// CreateBeneficiaries : to perform create a new beneficiary information for quick access on the payout page in Iris Portal.\nfunc (c Client) CreateBeneficiaries(req Beneficiaries) (*BeneficiariesResponse, *midtrans.Error)\n\n// UpdateBeneficiaries : to update an existing beneficiary identified by its alias_name.\nfunc (c Client) UpdateBeneficiaries(aliasName string, req Beneficiaries) (*BeneficiariesResponse, *midtrans.Error)\n\n// GetBeneficiaries : This method to fetch list of all beneficiaries saved in Iris Portal.\nfunc (c Client) GetBeneficiaries() ([]Beneficiaries, *midtrans.Error)\n\n// CreatePayout : This method for Creator to create a payout. It can be used for single payout and also multiple payouts.\nfunc (c Client) CreatePayout(req CreatePayoutReq) (*CreatePayoutResponse, *midtrans.Error)\n\n// ApprovePayout : this method for Apporver to approve multiple payout request.\nfunc (c Client) ApprovePayout(req ApprovePayoutReq) (*ApprovePayoutResponse, *midtrans.Error)\n\n// RejectPayout : This method for Apporver to reject multiple payout request.\nfunc (c Client) RejectPayout(req RejectPayoutReq) (*RejectPayoutResponse, *midtrans.Error)\n\n// GetPayoutDetails : Get details of a single payout.\nfunc (c Client) GetPayoutDetails(referenceNo string) (*PayoutDetailResponse, *midtrans.Error)\n\n// GetTransactionHistory : Returns all the payout details for specific dates \nfunc (c Client) GetTransactionHistory(fromDate string, toDate string) ([]TransactionHistoryResponse, *midtrans.Error) \n\n// GetTopUpChannels : Provide top up information channel for Aggregator Partner\nfunc (c Client) GetTopUpChannels() ([]TopUpAccountResponse, *midtrans.Error)\n\n// GetBalance : For Aggregator Partner, you need to top up to Iris’ bank account. Every partner have their own balance in Iris’\n// bank account. Use this API is to get current balance information.\nfunc (c Client) GetBalance() (*BalanceResponse, *midtrans.Error) \n\n// GetListBankAccount : Show list of registered bank accounts for facilitator partner\nfunc (c Client) GetListBankAccount() ([]BankAccountResponse, *midtrans.Error)\n\n// GetFacilitatorBalance : For Facilitator Partner, use this API is to get current balance information of your registered bank account.\nfunc (c Client) GetFacilitatorBalance(accountId string) (*BalanceResponse, *midtrans.Error) \n\n// GetBeneficiaryBanks : Show list of supported banks in IRIS.\nfunc (c Client) GetBeneficiaryBanks() (*ListBeneficiaryBankResponse, *midtrans.Error)\n\n// ValidateBankAccount : Check if an account is valid, if valid return account information.\nfunc (c Client) ValidateBankAccount(bankName string, accountNo string) (*BankAccountDetailResponse, *midtrans.Error)\n```\n\n\u003eNote: `IrisApiKey` will be used in `Iris.Client`'s the API Key can be found in Iris Dashboard. The API Key is different to Midtrans' payment gateway account's API key.\n```go\nvar i iris.Client\ni.New(\"YOUR-IRIS-API-KEY\", midtrans.Sandbox)\n\nres, _ := i.GetBeneficiaryBanks()\nfmt.Println(\"Response: \", res)\n```\n\n### 2.6 Handle HTTP Notification\nCreate separated web endpoint (notification url) to receive HTTP POST notification callback/webhook.\nHTTP notification will be sent whenever transaction status is changed.\nExample also available in `sample.go` in folder [example/simple/coreapi](example/simple/coreapi/sample.go)\n\n```go\nfunc notification(w http.ResponseWriter, r *http.Request) {\n\t// 1. Initialize empty map\n\tvar notificationPayload map[string]interface{}\n\n\t// 2. Parse JSON request body and use it to set json to payload\n\terr := json.NewDecoder(r.Body).Decode(\u0026notificationPayload)\n\tif err != nil {\n\t\t// do something on error when decode\n\t\treturn\n\t}\n\t// 3. Get order-id from payload\n\torderId, exists := notificationPayload[\"order_id\"].(string)\n\tif !exists {\n\t\t// do something when key `order_id` not found\n\t\treturn\n\t}\n\n\t// 4. Check transaction to Midtrans with param orderId\n\ttransactionStatusResp, e := c.CheckTransaction(orderId)\n\tif e != nil {\n\t\thttp.Error(w, e.GetMessage(), http.StatusInternalServerError)\n\t\treturn\n\t} else {\n\t\tif transactionStatusResp != nil {\n\t\t\t// 5. Do set transaction status based on response from check transaction status\n\t\t\tif transactionStatusResp.TransactionStatus == \"capture\" {\n\t\t\t\tif transactionStatusResp.FraudStatus == \"challenge\" {\n\t\t\t\t\t// TODO set transaction status on your database to 'challenge'\n\t\t\t\t\t// e.g: 'Payment status challenged. Please take action on your Merchant Administration Portal\n\t\t\t\t} else if transactionStatusResp.FraudStatus == \"accept\" {\n\t\t\t\t\t// TODO set transaction status on your database to 'success'\n\t\t\t\t}\n\t\t\t} else if transactionStatusResp.TransactionStatus == \"settlement\" {\n\t\t\t\t// TODO set transaction status on your databaase to 'success'\n\t\t\t} else if transactionStatusResp.TransactionStatus == \"deny\" {\n\t\t\t\t// TODO you can ignore 'deny', because most of the time it allows payment retries\n\t\t\t\t// and later can become success\n\t\t\t} else if transactionStatusResp.TransactionStatus == \"cancel\" || transactionStatusResp.TransactionStatus == \"expire\" {\n\t\t\t\t// TODO set transaction status on your databaase to 'failure'\n\t\t\t} else if transactionStatusResp.TransactionStatus == \"pending\" {\n\t\t\t\t// TODO set transaction status on your databaase to 'pending' / waiting payment\n\t\t\t}\n\t\t}\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write([]byte(\"ok\"))\n}\n```\n### 2.7 Transaction Action\nOther functions related to actions that can be performed to transaction(s). Also available as examples [here](example/simple/transaction/sample.go)\n#### Get Status\n```go\n// get status of transaction that already recorded on midtrans (already `charge`-ed) \nres, _ := c.CheckTransaction(\"YOUR_ORDER_ID OR TRANSACTION_ID\")\nif res != nil {\n// do something to `res` object\n}\n```\n#### Get Status B2B\n```go\n// get transaction status of VA b2b transaction\nres, _ := c.GetStatusB2B(\"YOUR_ORDER_ID OR TRANSACTION_ID\")\nif res != nil {\n// do something to `res` object\n}\n```\n#### Approve Transaction\n```go\n// approve a credit card transaction with `challenge` fraud status\nres, _ := c.ApproveTransaction(\"YOUR_ORDER_ID OR TRANSACTION_ID\")\nif res != nil {\n// do something to `res` object\n}\n```\n#### Deny Transaction\n```go\n// deny a credit card transaction with `challenge` fraud status\nres, _ := c.DenyTransaction(\"YOUR_ORDER_ID OR TRANSACTION_ID\")\nif res != nil {\n// do something to `res` object\n}\n```\n#### Cancel Transaction\n```go\n// cancel a credit card transaction or pending transaction\nres, _ := c.CancelTransaction(\"YOUR_ORDER_ID OR TRANSACTION_ID\")\nif res != nil {\n// do something to `res` object\n}\n```\n#### Capture Transaction\n```go\n// Capture an authorized transaction for card payment\nrefundRequest := \u0026coreapi.CaptureReq{\n\tTransactionID: \"TRANSACTION-ID\", \n\tGrossAmt:      10000,\n}\nres, _ := c.CaptureTransaction(refundRequest)\nif res != nil {\n// do something to `res` object\n}\n```\n#### Expire Transaction\n```go\n// expire a pending transaction\nres, _ := c.ExpireTransaction(\"YOUR_ORDER_ID OR TRANSACTION_ID\")\nif res != nil {\n// do something to `res` object\n}\n```\n#### Refund Transaction\n```go\nrefundRequest := \u0026coreapi.RefundReq{\n\tAmount:    5000, \n\tReason:    \"Item out of stock\",\n}\n\nres, _ := c.RefundTransaction(\"YOUR_ORDER_ID OR TRANSACTION_ID\", refundRequest)\nif res != nil {\n// do something to `res` object\n}\n```\n#### Refund Transaction with Direct Refund\n```go\nrefundRequest := \u0026coreapi.RefundReq{\n\t\tRefundKey: \"order1-ref1\",\n\t\tAmount:    5000,\n\t\tReason:    \"Item out of stock\",\n\t}\n\t\nres, _ := c.DirectRefundTransaction(\"YOUR_ORDER_ID OR TRANSACTION_ID\", refundRequest)\nif res != nil {\n// do something to `res` object\n}\n```\n## 3. Advance Usage\n### 3.1 Override Notification Url\nMerchant can opt to change or add custom notification urls on every transaction. It can be achieved by adding additional HTTP headers into charge request.\nFor Midtrans Payment, there are two headers we provide:\n\n1. `X-Append-Notification`: to add new notification url(s) alongside the settings on dashboard\n2. `X-Override-Notification`: to use new notification url(s) disregarding the settings on dashboard\n   Both header can only receive up to maximum of **3 urls**.\n\n\u003e **Note:** When both `SetPaymentAppendNotif` and `SetPaymentOverrideNotif` are used together then only `OverrideNotif` will be used.\n\n#### 3.1.1 Set Override/Append notification globally\n```go\n// Set override or append for globally\nmidtrans.SetPaymentAppendNotification(\"YOUR-APPEND-NOTIFICATION-ENDPOINT\")\nmidtrans.SetPaymentOverrideNotification(\"YOUR-OVERRID-NOTIFICATION-ENDPOINT\")\n```\n#### 3.1.2 Set Override/Append notification via client options\n```go\n// 1. Initiate Gateway\nvar c = coreapi.Client\nc.New(\"YOUR-SERVER-KEY\", midtrans.Sandbox)\n\n// 2. Set Payment Override or Append via gateway options for specific request\nc.Options.SetPaymentAppendNotification(\"YOUR-APPEND-NOTIFICATION-ENDPOINT\")\nc.Options.SetPaymentOverrideNotification(\"YOUR-APPEND-NOTIFICATION-ENDPOINT\")\n\n// 3. Then request to Midtrans API\nres, _ := c.ChargeRequest(\"YOUR-REQUEST\")\n```\nPlease see our documentation for [the details](https://api-docs.midtrans.com/#override-notification-url) about the feature\n\n### 3.2 Request using go Context\nWith Gateway options object you can set Go Context for each request by the net/http machinery, and is available with `SetContext()` method.\n```go\nc.Options.SetContext(context.Background())\n```\n\n### 3.3 Log Configuration\nBy default in `Sandbox` the log level will use `LogDebug` level, that outputs informational messages for debugging. In `Production` this module will only logs the error messages (`LogError` level), that outputs error message to `os.stderr`.\nYou have option to change the default log level configuration with global variable `midtrans.DefaultLoggerLevel`:\n```go\nmidtrans.DefaultLoggerLevel = \u0026midtrans.LoggerImplementation{LogLevel: midtrans.LogDebug}\n\n// Details Log Level\n// NoLogging    : sets a logger to not show the messages\n// LogError     : sets a logger to show error messages only.\n// LogInfo      : sets a logger to show information messages\n// LogDebug     : sets a logger to show informational messages for debugging\n```\n\n### 3.4 Override HTTP Client timeout\nBy default, timeout value for HTTP Client 80 seconds. But you can override the HTTP client default config from global variable `midtrans.DefaultGoHttpClient`:\n```go\nt := 300 * time.Millisecond\nmidtrans.DefaultGoHttpClient = \u0026http.Client{\n\tTimeout:       t,\n}\n```\n\n## 4. Handling Error\nWhen using function that result in Midtrans API call e.g: c.ChargeTransaction(...) or s.CreateTransaction(...) there's a chance it may throw error (Midtrans [Error object](/error.go)), the error object will contains below properties that can be used as information to your error handling logic:\n```go\n    _, err = c.chargeTransaction(param)\n    if err != nil {\n        msg := err.Error()                     // general message error\n        stsCode := err.GetStatusCode()         // HTTP status code e.g: 400, 401, etc.\n        rawApiRes := err.GetRawApiResponse()   // raw Go HTTP response object\n        rawErr := err.Unwrap()                 // raw Go err object\n    }\n```\nmidtrans.error complies with [Go standard error](https://go.dev/blog/go1.13-errors). which support `Error, Unwrap, Is, As`.\n```go\n// sample using errors.As\n_, err := c.chargeTransaction(param)\nvar Err *midtrans.Error\nif errors.As(err, \u0026Err) {\n\tfmt.Println(Err.Message)\n\tfmt.Println(Err.StatusCode)\n}\n\n// sample using unwrap\n_, err := c.chargeTransaction(param)\nif err != nil {\n\tlog.Print(errors.Unwrap(err))\n    fmt.Print(err)\n}\n```\n\n## 5. Examples\nExamples are available on [/examples](example) folder\nThere are:\n- [Core Api examples](example/simple/coreapi/sample.go)\n- [Snap examples](example/simple/snap/sample.go)\n- [Iris examples](example/simple/iris/sample.go)\n- [Readme Example](example/README.md)\n\nIntegration test are available\n- [CoreApi Sample Functional Test](coreapi/client_test.go)\n- [Snap Sample Functional Test](snap/client_test.go)\n- [Iris Sample Functional Test](iris/client_test.go)\n\n\n## Get help\n\n* [Midtrans Docs](https://docs.midtrans.com)\n* [Midtrans Dashboard ](https://dashboard.midtrans.com/)\n* [SNAP documentation](http://snap-docs.midtrans.com)\n* [Core API documentation](http://api-docs.midtrans.com)\n* Can't find answer you looking for? email to [support@midtrans.com](mailto:support@midtrans.com)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmidtrans%2Fmidtrans-go","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmidtrans%2Fmidtrans-go","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmidtrans%2Fmidtrans-go/lists"}