51 lines
1.2 KiB
Go
51 lines
1.2 KiB
Go
package auth
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"lone-services/pkg/utils"
|
|
|
|
jsoniter "github.com/json-iterator/go"
|
|
)
|
|
|
|
const code2SessionURL = "https://api.weixin.qq.com/sns/jscode2session"
|
|
|
|
type Session struct {
|
|
OpenID string `json:"openid"`
|
|
UnionID string `json:"unionid"`
|
|
SessionKey string `json:"session_key"`
|
|
ErrCode int `json:"errcode"`
|
|
ErrMsg string `json:"errmsg"`
|
|
}
|
|
|
|
func (c *Client) Code2Session(code string) (*Session, error) {
|
|
if c == nil || c.AppID == utils.StringEmpty || c.Secret == utils.StringEmpty {
|
|
return nil, fmt.Errorf("wechat app config missing")
|
|
}
|
|
if code == utils.StringEmpty {
|
|
return nil, fmt.Errorf("wechat code empty")
|
|
}
|
|
|
|
body, err := utils.Curl(code2SessionURL).SetData(map[string]string{
|
|
"appid": c.AppID,
|
|
"secret": c.Secret,
|
|
"js_code": code,
|
|
"grant_type": "authorization_code",
|
|
}).Get("")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var session Session
|
|
if err := jsoniter.UnmarshalFromString(body, &session); err != nil {
|
|
return nil, err
|
|
}
|
|
if session.ErrCode != utils.NumberZero {
|
|
return nil, fmt.Errorf("wechat code2session: %d %s", session.ErrCode, session.ErrMsg)
|
|
}
|
|
if session.OpenID == utils.StringEmpty {
|
|
return nil, fmt.Errorf("wechat openid empty")
|
|
}
|
|
return &session, nil
|
|
}
|