Git Product home page Git Product logo

go-midtrans's Introduction


⚠️⚠️ IMPORTANT ANNOUNCEMENT ⚠️⚠️

Please use the updated and revamped: Midtrans Go. For better and more intuitive usage.

Click Here to Learn More

This library was created in the early days, then we realize some of the designs and patterns used in this library is not the best and easiest to maintain. We learn from the mistakes, and decide it will be better to revamp as brand new Midtrans Go library. This decision is to avoid forcing breaking changes to this library, allow old users to migrate as they see fit, and allows better flexibility on the revamped design. Thank you for your support, contributions, and understanding. 🙂

This repo still be here for archive and backward-compatibility purpose for those who still use it. But it's always recommended to use the newer version Midtrans Go.

🔈 END OF ANNOUNCEMENT 🔈


Midtrans Library for Go(lang)

Go Report Card Apache 2.0 license Build Status

Midtrans ❤️ 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. Now, Midtrans is available to be used in Go, too.

Usage blueprint

  1. There is a type named Client (midtrans.Client) that should be instantiated through NewClient which hold any possible setting to the library.
  2. There is a gateway classes which you will be using depending on whether you used Core, SNAP, SNAP-Redirect. The gateway type need a Client instance.
  3. Any activity (charge, approve, etc) is done in the gateway level.

Example

We have attached usage examples in this repository in folder example/simplepay. Please proceed there for more detail on how to run the example.

Core Gateway

    midclient := midtrans.NewClient()
    midclient.ServerKey = "YOUR-VT-SERVER-KEY"
    midclient.ClientKey = "YOUR-VT-CLIENT-KEY"
    midclient.APIEnvType = midtrans.Sandbox

    coreGateway := midtrans.CoreGateway{
        Client: midclient,
    }

    chargeReq := &midtrans.ChargeReq{
        PaymentType: midtrans.SourceCreditCard,
        TransactionDetails: midtrans.TransactionDetails{
            OrderID: "12345",
            GrossAmt: 200000,
        },
        CreditCard: &midtrans.CreditCardDetail{
            TokenID: "YOUR-CC-TOKEN",
        },
        Items: &[]midtrans.ItemDetail{
            midtrans.ItemDetail{
                ID: "ITEM1",
                Price: 200000,
                Qty: 1,
                Name: "Someitem",
            },
        },
    }

    resp, _ := coreGateway.Charge(chargeReq)

How Core API does charge with map type

please refer to file main.go in folder example/simplepay

func ChargeWithMap(w http.ResponseWriter, r *http.Request) {
	var reqPayload = &midtrans.ChargeReqWithMap{}
	err := json.NewDecoder(r.Body).Decode(reqPayload)
	if err != nil {
		// do something
		return
	}
	
	chargeResp, _ := coreGateway.ChargeWithMap(reqPayload)
	result, err := json.Marshal(chargeResp)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(result)
}

Snap Gateway

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

Quick transaction with minimum Snap parameters:

var snapGateway midtrans.SnapGateway
snapGateway = midtrans.SnapGateway{
  Client: midclient,
}

snapResp, err := snapGateway.GetTokenQuick(generateOrderId(), 200000)
var snapToken string
if err != nil {
  snapToken = snapResp.Token
}

On the client side:

var token = $("#snap-token").val();
snap.pay(token, {
    onSuccess: function(res) { alert("Payment accepted!"); },
    onPending: function(res) { alert("Payment pending", res); },
    onError: function(res) { alert("Error", res); }
});

You may want to override those onSuccess, onPending and onError functions to reflect the behaviour that you wished when the charging result in their respective state.

