You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
1.5 KiB
60 lines
1.5 KiB
package wechat_auth
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
)
|
|
|
|
type (
|
|
ISys interface {
|
|
Auth(ctx context.Context, idToken string) (info *WeChatUserInfoResponse, err error)
|
|
}
|
|
WeChatTokenResponse struct {
|
|
AccessToken string `json:"access_token"`
|
|
ExpiresIn int `json:"expires_in"`
|
|
RefreshToken string `json:"refresh_token"`
|
|
OpenID string `json:"openid"`
|
|
Scope string `json:"scope"`
|
|
WeChatError // 内嵌错误结构
|
|
}
|
|
|
|
WeChatUserInfoResponse struct {
|
|
OpenID string `json:"openid"`
|
|
Nickname string `json:"nickname"`
|
|
HeadImgURL string `json:"headimgurl"`
|
|
UnionID string `json:"unionid"`
|
|
WeChatError
|
|
}
|
|
|
|
WeChatError struct {
|
|
ErrCode int `json:"errcode"`
|
|
ErrMsg string `json:"errmsg"`
|
|
}
|
|
)
|
|
|
|
var defsys ISys
|
|
|
|
// ErrNotInited 微信登录未初始化。OnInit 失败时调用方可选择降级;此时包级函数返回本错误,而不是 panic。
|
|
var ErrNotInited = errors.New("wechat_auth 未初始化:配置缺失")
|
|
|
|
func OnInit(config map[string]interface{}, option ...Option) error {
|
|
sys, err := newSys(newOptions(config, option...))
|
|
if err != nil {
|
|
// 出错时不要给 defsys 赋值,避免「非 nil 接口 + nil 指针」让守卫失效。
|
|
return err
|
|
}
|
|
defsys = sys
|
|
return nil
|
|
}
|
|
|
|
func NewSys(option ...Option) (sys ISys, err error) {
|
|
sys, err = newSys(newOptionsByOption(option...))
|
|
return
|
|
}
|
|
|
|
func Auth(ctx context.Context, idToken string) (info *WeChatUserInfoResponse, err error) {
|
|
if defsys == nil {
|
|
return nil, ErrNotInited
|
|
}
|
|
return defsys.Auth(ctx, idToken)
|
|
}
|
|
|