A small, standalone helper for the WeChat web OAuth (snsapi_base) flow used
to obtain a user's OpenID. GoFiber only.
go.gh.ink/wechat-oauth
go get go.gh.ink/wechat-oauthThe WeChat web OAuth flow has two steps; this library exposes one endpoint for each:
- Generate an authorise link — your front-end redirects the user to it;
WeChat redirects back to your
redirect_uriwith acode. - Exchange the code for an OpenID — your front-end posts the
codeback and receives theopenID.
Mount the routes on a GoFiber router with Register:
import (
"github.com/gofiber/fiber/v3"
wechatoauth "go.gh.ink/wechat-oauth"
)
app := fiber.New()
wechatoauth.Register(app, wechatoauth.Config{
AppID: "wx-app-id",
AppSecret: "wx-app-secret",
AllowOrigins: []string{"https://app.example.com"}, // redirect_uri whitelist
})Register mounts a /wechat group on the given router, so relative to it:
| Method & path | Purpose |
|---|---|
POST /wechat/authorize-link |
Build a WeChat authorize link. |
POST /wechat/open-id-callback |
Exchange a code for an openID. |
Request:
{ "redirect_uri": "https://app.example.com/cb", "state": "csrf-token" }redirect_uri must start with one of Config.AllowOrigins, otherwise the
request is rejected with ErrRedirectURIMismatch.
Response:
{ "code": 200, "data": { "url": "https://open.weixin.qq.com/connect/oauth2/authorize?..." }, "msg": "success" }Request (the code WeChat appended to your redirect_uri):
{ "code": "wx-code", "state": "csrf-token" }Response:
{ "code": 200, "data": { "openID": "o-xxxx" }, "msg": "success" }When WeChat rejects the code (invalid / expired / already used), the handler
does not return an empty openID: the failure is routed to ErrorHandler
as an *UpstreamError carrying WeChat's errcode / errmsg.
| Field | Meaning |
|---|---|
AppID |
WeChat official-account / open-platform app ID. |
AppSecret |
Corresponding app secret. |
AllowOrigins |
Allowed redirect_uri prefixes for authorize-link. Empty entries are ignored. |
ErrorHandler |
Optional func(c fiber.Ctx, err error) error. Defaults to a 500 JSON response. |
Unmarshal |
Optional custom JSON decoder. Defaults to encoding/json. |
HTTPClient |
Optional *http.Client for WeChat API calls. Defaults to a client with a 10s timeout. Outbound calls are also bound to the inbound request context. |
Handlers report failures through ErrorHandler:
ErrRedirectURIMismatch—redirect_urinot covered byAllowOrigins.ErrMissingRedirectURI/ErrMissingCode— required request field absent.ErrEmptyOpenID— WeChat answered success without anopenid.*UpstreamError— WeChat API failure; match witherrors.Asand inspectHTTPStatus(non-200 transport reply) orErrCode/ErrMsg(business failure inside a 200 body).
Register is a convenience wrapper. For full control over routing, build a
*Handler yourself and mount the handlers where you like:
h := wechatoauth.New(cfg)
app.Post("/oauth/link", h.AuthorizeLinkGen)
app.Post("/oauth/openid", h.OpenIDCallback)See LICENSE.