Alternativelly, more complete Snap parameter:

    midclient := midtrans.NewClient()
    midclient.ServerKey = "YOUR-VT-SERVER-KEY"
    midclient.ClientKey = "YOUR-VT-CLIENT-KEY"
    midclient.APIEnvType = midtrans.Sandbox

    var snapGateway midtrans.SnapGateway
    snapGateway = midtrans.SnapGateway{
        Client: midclient,
    }

    custAddress := &midtrans.CustAddress{
        FName: "John",
        LName: "Doe",
        Phone: "081234567890",
        Address: "Baker Street 97th",
        City: "Jakarta",
        Postcode: "16000",
        CountryCode: "IDN",
    }

    snapReq := &midtrans.SnapReq{
        TransactionDetails: midtrans.TransactionDetails{
            OrderID: "order-id-go-"+timestamp,
            GrossAmt: 200000,
        },
        CustomerDetail: &midtrans.CustDetail{
            FName: "John",
            LName: "Doe",
            Email: "[email protected]",
            Phone: "081234567890",
            BillAddr: custAddress,
            ShipAddr: custAddress,
        },
        Items: &[]midtrans.ItemDetail{
            midtrans.ItemDetail{
                ID: "ITEM1",
                Price: 200000,
                Qty: 1,
                Name: "Someitem",
            },
        },
    }

    log.Println("GetToken:")
    snapTokenResp, err := snapGateway.GetToken(snapReq)

Handle HTTP Notification

Create separated web endpoint (notification url) to receive HTTP POST notification callback/webhook. HTTP notification will be sent whenever transaction status is changed. Example also available in main.go in folder example/simplepay

func notification(w http.ResponseWriter, r *http.Request) {
	var reqPayload = &midtrans.ChargeReqWithMap{}
	err := json.NewDecoder(r.Body).Decode(reqPayload)
	if err != nil {
		// do something
		return
	}

	encode, _ := json.Marshal(reqPayload)
	resArray := make(map[string]string)
	err = json.Unmarshal(encode, &resArray)

	chargeResp, _ := coreGateway.StatusWithMap(resArray["order_id"])
	result, err := json.Marshal(chargeResp)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(result)
}

Iris Gateway

Iris is Midtrans cash management solution that allows you to disburse payments to any bank accounts in Indonesia securely and easily. Iris connects to the banks’ hosts to enable seamless transfer using integrated APIs.

Note: ServerKey used for irisGateway's Client is API Key found in Iris Dashboard. The API Key is different with Midtrans' payment gateway account's key.

var irisGateway midtrans.IrisGateway
irisGateway = midtrans.IrisGateway{
  Client: midclient,
}

res, err := irisGateway.GetListBeneficiaryBank()
if err != nil {
    fmt.Println("err ", err)
    return
}
fmt.Printf("result %v \n ", res.BeneficiaryBanks)

License

See LICENSE.

go-midtrans's People

Contributors

adamnoto avatar apinprastya avatar ardityawahyu avatar ariestiyansyah avatar budiariyanto avatar dhi9 avatar fajrifernanda avatar gobliggg avatar haritsfahreza avatar harymindiar avatar hitzam avatar ivandzf avatar mychaelgo avatar ngurajeka avatar omarxp avatar perfmind avatar prakashdivyy avatar rizdaprasetya avatar shcode 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

go-midtrans's Issues

Invalid SnapRequest sent by mobile sdk

Hi,

I'm using this module with version (v0.0.0-20190513104831-ff7f567d2249) in my golang backend. However, when we receive the snap request from our android app, we found out that credit_card.authentication sent by the android sdk is not a boolean, but string. Meanwhile in go-midtrans module, it is defined as boolean in here.

We are using struct SnapReq to decode the json sent by the android and to do some validation against the request sent by android app. However we got error due to the issue i explained above.

decoder := json.NewDecoder(r.Body)
var snapRequest go-midtrans.SnapReq
err := decoder.Decode(&snapRequest)
if err != nil {
.....
}

Is this expected?

LICENSE unavailable

Hi @rizdaprasetya and Midtrans team,

As we know, this repository has no LICENSE yet. It would be great if you define the LICENSE of this repository. Maybe Apache 2.0 or MIT would be great options 😄

Thanks,
Reza

wrong type on BCATransferDetail struct

Hi There,

i just saw the codes on https://github.com/veritrans/go-midtrans/blob/master/request.go#L77. seems there was incorrect type

