Location>code7788 >text

Go Language Docking WeChat Payment and Refund Full Process Guide

Popularity:105 ℃/2024-10-08 17:35:05

Catalog:
I. Preparatory work
Second, initialize the WeChat payment client
III. Realization of payment functions
1. Chronology of payments
2. Realization of payments in different scenarios
WAP Payment
PC payment
Android Payment
3. Parsing payment callbacks
IV. Implementation of the refund function
Refund Timing Chart
Initiate refunds
Parsing Refund Callbacks
V. Summary

In today's growing Internet technology, online payment has become an indispensable part. As a concise and efficient programming language, Go (also known as Golang) is becoming more and more popular among developers in the field of back-end development due to its powerful concurrent processing capabilities and efficient performance. In this article, we will introduce in detail how to use Go to dock WeChat Pay, and realize the payment and refund functions to help developers quickly get started.

I. Preparatory work

Here are a few things you need to have in place before you start writing code:

  1. Register as a WeChat Pay Merchant: If you don't have a WeChat Pay merchant account yet, you'll need to head over toWeChat Pay Merchant PlatformComplete the registration.
  2. Getting the necessary configuration information
    • Merchant Number (MchId)
    • AppID (Appid)
    • API v3 key (ApiV3Key)
    • Merchant Certificate Serial Number (MchSerialNo)
    • Private key (PrivateKey)
    • Payment Notification Address (NotifyUrl)
    • Refund Notice Address (RefundUrl)
  3. Installation of third-party libraries: In order to simplify the call of the microsoft payment interface, it is recommended to use the/go-pay/gopayThis library. It can be accessed via thego getcommand to install:
    go get /go-pay/gopay
    

Second, initialize the WeChat payment client

First, we need to create aWechatPayServicestructure to encapsulate WeChat Payment related operations. The structure contains the context, configuration information and the WeChat Pay client instance.

type WechatPayService struct {
	ctx       
	config    WechatPayConfig
	wechatPay *wechat.ClientV3
}

type WechatPayConfig struct {
	Appid       string
	Appid1      string
	MchId       string
	ApiV3Key    string
	MchSerialNo string
	PrivateKey  string
	NotifyUrl   string
	RefundUrl   string
}

Next, we passed theNewWechatPayServicefunction to initialize theWechatPayServiceExample.

func NewWechatPayService(ctx , config WechatPayConfig) *WechatPayService {
	client, err := wechat.NewClientV3(, , config.ApiV3Key, )
	if err != nil {
		(err)
		return nil
	}
	err = ()
	if err != nil {
		(err)
		return nil
	}
	 = 

	return &WechatPayService{
		ctx:       ctx,
		wechatPay: client,
		config:    config,
	}
}

In this snippet, we pass theNewClientV3method initializes the WeChat Pay client, passing in key parameters such as merchant number, certificate serial number, API v3 key and private key. To secure the payment, automatic signature verification is enabled.

III. Realization of payment functions

1. Chronology of payments

2. Realization of payments in different scenarios

WAP Payment

func (w *WechatPayService) WapPay(charge *Charge) (result string, err error) {
	amount := ().DivRound((1), 2).IntPart()
	expire := ().Add(10 * ).Format(time.RFC3339)
	bm := make()
	("appid", ).
		Set("mchid", ).
		Set("description", ).
		Set("out_trade_no", ).
		Set("time_expire", expire).
		Set("notify_url", ).
		SetBodyMap("amount", func(bm ) {
			("total", amount).
				Set("currency", "CNY")
		}).
		SetBodyMap("scene_info", func(bm ) {
			("payer_client_ip", "127.0.0.1").
				SetBodyMap("h5_info", func(bm ) {
					("type", "Wap")
				})
		})

	rsp, err := .V3TransactionH5(, bm)
	if err != nil {
		return
	}
	result = .H5Url
	return
}

PC payment

func (w *WechatPayService) PcPay(charge *Charge) (result string, err error) {
	amount := ().DivRound((1), 2).IntPart()
	expire := ().Add(10 * ).Format(time.RFC3339)
	bm := make()
	("appid", ).
		Set("mchid", ).
		Set("description", ).
		Set("out_trade_no", ).
		Set("time_expire", expire).
		Set("notify_url", ).
		SetBodyMap("amount", func(bm ) {
			("total", amount).
				Set("currency", "CNY")
		})

	rsp, err := .V3TransactionNative(, bm)
	if err != nil {
		return
	}
	result = 
	return
}

Android Payment

func (w *WechatPayService) AndroidPay(charge *Charge) (result string, err error) {
	amount := ().DivRound((1), 2).IntPart()
	expire := ().Add(10 * ).Format(time.RFC3339)
	bm := make()
	("appid", .Appid1).
		Set("mchid", ).
		Set("description", ).
		Set("out_trade_no", ).
		Set("time_expire", expire).
		Set("notify_url", ).
		SetBodyMap("amount", func(bm ) {
			("total", amount).
				Set("currency", "CNY")
		})

	rsp, err := .V3TransactionApp(, bm) 
	if err != nil {
		return
	}

	jsapiInfo, err := (.Appid1, )
	str, _ := (jsapiInfo)
	result = string(str)
	return
}
  • APP payment is very similar to JSAPI payment. The main difference lies in the interaction between the app and the merchant service backend. the app will get the signature information from the merchant service backend, and according to the signature information, the app will directly call WeChat payment service to place the order.

3. Parsing payment callbacks

When the user completes the payment, WeChat sends a callback notification to our server that the payment was successful. We need to parse this notification and verify its legitimacy.

func (w *WechatPayService) GetNotifyResult(r *) (res *wechat.V3DecryptResult, err error) {
	notifyReq, err := wechat.V3ParseNotify(r) // Parsing callback parameters
	if err != nil {
		(err)
		return
	}
	if notifyReq == nil {
		return
	}
	return (.ApiV3Key) // Decrypting callback contents
}

pass (a bill or inspection etc)V3ParseNotifymethod that parses the payment notification and decrypts the payment result using the API v3 key.

IV. Implementation of the refund function

Refund Timing Chart

Initiate refunds

In addition to payments, refunds are also a common feature in WeChat Pay. Next, let's see how to implement the refund function using Go language.

When a refund is needed for a paid order, you can call theRefundMethods.

func (w *WechatPayService) Refund(charge *RefundCharge) (err error) {
	amount := ().DivRound((1), 2).IntPart()
	bm := make()
	("out_trade_no", ).
		Set("out_refund_no", ).
		Set("reason", ).
		Set("notify_url", ).
		SetBodyMap("amount", func(bm ) {
			("total", amount).
				Set("refund", amount).
				Set("currency", "CNY")
		})

	rsp, err := .V3Refund(, bm) // Initiation of refund requests
	if err != nil {
		return
	}

	if rsp == nil || == nil || != "" {
        // Processing Refund Errors
		err = ()
		return
	}
	return
}

Parsing Refund Callbacks

func (w *WechatPayService) GetRefundNotifyResult(r *) (res *wechat.V3DecryptRefundResult, err error) {
	notifyReq, err := wechat.V3ParseNotify(r)
	if err != nil {
		return
	}
	return (.ApiV3Key)
}

V. Summary

Through the introduction of this article, I believe you have mastered how to use the Go language to dock WeChat Pay and implement the payment and refund functions. These features can not only improve the user experience, but also help you in the actual project more efficiently deal with payment-related business logic. I hope this article will be helpful to you!

If you have any questions or suggestions, please feel free to share them in the comment section. Looking forward to your valuable opinions!