auth.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. checkEncryptedDataURL = "https://api.weixin.qq.com/wxa/business/checkencryptedmsg?access_token=%s"
  11. )
  12. // Auth 登录/用户信息
  13. type Auth struct {
  14. *context.Context
  15. }
  16. // NewAuth new auth
  17. func NewAuth(ctx *context.Context) *Auth {
  18. return &Auth{ctx}
  19. }
  20. // ResCode2Session 登录凭证校验的返回结果
  21. type ResCode2Session struct {
  22. util.CommonError
  23. OpenID string `json:"openid"` // 用户唯一标识
  24. SessionKey string `json:"session_key"` // 会话密钥
  25. UnionID string `json:"unionid"` // 用户在开放平台的唯一标识符,在满足UnionID下发条件的情况下会返回
  26. }
  27. // RspCheckEncryptedData .
  28. type RspCheckEncryptedData struct {
  29. util.CommonError
  30. Vaild bool `json:"vaild"` // 是否是合法的数据
  31. CreateTime uint `json:"create_time"` // 加密数据生成的时间戳
  32. }
  33. // Code2Session 登录凭证校验。
  34. func (auth *Auth) Code2Session(jsCode string) (result ResCode2Session, err error) {
  35. var response []byte
  36. if response, err = util.HTTPGet(fmt.Sprintf(code2SessionURL, auth.AppID, auth.AppSecret, jsCode)); err != nil {
  37. return
  38. }
  39. if err = json.Unmarshal(response, &result); err != nil {
  40. return
  41. }
  42. if result.ErrCode != 0 {
  43. err = fmt.Errorf("Code2Session error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
  44. return
  45. }
  46. return
  47. }
  48. // GetPaidUnionID 用户支付完成后,获取该用户的 UnionId,无需用户授权
  49. func (auth *Auth) GetPaidUnionID() {
  50. // TODO
  51. }
  52. // CheckEncryptedData .检查加密信息是否由微信生成(当前只支持手机号加密数据),只能检测最近3天生成的加密数据
  53. func (auth *Auth) CheckEncryptedData(encryptedMsgHash string) (result RspCheckEncryptedData, err error) {
  54. var response []byte
  55. var (
  56. at string
  57. )
  58. if at, err = auth.GetAccessToken(); err != nil {
  59. return
  60. }
  61. if response, err = util.HTTPPost(fmt.Sprintf(checkEncryptedDataURL, at), "encrypted_msg_hash="+encryptedMsgHash); err != nil {
  62. return
  63. }
  64. if err = util.DecodeWithError(response, &result, "CheckEncryptedDataAuth"); err != nil {
  65. return
  66. }
  67. return
  68. }