wechat.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. package services
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/rdlucklib/rdluck_tools/http"
  7. "hongze/hongze_mobile_admin/models/custom"
  8. "hongze/hongze_mobile_admin/models/tables/wx_token"
  9. "hongze/hongze_mobile_admin/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. func WxGetUserOpenIdByCode(code string) (item *WxAccessToken, err error) {
  25. if code == "" {
  26. err = errors.New("code is empty")
  27. return nil, err
  28. }
  29. requestUrl := `https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code`
  30. requestUrl = fmt.Sprintf(requestUrl, utils.WxAppId, utils.WxAppSecret, code)
  31. result, err := http.Get(requestUrl)
  32. if err != nil {
  33. return nil, err
  34. }
  35. utils.FileLog.Info("WxGetUserOpenIdByCode:%s", string(result))
  36. err = json.Unmarshal(result, &item)
  37. return
  38. }
  39. func WxGetAdminOpenIdByCode(code string) (item *WxAccessToken, err error) {
  40. if code == "" {
  41. err = errors.New("code is empty")
  42. return nil, err
  43. }
  44. requestUrl := `https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code`
  45. requestUrl = fmt.Sprintf(requestUrl, utils.AdminWxAppId, utils.AdminWxAppSecret, code)
  46. result, err := http.Get(requestUrl)
  47. if err != nil {
  48. return nil, err
  49. }
  50. utils.FileLog.Info("WxGetAdminOpenIdByCode:%s", string(result))
  51. err = json.Unmarshal(result, &item)
  52. return
  53. }
  54. type WxToken struct {
  55. AccessToken string `json:"access_token"`
  56. ExpiresIn int `json:"expires_in"`
  57. Errcode int `json:"errcode"`
  58. Errmsg string `json:"errmsg"`
  59. }
  60. func WxGetToken(wxAppId, wxAppSecret string) (item *WxToken, err error) {
  61. requestUrl := `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s`
  62. requestUrl = fmt.Sprintf(requestUrl, wxAppId, wxAppSecret)
  63. fmt.Println("requestUrl:", requestUrl)
  64. result, err := http.Get(requestUrl)
  65. if err != nil {
  66. return nil, err
  67. }
  68. item = &WxToken{}
  69. err = json.Unmarshal(result, &item)
  70. fmt.Println("WxGetToken start")
  71. fmt.Println(string(result))
  72. fmt.Println("WxGetToken end")
  73. return
  74. }
  75. func WxGetAccessToken() (accessToken string, err error) {
  76. wxToken, err := wx_token.GetWxToken()
  77. fmt.Println(err, wxToken)
  78. if err != nil && err.Error() != utils.ErrNoRow() {
  79. return
  80. }
  81. //wx_token 不存在
  82. if wxToken == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
  83. token, err := WxGetToken(utils.WxAppId, utils.WxAppSecret)
  84. if err != nil {
  85. return accessToken, err
  86. }
  87. if token.Errmsg != "" {
  88. err = errors.New("获取access_token 失败 errcode:" + token.Errmsg + " ;errmsg:" + token.Errmsg)
  89. return "", err
  90. }
  91. expiresIn := time.Now().Add(110 * time.Minute).Unix()
  92. err = wx_token.AddWxToken(token.AccessToken, expiresIn)
  93. if err != nil {
  94. err = errors.New("新增wx_token失败" + err.Error())
  95. return accessToken, err
  96. }
  97. accessToken = token.AccessToken
  98. } else {
  99. if wxToken.ExpiresIn <= time.Now().Unix() {
  100. token, err := WxGetToken(utils.WxAppId, utils.WxAppSecret)
  101. if err != nil {
  102. return accessToken, err
  103. }
  104. if token.Errmsg != "" {
  105. err = errors.New("获取access_token 失败 errcode:" + token.Errmsg + " ;errmsg:" + token.Errmsg)
  106. return "", err
  107. }
  108. expiresIn := time.Now().Add(110 * time.Minute).Unix()
  109. err = wx_token.UpdateWxToken(token.AccessToken, expiresIn, wxToken.Id)
  110. if err != nil {
  111. err = errors.New("修改wx_token失败" + err.Error())
  112. return accessToken, err
  113. }
  114. accessToken = token.AccessToken
  115. } else {
  116. accessToken = wxToken.AccessToken
  117. }
  118. }
  119. return
  120. }
  121. // WxGetRedisAccessToken 从redis中获取token
  122. func WxGetRedisAccessToken(wxAppId, wxAppSecret string) (accessToken string, err error) {
  123. //从redis中获取token校验验证码
  124. accessToken, err = utils.Rc.RedisString(utils.HZ_ADMIN_WX_ACCESS_TOEKN+wxAppId)
  125. if err != nil {
  126. err = nil
  127. token, tErr := WxGetToken(wxAppId, wxAppSecret)
  128. if tErr != nil {
  129. return "", tErr
  130. }
  131. if token.Errmsg != "" {
  132. err = errors.New("获取access_token 失败 errcode:" + token.Errmsg + " ;errmsg:" + token.Errmsg)
  133. return "", err
  134. }
  135. redisTimeExpire := time.Duration(token.ExpiresIn - 600) * time.Second
  136. err = utils.Rc.Put(utils.HZ_ADMIN_WX_ACCESS_TOEKN+wxAppId, token.AccessToken, redisTimeExpire)
  137. if err != nil {
  138. err = errors.New("保存access_token失败 " + err.Error())
  139. return accessToken, err
  140. }
  141. accessToken = token.AccessToken
  142. return
  143. }
  144. return
  145. }
  146. type WxUserInfo struct {
  147. Openid string `json:"openid"`
  148. Nickname string `json:"nickname"`
  149. Sex int `json:"sex"`
  150. Language string `json:"language"`
  151. City string `json:"city"`
  152. Province string `json:"province"`
  153. Country string `json:"country"`
  154. Headimgurl string `json:"headimgurl"`
  155. SubscribeTime int `json:"subscribe_time"`
  156. Unionid string `json:"unionid"`
  157. Remark string `json:"remark"`
  158. Groupid int `json:"groupid"`
  159. SubscribeScene string `json:"subscribe_scene"`
  160. SessionKey string `json:"session_key"`
  161. Errcode int `json:"errcode"`
  162. Errmsg string `json:"errmsg"`
  163. }
  164. func WxGetUserInfo(openId, accessToken string) (item *WxUserInfo, err error) {
  165. requestUrl := `https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s`
  166. requestUrl = fmt.Sprintf(requestUrl, accessToken, openId)
  167. result, err := http.Get(requestUrl)
  168. if err != nil {
  169. return
  170. }
  171. fmt.Println("result:", string(result))
  172. utils.FileLog.Info("WxGetUserInfo:%s openId:%s,accessToken:%s ", string(result), openId, accessToken)
  173. utils.FileLog.Info("WxGetUserInfo Result:%s ", string(result))
  174. err = json.Unmarshal(result, &item)
  175. return
  176. }
  177. func GetWxTicket(accessToken string) (string, error) {
  178. Url := strings.Join([]string{"https://api.weixin.qq.com/cgi-bin/ticket/getticket",
  179. "?access_token=", accessToken,
  180. "&type=jsapi"}, "")
  181. infoBody, err := http.Get(Url)
  182. if err != nil {
  183. return "", err
  184. }
  185. atr := custom.WxTicket{}
  186. err = json.Unmarshal(infoBody, &atr)
  187. fmt.Println("ticket result:", string(infoBody))
  188. if err != nil {
  189. return atr.Errmsg, err
  190. } else {
  191. return atr.Ticket, nil
  192. }
  193. }
  194. func GetWxSignature(ticket, url, noncestr string) (string, string, int64) {
  195. timestamp := time.Now().Unix()
  196. signStr := strings.Join([]string{"jsapi_ticket=", ticket,
  197. "&noncestr=", noncestr,
  198. "&timestamp=", strconv.FormatInt(timestamp, 10), "&url=", url}, "")
  199. signature := utils.Sha1(signStr)
  200. fmt.Println("signStr", signStr)
  201. return signature, noncestr, timestamp
  202. }
  203. type WxUserDetail struct {
  204. Unionid string
  205. Headimgurl string
  206. Nickname string
  207. }
  208. //微信接口基础返回数据
  209. type WxBase struct {
  210. Errcode int
  211. Errmsg string
  212. }
  213. //微信用户数据
  214. type WxUsers struct {
  215. WxBase
  216. Total int
  217. Count int
  218. Data struct {
  219. Openid []string
  220. }
  221. NextOpenid string
  222. }
  223. func WxUsersGet() (openIdStr string) {
  224. accessToken, err := WxGetAccessToken()
  225. if err != nil {
  226. utils.FileLog.Info("GetWxAccessToken Err:%s", err.Error())
  227. return
  228. }
  229. url := "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken
  230. result, err := http.Get(url)
  231. if err != nil {
  232. utils.FileLog.Info("GetUser Err:", err.Error())
  233. return
  234. }
  235. item := new(WxUsers)
  236. err = json.Unmarshal(result, &item)
  237. if err != nil {
  238. fmt.Println("Unmarshal Err:", err.Error())
  239. return
  240. }
  241. if item.Errcode != 0 {
  242. utils.FileLog.Info("微信接口返回异常 Err:", item.Errmsg)
  243. return
  244. }
  245. err = errors.New(item.Errmsg)
  246. openIdStr = strings.Join(item.Data.Openid, "','")
  247. openIdStr = "'" + openIdStr + "'"
  248. return
  249. }
  250. func WxAdminOpenIdGet() (openIdStr string) {
  251. accessToken, err := WxGetRedisAccessToken(utils.AdminWxAppId, utils.AdminWxAppSecret)
  252. if err != nil {
  253. utils.FileLog.Info("GetWxAccessToken Err:%s", err.Error())
  254. return
  255. }
  256. url := "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken
  257. result, err := http.Get(url)
  258. if err != nil {
  259. utils.FileLog.Info("GetUser Err:", err.Error())
  260. return
  261. }
  262. item := new(WxUsers)
  263. err = json.Unmarshal(result, &item)
  264. if err != nil {
  265. fmt.Println("Unmarshal Err:", err.Error())
  266. return
  267. }
  268. if item.Errcode != 0 {
  269. utils.FileLog.Info("微信接口返回异常 Err:", item.Errmsg)
  270. return
  271. }
  272. err = errors.New(item.Errmsg)
  273. openIdStr = strings.Join(item.Data.Openid, "','")
  274. openIdStr = "'" + openIdStr + "'"
  275. return
  276. }