wechat.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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_clpt/models"
  9. "hongze/hongze_clpt/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. // 小助手
  62. func WxGetUserOpenIdByCode(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/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code`
  68. requestUrl = fmt.Sprintf(requestUrl, utils.WxPublicAppId, utils.WxPublicAppSecret, code)
  69. result, err := http.Get(requestUrl)
  70. if err != nil {
  71. return nil, err
  72. }
  73. err = json.Unmarshal(result, &item)
  74. return
  75. }
  76. func WxGetToken() (item *WxAccessToken, err error) {
  77. requestUrl := `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s`
  78. requestUrl = fmt.Sprintf(requestUrl, utils.WxPublicAppId, utils.WxPublicAppSecret)
  79. result, err := http.Get(requestUrl)
  80. if err != nil {
  81. utils.FileLog.Info("获取wxToken失败,Err:%s", err.Error())
  82. return nil, err
  83. }
  84. err = json.Unmarshal(result, &item)
  85. if err != nil {
  86. fmt.Println(fmt.Sprintf("GetWxToken Unmarshal Err:%s", err.Error()))
  87. return
  88. }
  89. if item.Errmsg != "" {
  90. err = fmt.Errorf(item.Errmsg)
  91. utils.FileLog.Info(fmt.Sprintf("GetWxToken fail result:%s", string(result)))
  92. }
  93. return
  94. }
  95. func WxGetUserInfo(openId, accessToken string) (item *WxUserInfo, err error) {
  96. requestUrl := `https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s`
  97. requestUrl = fmt.Sprintf(requestUrl, accessToken, openId)
  98. result, err := http.Get(requestUrl)
  99. if err != nil {
  100. return
  101. }
  102. fmt.Println("result:", string(result))
  103. utils.FileLog.Info("WxGetUserInfo:%s openId:%s,accessToken:%s ", string(result), openId, accessToken)
  104. utils.FileLog.Info("WxGetUserInfo Result:%s ", string(result))
  105. err = json.Unmarshal(result, &item)
  106. return
  107. }
  108. func GetWxSignature(ticket, url, noncestr string) (string, string, int64) {
  109. timestamp := time.Now().Unix()
  110. signStr := strings.Join([]string{"jsapi_ticket=", ticket,
  111. "&noncestr=", noncestr,
  112. "&timestamp=", strconv.FormatInt(timestamp, 10), "&url=", url}, "")
  113. signature := utils.Sha1(signStr)
  114. fmt.Println("signStr", signStr)
  115. return signature, noncestr, timestamp
  116. }
  117. type WxUserDetail struct {
  118. Unionid string
  119. Headimgurl string
  120. Nickname string
  121. }
  122. func GetWxAccessTokenByXzs() (accessTokenStr string, err error) {
  123. //缓存校验
  124. if utils.RunMode == "release" {
  125. cacheKey := "xygxxzs_wxtoken"
  126. accessTokenStr, _ = utils.Rc.RedisString(cacheKey)
  127. if accessTokenStr != "" {
  128. return
  129. } else {
  130. WxAccessToken, errWx := WxGetToken()
  131. if errWx != nil {
  132. err = errWx
  133. return
  134. }
  135. accessTokenStr = WxAccessToken.AccessToken
  136. utils.Rc.Put(cacheKey, WxAccessToken.AccessToken, time.Second*7000)
  137. }
  138. } else {
  139. accessTokenStr, err = GetWxAccessToken()
  140. if err != nil {
  141. return
  142. }
  143. }
  144. return
  145. }
  146. func GetWxTicket(accessToken string) (string, error) {
  147. Url := strings.Join([]string{"https://api.weixin.qq.com/cgi-bin/ticket/getticket",
  148. "?access_token=", accessToken,
  149. "&type=jsapi"}, "")
  150. infoBody, err := http.Get(Url)
  151. if err != nil {
  152. return "", err
  153. }
  154. atr := models.WxTicket{}
  155. err = json.Unmarshal(infoBody, &atr)
  156. fmt.Println("ticket result:", string(infoBody))
  157. if err != nil {
  158. return atr.Errmsg, err
  159. } else {
  160. return atr.Ticket, nil
  161. }
  162. }
  163. // 获取测试环境的AccessToken
  164. func GetWxAccessToken() (accessTokenStr string, err error) {
  165. o := orm.NewOrmUsingDB("weekly_report")
  166. sql := `SELECT * FROM wx_token LIMIT 1`
  167. wxToken := new(WxToken)
  168. err = o.Raw(sql).QueryRow(&wxToken)
  169. if err != nil && err.Error() != utils.ErrNoRow() {
  170. return
  171. }
  172. //Token不存在
  173. if wxToken == nil {
  174. fmt.Println("wxToken is empty")
  175. accessToken, err := WxGetToken()
  176. if err != nil {
  177. return "", err
  178. }
  179. if accessToken.AccessToken != "" {
  180. expiresIn := time.Now().Add(time.Duration(accessToken.ExpiresIn) * time.Second).Unix()
  181. addSql := "insert into wx_token (access_token,expires_in) values (?,?)"
  182. _, err = o.Raw(addSql, accessToken.AccessToken, expiresIn).Exec()
  183. accessTokenStr = accessToken.AccessToken
  184. }
  185. return accessTokenStr, err
  186. } else {
  187. //判断token是否过期
  188. if time.Now().Unix() > wxToken.ExpiresIn {
  189. accessToken, err := WxGetToken()
  190. fmt.Println(accessToken)
  191. if err != nil {
  192. return "", err
  193. }
  194. if accessToken.AccessToken != "" {
  195. expiresIn := time.Now().Add(time.Duration(accessToken.ExpiresIn) * time.Second).Unix()
  196. updateSql := "update wx_token set access_token = ?,expires_in = ? "
  197. _, err = o.Raw(updateSql, accessToken.AccessToken, expiresIn).Exec()
  198. accessTokenStr = accessToken.AccessToken
  199. fmt.Println("更新 TOKEN:", err)
  200. }
  201. return accessTokenStr, err
  202. } else {
  203. return wxToken.AccessToken, nil
  204. }
  205. }
  206. }
  207. // 开放平台
  208. func WxGetUserOpenIdByOpenCode(code string) (item *WxAccessToken, err error) {
  209. if code == "" {
  210. err = errors.New("code is empty")
  211. return nil, err
  212. }
  213. requestUrl := `https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code`
  214. requestUrl = fmt.Sprintf(requestUrl, utils.WxOpenAppId, utils.WxOpenAppSecret, code)
  215. fmt.Println(requestUrl)
  216. result, err := http.Get(requestUrl)
  217. if err != nil {
  218. return nil, err
  219. }
  220. err = json.Unmarshal(result, &item)
  221. return
  222. }
  223. func WxGetOpenToken(wxcode string) (item *WxAccessToken, err error) {
  224. //requestUrl := `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s`
  225. requestUrl := `https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code`
  226. requestUrl = fmt.Sprintf(requestUrl, utils.WxOpenAppId, utils.WxOpenAppSecret, wxcode)
  227. result, err := http.Get(requestUrl)
  228. if err != nil {
  229. utils.FileLog.Info("获取wxToken失败,Err:%s", err.Error())
  230. return nil, err
  231. }
  232. err = json.Unmarshal(result, &item)
  233. if err != nil {
  234. fmt.Println(fmt.Sprintf("GetWxToken Unmarshal Err:%s", err.Error()))
  235. return
  236. }
  237. if item.Errmsg != "" {
  238. err = fmt.Errorf(item.Errmsg)
  239. utils.FileLog.Info(fmt.Sprintf("GetWxToken fail result:%s", string(result)))
  240. }
  241. return
  242. }
  243. func GetWxAccessOpenToken(code string) (item *WxAccessToken, err error) {
  244. //缓存校验
  245. //cacheKey := utils.OPEN_TOKEN_KEY
  246. //accessTokenStr, _ = utils.Rc.RedisString(cacheKey)
  247. //if accessTokenStr != "" {
  248. // return
  249. //} else {
  250. // WxAccessToken, errWx := WxGetOpenToken()
  251. // if errWx != nil {
  252. // err = errWx
  253. // return
  254. // }
  255. // accessTokenStr = WxAccessToken.AccessToken
  256. // utils.Rc.Put(cacheKey, WxAccessToken.AccessToken, time.Second*7000)
  257. //}
  258. WxAccessToken, errWx := WxGetOpenToken(code)
  259. if errWx != nil {
  260. err = errWx
  261. return
  262. }
  263. item = WxAccessToken
  264. //accessTokenStr = WxAccessToken.AccessToken
  265. return
  266. }
  267. func WxGetTokenXcx() (item *WxToken, err error) {
  268. requestUrl := `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s`
  269. requestUrl = fmt.Sprintf(requestUrl, utils.WxAppId, utils.WxAppSecret)
  270. result, err := http.Get(requestUrl)
  271. if err != nil {
  272. utils.FileLog.Info("WxGetToken Result:%s ", string(result))
  273. return nil, err
  274. }
  275. err = json.Unmarshal(result, &item)
  276. return
  277. }