phone_number.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package business
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/silenceper/wechat/v2/util"
  6. )
  7. const (
  8. getPhoneNumberURL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s"
  9. )
  10. // GetPhoneNumberRequest 获取手机号请求
  11. type GetPhoneNumberRequest struct {
  12. Code string `json:"code"` // 手机号获取凭证
  13. }
  14. // PhoneInfo 手机号信息
  15. type PhoneInfo struct {
  16. PhoneNumber string `json:"phoneNumber"` // 用户绑定的手机号(国外手机号会有区号)
  17. PurePhoneNumber string `json:"purePhoneNumber"` // 没有区号的手机号
  18. CountryCode string `json:"countryCode"` // 区号
  19. Watermark struct {
  20. AppID string `json:"appid"` // 小程序appid
  21. Timestamp int64 `json:"timestamp"` // 用户获取手机号操作的时间戳
  22. } `json:"watermark"`
  23. }
  24. // GetPhoneNumber code换取用户手机号。 每个code只能使用一次,code的有效期为5min
  25. func (business *Business) GetPhoneNumber(in *GetPhoneNumberRequest) (info PhoneInfo, err error) {
  26. return business.GetPhoneNumberWithContext(context.Background(), in)
  27. }
  28. // GetPhoneNumberWithContext 利用context将code换取用户手机号。 每个code只能使用一次,code的有效期为5min
  29. func (business *Business) GetPhoneNumberWithContext(ctx context.Context, in *GetPhoneNumberRequest) (info PhoneInfo, err error) {
  30. accessToken, err := business.GetAccessTokenContext(ctx)
  31. if err != nil {
  32. return
  33. }
  34. uri := fmt.Sprintf(getPhoneNumberURL, accessToken)
  35. response, err := util.PostJSONContext(ctx, uri, in)
  36. if err != nil {
  37. return
  38. }
  39. // 使用通用方法返回错误
  40. var resp struct {
  41. util.CommonError
  42. PhoneInfo PhoneInfo `json:"phone_info"`
  43. }
  44. err = util.DecodeWithError(response, &resp, "business.GetPhoneNumber")
  45. return resp.PhoneInfo, err
  46. }