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.
Requirements
In this tutorial, we will build a simple e-commerce website. The website needs to implement the following functions:
- Users log in to the website through WeChat.
- Users browse items and add items to the shopping cart.
- 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.
- 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" } }
- 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
.
- 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
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.
- Define the order struct
type Order struct { OrderNumber string Amount float64 }
- Generate the order and send the order to WeChat
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
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.
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!

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

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

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.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.