search
HomeBackend DevelopmentGolangHow to use Golang to implement WeChat payment for web applications

How to use Golang to implement WeChat payment for web applications

Jun 24, 2023 am 09:12 AM
golangWeChat Payweb application

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

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

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")
}

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"
    }
}
  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)
}

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

    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)
    ...
}

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()
}

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>

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
    }
    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
}

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

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!

Statement
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
Choosing Between Golang and Python: The Right Fit for Your ProjectChoosing Between Golang and Python: The Right Fit for Your ProjectApr 19, 2025 am 12:21 AM

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang: Concurrency and Performance in ActionGolang: Concurrency and Performance in ActionApr 19, 2025 am 12:20 AM

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang vs. Python: Which Language Should You Learn?Golang vs. Python: Which Language Should You Learn?Apr 19, 2025 am 12:20 AM

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang vs. Python: Performance and ScalabilityGolang vs. Python: Performance and ScalabilityApr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang vs. Other Languages: A ComparisonGolang vs. Other Languages: A ComparisonApr 19, 2025 am 12:11 AM

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

Golang and Python: Understanding the DifferencesGolang and Python: Understanding the DifferencesApr 18, 2025 am 12:21 AM

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang vs. C  : Assessing the Speed DifferenceGolang vs. C : Assessing the Speed DifferenceApr 18, 2025 am 12:20 AM

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang: A Key Language for Cloud Computing and DevOpsGolang: A Key Language for Cloud Computing and DevOpsApr 18, 2025 am 12:18 AM

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.