wechat.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. package services
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/beego/beego/v2/client/orm"
  7. "github.com/rdlucklib/rdluck_tools/http"
  8. "hongze/hongze_mfyx_gzh/models"
  9. "hongze/hongze_mfyx_gzh/utils"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. type WxAccessToken struct {
  15. AccessToken string `json:"access_token"`
  16. ExpiresIn int `json:"expires_in"`
  17. RefreshToken string `json:"refresh_token"`
  18. Openid string `json:"openid"`
  19. Unionid string `json:"unionid"`
  20. Scope string `json:"scope"`
  21. Errcode int `json:"errcode"`
  22. Errmsg string `json:"errmsg"`
  23. }
  24. type WxUserInfo struct {
  25. Openid string `json:"openid"`
  26. Nickname string `json:"nickname"`
  27. Sex int `json:"sex"`
  28. Language string `json:"language"`
  29. City string `json:"city"`
  30. Province string `json:"province"`
  31. Country string `json:"country"`
  32. Headimgurl string `json:"headimgurl"`
  33. SubscribeTime int `json:"subscribe_time"`
  34. Unionid string `json:"unionid"`
  35. Remark string `json:"remark"`
  36. Groupid int `json:"groupid"`
  37. SubscribeScene string `json:"subscribe_scene"`
  38. Errcode int `json:"errcode"`
  39. Errmsg string `json:"errmsg"`
  40. SessionKey string `json:"session_key"`
  41. }
  42. type WxToken struct {
  43. AccessToken string
  44. ExpiresIn int64
  45. Id int64
  46. }
  47. func WxGetUserOpenIdByCode(code string) (item *WxAccessToken, err error) {
  48. if code == "" {
  49. err = errors.New("code is empty")
  50. return nil, err
  51. }
  52. requestUrl := `https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code`
  53. requestUrl = fmt.Sprintf(requestUrl, utils.WxAppId, utils.WxAppSecret, code)
  54. result, err := http.Get(requestUrl)
  55. if err != nil {
  56. return nil, err
  57. }
  58. err = json.Unmarshal(result, &item)
  59. return
  60. }
  61. // mfyx公众号
  62. func WxGetUserOpenIdByCodeGzh(code string) (item *WxAccessToken, err error) {
  63. if code == "" {
  64. err = errors.New("code is empty")
  65. return nil, err
  66. }
  67. //requestUrl := `https://api.weixin.qq.com/cgi-bin/token?appid=%s&secret=%s&code=%s&grant_type=client_credential`
  68. requestUrl := `https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code`
  69. requestUrl = fmt.Sprintf(requestUrl, utils.WxPublicAppId, utils.WxPublicAppSecret, code)
  70. result, err := http.Get(requestUrl)
  71. if err != nil {
  72. return nil, err
  73. }
  74. err = json.Unmarshal(result, &item)
  75. return
  76. }
  77. func WxGetToken() (item *WxAccessToken, err error) {
  78. requestUrl := `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s`
  79. requestUrl = fmt.Sprintf(requestUrl, utils.WxPublicAppId, utils.WxPublicAppSecret)
  80. result, err := http.Get(requestUrl)
  81. if err != nil {
  82. utils.FileLog.Info("获取wxToken失败,Err:%s", err.Error())
  83. return nil, err
  84. }
  85. err = json.Unmarshal(result, &item)
  86. if err != nil {
  87. fmt.Println(fmt.Sprintf("GetWxToken Unmarshal Err:%s", err.Error()))
  88. return
  89. }
  90. if item.Errmsg != "" {
  91. err = fmt.Errorf(item.Errmsg)
  92. utils.FileLog.Info(fmt.Sprintf("GetWxToken fail result:%s", string(result)))
  93. }
  94. return
  95. }
  96. func WxGetUserInfo(openId, accessToken string) (item *WxUserInfo, err error) {
  97. requestUrl := `https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s`
  98. requestUrl = fmt.Sprintf(requestUrl, accessToken, openId)
  99. result, err := http.Get(requestUrl)
  100. if err != nil {
  101. return
  102. }
  103. //fmt.Println("result:", string(result))
  104. utils.FileLog.Info("WxGetUserInfo:%s openId:%s,accessToken:%s ", string(result), openId, accessToken)
  105. utils.FileLog.Info("WxGetUserInfo Result:%s ", string(result))
  106. err = json.Unmarshal(result, &item)
  107. return
  108. }
  109. func GetWxSignature(ticket, url, noncestr string) (string, string, int64) {
  110. timestamp := time.Now().Unix()
  111. signStr := strings.Join([]string{"jsapi_ticket=", ticket,
  112. "&noncestr=", noncestr,
  113. "&timestamp=", strconv.FormatInt(timestamp, 10), "&url=", url}, "")
  114. signature := utils.Sha1(signStr)
  115. fmt.Println("signStr", signStr)
  116. return signature, noncestr, timestamp
  117. }
  118. type WxUserDetail struct {
  119. Unionid string
  120. Headimgurl string
  121. Nickname string
  122. }
  123. func GetWxAccessTokenByGzh() (accessTokenStr string, err error) {
  124. //缓存校验
  125. if utils.RunMode == "release" {
  126. cacheKey := "mfyx_wxtoken"
  127. accessTokenStr, _ = utils.Rc.RedisString(cacheKey)
  128. if accessTokenStr != "" {
  129. return
  130. } else {
  131. WxAccessToken, errWx := WxGetToken()
  132. if errWx != nil {
  133. err = errWx
  134. return
  135. }
  136. accessTokenStr = WxAccessToken.AccessToken
  137. utils.Rc.Put(cacheKey, WxAccessToken.AccessToken, time.Second*7000)
  138. }
  139. } else {
  140. accessTokenStr, err = GetWxAccessToken()
  141. if err != nil {
  142. return
  143. }
  144. }
  145. return
  146. }
  147. func GetWxTicket(accessToken string) (string, error) {
  148. Url := strings.Join([]string{"https://api.weixin.qq.com/cgi-bin/ticket/getticket",
  149. "?access_token=", accessToken,
  150. "&type=jsapi"}, "")
  151. infoBody, err := http.Get(Url)
  152. if err != nil {
  153. return "", err
  154. }
  155. atr := models.WxTicket{}
  156. err = json.Unmarshal(infoBody, &atr)
  157. fmt.Println("ticket result:", string(infoBody))
  158. if err != nil {
  159. return atr.Errmsg, err
  160. } else {
  161. return atr.Ticket, nil
  162. }
  163. }
  164. // 获取测试环境的AccessToken
  165. func GetWxAccessToken() (accessTokenStr string, err error) {
  166. o := orm.NewOrmUsingDB("weekly_report")
  167. sql := `SELECT * FROM wx_token LIMIT 1`
  168. wxToken := new(WxToken)
  169. err = o.Raw(sql).QueryRow(&wxToken)
  170. if err != nil && err.Error() != utils.ErrNoRow() {
  171. return
  172. }
  173. //Token不存在
  174. if wxToken == nil {
  175. fmt.Println("wxToken is empty")
  176. accessToken, err := WxGetToken()
  177. if err != nil {
  178. return "", err
  179. }
  180. if accessToken.AccessToken != "" {
  181. expiresIn := time.Now().Add(time.Duration(accessToken.ExpiresIn) * time.Second).Unix()
  182. addSql := "insert into wx_token (access_token,expires_in) values (?,?)"
  183. _, err = o.Raw(addSql, accessToken.AccessToken, expiresIn).Exec()
  184. accessTokenStr = accessToken.AccessToken
  185. }
  186. return accessTokenStr, err
  187. } else {
  188. //判断token是否过期
  189. if time.Now().Unix() > wxToken.ExpiresIn {
  190. accessToken, err := WxGetToken()
  191. fmt.Println(accessToken)
  192. if err != nil {
  193. return "", err
  194. }
  195. if accessToken.AccessToken != "" {
  196. expiresIn := time.Now().Add(time.Duration(accessToken.ExpiresIn) * time.Second).Unix()
  197. updateSql := "update wx_token set access_token = ?,expires_in = ? "
  198. _, err = o.Raw(updateSql, accessToken.AccessToken, expiresIn).Exec()
  199. accessTokenStr = accessToken.AccessToken
  200. fmt.Println("更新 TOKEN:", err)
  201. }
  202. return accessTokenStr, err
  203. } else {
  204. return wxToken.AccessToken, nil
  205. }
  206. }
  207. }