The auth interaction flow between a WeChat Mini Program and the backend

The core flow of WeChat Mini Program login: the mini program gets a temporary credential code → the backend exchanges the code for an openid → the backend issues its own JWT to the mini program. Below is the overall flow diagram.

sequenceDiagram
    participant MP as WeChat Mini Program
    participant WX as WeChat server
    participant GW as gateway
    participant Auth as auth module
    participant User as user-service
    participant DB as lia_user database

    MP->>WX: wx.login() to get code
    WX-->>MP: returns temporary code
    MP->>GW: POST /auth/wx-login {code}
    GW->>Auth: forward the request
    Auth->>WX: code2session(code)
    WX-->>Auth: returns openid + session_key
    Auth->>User: OpenFeign to query/create the user
    User->>DB: query by openid
    DB-->>User: user record (or empty)
    User-->>Auth: return userId
    Auth->>Auth: generate JWT
    Auth-->>MP: return token + user info
    MP->>MP: store into Storage

Breaking down the key points

1. The mini program gets the code (frontend)

wx.login({
  success(res) {
    // res.code is a one-time temporary credential, expires in 5 minutes
    wx.request({
      url: 'https://your-domain/auth/wx-login',
      method: 'POST',
      data: { code: res.code }
    })
  }
})

2. The backend exchanges the code for an openid

Call the WeChat endpoint https://api.weixin.qq.com/sns/jscode2session with four parameters:

Parameter Value
appid Mini program AppID
secret Mini program AppSecret (put it in Nacos, don’t hardcode)
js_code The code passed from the frontend
grant_type Fixed value authorization_code

WeChat returns the openid (the user’s unique identifier) and session_key (used for decryption; you can skip it for the login scenario for now).

3. openid is an identity, not a password

openid is only the “who is this user” identifier. You can’t trust the frontend to send the openid directly; you must exchange the code with WeChat every time, which is what prevents forgery.

4. Where to put it in your architecture

The auth module is the best fit, sitting alongside your existing JWT login logic:

  • Add a WxLoginController + WxLoginService in the auth module
  • Use RestClient/WebClient to call the WeChat endpoint (you’re already on Spring Boot 3)
  • After getting the openid, call user-service via OpenFeign to “register if not found” (upsert)
  • Add an openid column (unique index) to the lia_user table
  • Reuse your existing JWT utility class to issue the token

5. Database change

ALTER TABLE tb_user ADD COLUMN openid VARCHAR(64) UNIQUE;

The whole flow shares the same JWT system as your current username-password login; only the “verify identity” step changes from “checking the password” to “exchanging the code for an openid.”

Want me to write the complete code for the auth module that calls the WeChat endpoint and issues the JWT?