Home >Backend Development >Golang >How to use Golang to implement WeChat payment for web applications
WeChat Pay is a very common online payment method, and many websites/applications need to integrate this function. This article will introduce how to use Golang to implement WeChat payment function. In this article, we will use the Gin framework to build a simple web application and use the go-wechat WeChat SDK to quickly implement WeChat payment.
In this tutorial, we will build a simple e-commerce website. The website needs to implement the following functions:
Before you start, please make sure you have the following requirements:
appid
, mch_id
, key
and other parameters. Before proceeding, please install the WeChat SDK from go-wechat’s Github repository.
go get github.com/silenceper/wechat/v2
Obtain the following parameters from the WeChat payment account and add them to the system environment variables:
APP_ID
: WeChat APP_IDMCH_ID
: Merchant IDAPI_KEY
: Merchant API keyexport APP_ID=your_appid export MCH_ID=your_mchid export API_KEY=your_api_key
In the file main.go
, we will use the gin package to initialize the application.
package main import ( "net/http" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/", func(c *gin.Context) { c.String(http.StatusOK, "Hello World!") }) router.Run(":8080") }
On the previous page, we set up the basic Gin application. We will now add WeChat login functionality.
You can choose to define configuration via JSON, YAML or TOML format. Here, we will create a config.json
file to define the configuration.
{ "wechat": { "appid": "your_appid", "secret": "your_app_secret" } }
The next step is to initialize WeChatClient
and use the oauth2
request code to get the access token.
import ( "encoding/json" "io/ioutil" "net/http" "os" "github.com/silenceper/wechat/v2" ) func loadConfig() map[string]string { file, err := os.Open("config.json") if err != nil { panic("Failed to load config file.") } defer file.Close() data, err := ioutil.ReadAll(file) if err != nil { panic("Failed to read config file.") } var config map[string]map[string]string err = json.Unmarshal(data, &config) if err != nil { panic("Failed to parse config file.") } return config["wechat"] } func initializeWeChat() *wechat.WeChat { config := loadConfig() client := wechat.NewWechat(&wechat.Config{ AppID: config["appid"], AppSecret: config["secret"], Token: "", EncodingAESKey: "", }) return client } func weChatLoginHandler(c *gin.Context) { client := initializeWeChat() redirectURL := "<YOUR_REDIRECT_URL>" url := client.Oauth2.GetRedirectURL(redirectURL, "snsapi_userinfo", "") c.Redirect(http.StatusTemporaryRedirect, url) }
Essentially, we define a WeChatClient that contains the authentication for the application. We also define a Gin handler that sets the redirect URL and gets the access token using the oauth2
request in WeChatClient
.
In the redirect URL, /wechat/callback# will be called when the user authorizes our application to run under their account. ## Handler. This handler stores the user's WeChat ID, nickname, and other public data in the user's session.
func callbackHandler(c *gin.Context) { code := c.Request.URL.Query().Get("code") client := initializeWeChat() accessToken, err := client.Oauth2.GetUserAccessToken(code) if err != nil { panic("Failed to get access token from WeChat.") } userInfo, err := client.Oauth2.GetUserInfo(accessToken.AccessToken, accessToken.Openid) if err != nil { panic("Failed to get user info from WeChat.") } session := sessions.Default(c) session.Set("wechat_openid", userInfo.Openid) session.Set("wechat_nickname", userInfo.Nickname) session.Save() c.Redirect(http.StatusTemporaryRedirect, "/") }
func main() { ... router.GET("/wechat/login", weChatLoginHandler) router.GET("/wechat/callback", callbackHandler) ... }Implementing the shopping cartWe will add a basic shopping cart state to the application. Just add the shopping cart information in the user session.
type CartItem struct { ProductID int Quantity int } func (c *CartItem) Subtotal() float64 { // TODO: Implement. } type Cart struct { Contents []*CartItem } func (c *Cart) Add(productID, quantity int) { item := &CartItem{ ProductID: productID, Quantity: quantity, } found := false for _, existingItem := range c.Contents { if existingItem.ProductID == productID { existingItem.Quantity += quantity found = true break } } if !found { c.Contents = append(c.Contents, item) } } func (c *Cart) Remove(productID int) { for i, item := range c.Contents { if item.ProductID == productID { c.Contents = append(c.Contents[:i], c.Contents[i+1:]...) break } } } func (c *Cart) Total() float64 { total := 0.0 for _, item := range c.Contents { total += item.Subtotal() } return total } func cartFromSession(session sessions.Session) *Cart { value := session.Get("cart") if value == nil { return &Cart{} } cartBytes := []byte(value.(string)) var cart Cart json.Unmarshal(cartBytes, &cart) return &cart } func syncCartToSession(session sessions.Session, cart *Cart) { cartBytes, err := json.Marshal(cart) if err != nil { panic("Failed to sync cart with session data store.") } session.Set("cart", string(cartBytes)) session.Save() }As shown above, we implemented a function containing
Add(productID, quantity int),
Remove(productID int),
Total() float64Several methods of cart struct. We store and load cart data from the session (
cartFromSession() and
syncCartToSession()) and calculate the subtotal of the item via the
CartItem.Subtotal() method .
<footer> <div class="container"> <div class="row"> <div class="col-sm-4"> <a href="/">Back to home</a> </div> <div class="col-sm-4"> <p id="cart-count"></p> </div> <div class="col-sm-4"> <p id="cart-total"></p> </div> </div> </div> </footer> <script> document.getElementById("cart-count").innerText = "{{.CartItemCount}} items in cart"; document.getElementById("cart-total").innerText = "Total: ${{.CartTotal}}"; </script>WeChat paymentIn order to implement WeChat payment, we need to define an order struct, generate the order and send it to WeChat payment , processing payment notifications. Below is a simple implementation.
type Order struct { OrderNumber string Amount float64 }
func generateOutTradeNo() string { // TODO: Implement. } func createOrder(cart *Cart) *Order { order := &Order{ OrderNumber: generateOutTradeNo(), Amount: cart.Total(), } client := initializeWeChat() payment := &wechat.Payment{ AppID: APP_ID, MchID: MCH_ID, NotifyURL: "<YOUR_NOTIFY_URL>", TradeType: "JSAPI", Body: "购物车结算", OutTradeNo: order.OrderNumber, TotalFee: int(order.Amount * 100), SpbillCreateIP: "127.0.0.1", OpenID: "<USER_WECHAT_OPENID>", Key: API_KEY, } result, err := client.Pay.SubmitPayment(payment) if err != nil { panic("Failed to submit payment.") } // Save order state and return it. return order }
func setupCheckOrderStatus() { go func() { for { // Wait 10 seconds before checking (or less if you want to check more frequently). time.Sleep(10 * time.Second) client := initializeWeChat() // TODO: Retrieve orders that need to be checked. for _, order := range ordersToCheck { queryOrderResult, err := client.Pay.QueryOrder(&wechat.QueryOrderParams{ OutTradeNo: order.OrderNumber, }) if err != nil { panic("Failed to query order.") } switch queryOrderResult.TradeState { case wechat.TradeStateSuccess: // Handle order payment in your app. order.Paid = true // TODO: Update order state in database. case wechat.TradeStateClosed: // Handle order payment in your app. order.Paid = false // TODO: Update order state in database. case wechat.TradeStateRefund: // Handle order payment in your app. order.Paid = false // TODO: Update order state in database. default: break } // TODO: Remove checked order from cache. } } }() }We need to call the query function to check the transaction where WeChat forces the order status to be changed. WeChat SDK will return one of the following statuses.
The above is the detailed content of How to use Golang to implement WeChat payment for web applications. For more information, please follow other related articles on the PHP Chinese website!