auth.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package auth
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/silenceper/wechat/v2/miniprogram/context"
  6. "github.com/silenceper/wechat/v2/util"
  7. )
  8. const (
  9. code2SessionURL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
  10. )
  11. //Auth 登录/用户信息
  12. type Auth struct {
  13. *context.Context
  14. }
  15. //NewAuth new auth
  16. func NewAuth(ctx *context.Context) *Auth {
  17. return &Auth{ctx}
  18. }
  19. // ResCode2Session 登录凭证校验的返回结果
  20. type ResCode2Session struct {
  21. util.CommonError
  22. OpenID string `json:"openid"` // 用户唯一标识
  23. SessionKey string `json:"session_key"` // 会话密钥
  24. UnionID string `json:"unionid"` // 用户在开放平台的唯一标识符,在满足UnionID下发条件的情况下会返回
  25. }
  26. //Code2Session 登录凭证校验。
  27. func (auth *Auth) Code2Session(jsCode string) (result ResCode2Session, err error) {
  28. urlStr := fmt.Sprintf(code2SessionURL, auth.AppID, auth.AppSecret, jsCode)
  29. var response []byte
  30. response, err = util.HTTPGet(urlStr)
  31. if err != nil {
  32. return
  33. }
  34. err = json.Unmarshal(response, &result)
  35. if err != nil {
  36. return
  37. }
  38. if result.ErrCode != 0 {
  39. err = fmt.Errorf("Code2Session error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
  40. return
  41. }
  42. return
  43. }
  44. //GetPaidUnionID 用户支付完成后,获取该用户的 UnionId,无需用户授权
  45. func (auth *Auth) GetPaidUnionID() {
  46. //TODO
  47. }