Home > Backend Development > Golang > How to use Golang to implement WeChat payment for web applications

How to use Golang to implement WeChat payment for web applications

PHPz
Release: 2023-06-24 09:12:05
Original
2696 people have browsed it

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.

Requirements

In this tutorial, we will build a simple e-commerce website. The website needs to implement the following functions:

  1. Users log in to the website through WeChat.
  2. Users browse items and add items to the shopping cart.
  3. Users can use WeChat payment to purchase goods.

Preparation

Before you start, please make sure you have the following requirements:

  • Have registered a WeChat payment account and have appid, mch_id, key and other parameters.
  • Golang and Gin frameworks installed.

Install go-wechat SDK

Before proceeding, please install the WeChat SDK from go-wechat’s Github repository.

go get github.com/silenceper/wechat/v2
Copy after login

Configure environment variables

Obtain the following parameters from the WeChat payment account and add them to the system environment variables:

  • APP_ID : WeChat APP_ID
  • MCH_ID: Merchant ID
  • API_KEY: Merchant API key
export APP_ID=your_appid
export MCH_ID=your_mchid
export API_KEY=your_api_key
Copy after login

Build application

Initializing Gin

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")
}
Copy after login

Add WeChat login to the application

On the previous page, we set up the basic Gin application. We will now add WeChat login functionality.

  1. Add configuration file

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"
    }
}
Copy after login
  1. Initializing WeChat

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)
}
Copy after login

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.

  1. Handling WeChat Authorization

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, "/")
}
Copy after login

    Integrate WeChat login
We should integrate WeChat login into our application. The process is relatively simple. Just add the handler to the Gin router.

func main() {
    ...
    router.GET("/wechat/login", weChatLoginHandler)
    router.GET("/wechat/callback", callbackHandler)
    ...
}
Copy after login

Implementing the shopping cart

We 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()
}
Copy after login

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 .

Display the shopping cart status at the bottom of the page:

<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>
Copy after login

WeChat payment

In 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.

    Define the order struct
  1. type Order struct {
        OrderNumber string
        Amount      float64
    }
    Copy after login
    Generate the order and send the order to WeChat
In this step, we will generate the order And create an order number through WeChat payment. Read go-wechat's payments documentation to learn more.

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
}
Copy after login

    Processing WeChat payment notification
After WeChat notifies us that we have received the user's payment, in the callback, we will store the order status for later query.

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.
            }
        }
    }()
}
Copy after login
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.

    TradeStateSuccess: The user's payment was successful.
  • TradeStateClosed: The order has been closed.
  • TradeStateRefund: The transaction has been refunded.
Summary

In this article, we learned how to use Golang and Gin framework to build an e-commerce website, and used go-wechat SDK to quickly implement WeChat login and Payment function. We learned how to handle user authentication and authorization through WeChatClient and how to store WeChat user data in the user's session. We also learned how to define a simple shopping cart and order and integrate with WeChat Pay using go-wechat SDK.

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template