sns.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package miniprogram
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/silenceper/wechat/util"
  6. )
  7. const (
  8. code2SessionURL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
  9. )
  10. // ResCode2Session 登录凭证校验的返回结果
  11. type ResCode2Session struct {
  12. util.CommonError
  13. OpenID string `json:"openid"` // 用户唯一标识
  14. SessionKey string `json:"session_key"` // 会话密钥
  15. UnionID string `json:"unionid"` // 用户在开放平台的唯一标识符,在满足UnionID下发条件的情况下会返回
  16. }
  17. // Code2Session 登录凭证校验
  18. func (wxa *MiniProgram) Code2Session(jsCode string) (result ResCode2Session, err error) {
  19. urlStr := fmt.Sprintf(code2SessionURL, wxa.AppID, wxa.AppSecret, jsCode)
  20. var response []byte
  21. response, err = util.HTTPGet(urlStr)
  22. if err != nil {
  23. return
  24. }
  25. err = json.Unmarshal(response, &result)
  26. if err != nil {
  27. return
  28. }
  29. if result.ErrCode != 0 {
  30. err = fmt.Errorf("Code2Session error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
  31. return
  32. }
  33. return
  34. }