wechat.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package services
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta_gn/eta_report/models"
  6. "eta_gn/eta_report/services/wechat"
  7. "eta_gn/eta_report/utils"
  8. "fmt"
  9. "github.com/rdlucklib/rdluck_tools/http"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. func GetWxTicket(accessToken string) (int, string, error) {
  15. Url := strings.Join([]string{"https://api.weixin.qq.com/cgi-bin/ticket/getticket",
  16. "?access_token=", accessToken,
  17. "&type=jsapi"}, "")
  18. infoBody, err := http.Get(Url)
  19. if err != nil {
  20. return 0, "", err
  21. }
  22. atr := models.WxTicket{}
  23. err = json.Unmarshal(infoBody, &atr)
  24. fmt.Println("ticket result:", string(infoBody))
  25. if err != nil {
  26. return atr.Errcode, atr.Errmsg, err
  27. } else {
  28. return 0, atr.Ticket, nil
  29. }
  30. }
  31. func GetWxSignature(ticket, url, noncestr string) (string, string, int64) {
  32. timestamp := time.Now().Unix()
  33. signStr := strings.Join([]string{"jsapi_ticket=", ticket,
  34. "&noncestr=", noncestr,
  35. "&timestamp=", strconv.FormatInt(timestamp, 10), "&url=", url}, "")
  36. signature := utils.Sha1(signStr)
  37. fmt.Println("signStr", signStr)
  38. return signature, noncestr, timestamp
  39. }
  40. // GetDefaultWxAccessToken 获取微信token
  41. func GetDefaultWxAccessToken() (accessToken string, err error, errMsg string) {
  42. // 微信配置信息
  43. conf, e := models.GetBusinessConf()
  44. if e != nil {
  45. errMsg = "获取配置信息失败, Err: " + e.Error()
  46. err = errors.New(errMsg)
  47. return
  48. }
  49. appId := ""
  50. appSecret := ""
  51. if v, ok := conf[models.BusinessConfWxAppId]; ok {
  52. appId = v
  53. }
  54. if v, ok := conf[models.BusinessConfWxAppSecret]; ok {
  55. appSecret = v
  56. }
  57. if appId == "" || appSecret == "" {
  58. errMsg = "获取微信公众号未配置"
  59. err = errors.New(errMsg)
  60. return
  61. }
  62. req := wechat.WxTokenReq{
  63. WxAppId: appId,
  64. WxAppSecret: appSecret,
  65. }
  66. accessToken, err, errMsg = wechat.GetAccessToken(req)
  67. return
  68. }