type BCABankTransferDetail struct {
    Bank Bank `json:"bank"`
    VaNumber string `json:"va_number"`
    FreeText struct {
        Inquiry []BCABankTransferDetail `json:"inquiry"`
        Payment []BCABankTransferDetail `json:"payment"`
    } `json:"free_text"`
}

it should be using BCABankTransferLangDetail instead BCABankTransferDetail

type BCABankTransferDetail struct {
    Bank Bank `json:"bank"`
    VaNumber string `json:"va_number"`
    FreeText struct {
        Inquiry []BCABankTransferLangDetail `json:"inquiry"`
        Payment []BCABankTransferLangDetail `json:"payment"`
    } `json:"free_text"`
}

if i referred from doc the payload json should be like this

"bank_transfer":{
     "bank": "bca",
     "free_text": {
          "inquiry": [
                {
                    "id": "Free Text ID Free Text ID Free Text ID",
                    "en": "Free Text EN Free Text EN Free Text EN"
                }
          ],
          "payment": [
                {
                    "id": "Free Text ID Free Text ID Free Text ID",
                    "en": "Free Text EN Free Text EN Free Text EN"
                }
          ]
    }

also this one

type BCABankTransferLangDetail struct {
    LangID string `json:"id,omitempty"`
    LangEN string `json:"id,omitempty"`
}

the second annotation should be LangEN string json:"en,omitempty"

go-midtrans doesn't work while running inside docker container

I found something weird while working with this go package, I tried to run it from Docker Container and I got error One or more parameters in the payload is invalid. but when I try it in localhost from my machine, it's working like a charm

Error Log from Docker Container

2021/01/02 20:41:46 Request  POST :  api.sandbox.midtrans.com /v2/charge
2021/01/02 20:41:46 One or more parameters in the payload is invalid.

Success Log from my local machine

2021/01/03 03:28:06 Request  POST :  api.sandbox.midtrans.com /v2/charge
2021/01/03 03:28:06 OK, Mandiri Bill transaction is successful

If there is a special configuration for run midtrans inside Docker
please add it into documentation thanks

No documentation about set custom transaction expired

Hello I am using midtrans for my business, and I have struggle finding how to define custom trx expire in ChargeReq.

I have try this one by reading the code of go-midtrans but this is not work, please help me by explain how to define custom
transaction expire in ChargeReq

req := &midtrans.ChargeReq{
		PaymentType: midtrans.SourceEchannel,
		MandiriBillBankTransferDetail: &midtrans.MandiriBillBankTransferDetail{
			BillInfo1: "complete payment",
			BillInfo2: "dept",
		},
                // how to set valid configuration for custom trx expire
		CustomExpiry: &midtrans.CustomExpiry{
			OrderTime:      trxTime.Format("2006-01-02 15:04:05 +0700"),
			ExpiryDuration: 1,
			Unit:           "HOUR",
		},
		TransactionDetails: midtrans.TransactionDetails{
			OrderID:  trxID,
			GrossAmt: grossAmt,
		},
		CustomerDetail: &midtrans.CustDetail{
			Phone: custPhone,
			FName: custName,
		},
		Items: &[]midtrans.ItemDetail{
			{
				ID:    itemID,
				Price: grossAmt,
				Qty:   1,
				Name:  itemName,
			},
		},
	}

Refund support?

The core gateway doesn't include API for refund and direct refund

custom callback for snap doesnt work

Hello

Documentation said we could use custom callback for our payment
custom finish url

when i tried to custom my payload like
Callbacks: &midtrans.Callbacks{ Finish: "https://example.org/?foo=123456", },

instead of giving my custom finish url query, it still redirect with query
?status_code=200&transaction_status=settlement&merchant_id=XXXXXX&order_id=XXXXXXX

I used Development env for testing

Installment On Snap

Hi midtrans team,

I found that Installement Term on CreditCardDetail has data type int8, but on the API Documentation it should be json object:

image

And what should I put on InstallmentTerm value?
image

Any suggestion?

Thanks!

Snap SDK did not return "status_code"

Hi @rizdaprasetya and Midtrans team,

As we know, SnapResponse struct has field status_code to keep HTTP Status Code from Midtrans. But I found that field is always empty and found that it does not use or set by any function right now. I need that field so I can check the error that happen on Midtrans API.

I will submit a PR regarding to this issue 😄

Thanks!

Mandiri eCash is not found on charge request struct

When I test use mandiri ecash payment method (at https://api-docs.midtrans.com/#mandiri-e-cash)

{
  "payment_type": "mandiri_ecash",
  "mandiri_ecash": {
    "description": "Transaction Description"
  },
  ...
}

There is json key "mandiri_ecash" but it's not exist at https://github.com/veritrans/go-midtrans/blob/master/request.go#L142

May should be like this

type ChargeReq struct {
    ...
    MandiriClickPay  *MandiriClickPayDetail `json:"mandiri_clickpay,omitempty"`
    MandiriEcash     *MandiriEcashDetail    `json:"mandiri_ecash,omitempty"`
    CIMBClicks       *CIMBClicksDetail      `json:"cimb_clicks,omitempty"`
    ...
}

Missing channel_status_code and channel_status_message field in CoreGateway Response

Doc: https://api-docs.midtrans.com/#get-transaction-status
Request:

GET /v2/{order_id}/status

Response:

{
  "status_code" : "200",
  "status_message" : "Success, transaction found",
  "transaction_id" : "249fc620-6017-4540-af7c-5a1c25788f46",
  "masked_card" : "481111-1114",
  "order_id" : "example-1424936368",
  "payment_type" : "credit_card",
  "transaction_time" : "2015-02-26 14:39:33",
  "transaction_status" : "partial_refund",
  "fraud_status" : "accept",
  "approval_code" : "1424936374393",
  "signature_key" : "2802a264cb978fbc59f631c68d120cbda8dc853f5dfdc52301c615cf4f14e7a0b09aa...",
  "bank" : "bni",
  "gross_amount" : "30000.00",
  "channel_response_code": "00",
  "channel_response_message": "Approved",
  "card_type": "credit",
  "refund_amount": "12000.00",
  "refunds": [
    {
      "refund_chargeback_id": 1,
      "refund_amount": "5000.00",
      "created_at": "2015-02-27 00:14:20",
      "reason": "some reason",
      "refund_key": "reference1"
    },
    {
      "refund_chargeback_id": 2,
      "refund_amount": "7000.00",
      "created_at": "2015-02-28 01:23:15",
      "reason": "",
      "refund_key": "reference2"
    },
  ]
}

Based on this documentation when we call Get Status API, it might contains the channel_status_code and channel_status_message field, but it was missing from Response struct in response.go

Invalid installment struct

Hi,

We will use installment struct, and i found the installment struct has missing code.

type InstallmentTermsDetail {
	Bni     []int8 `json:"bni,omitempty"`
	Mandiri []int8 `json:"mandiri,omitempty"`
	Cimb    []int8 `json:"cimb,omitempty"`
	Mega    []int8 `json:"mega,omitempty"`
	Bca     []int8 `json:"bca,omitempty"`
	Bri     []int8 `json:"bri,omitempty"`
	Maybank []int8 `json:"maybank,omitempty"`
	Offline []int8 `json:"offline,omitempty"`
}

there is missing type struct

and i found a type of field Terms has an array of object.
refer to this documentation midtrans-snap-documentation that field is using an object.

please take a look on #60

Wrong status_code on Response struct for CoreGateway

Hi midtrans team,
Based on this fix #19 , it fill the status_code both in SnapResponse's struct and Response's struct with http statuscode.

But in CoreGateway, when getting status of an order https://api.sandbox.midtrans.com/v2/some-order-id/status, it gives the status_code result in response body based on transaction's status like image below.
Screen Shot 2019-11-26 at 21 16 41

Because of fix in #19 it will replace the status_code=407 (which explain the transaction's status) with status_code=200 from http status_code in Response of CoreGateway.

so the status_code in Response struct must not replaced with the http status code, because it is refer from transaction's status.

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.