service.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package service
  2. import (
  3. "context"
  4. "crypto/sha1"
  5. "fmt"
  6. "go-common/app/interface/bbq/wechat/dao"
  7. "go-common/app/interface/bbq/wechat/internal/conf"
  8. "go-common/app/interface/bbq/wechat/internal/model"
  9. "go-common/library/log"
  10. )
  11. // Service struct
  12. type Service struct {
  13. c *conf.Config
  14. dao *dao.Dao
  15. }
  16. // New init
  17. func New(c *conf.Config) (s *Service) {
  18. s = &Service{
  19. c: c,
  20. dao: dao.New(c),
  21. }
  22. return s
  23. }
  24. // Ping Service
  25. func (s *Service) Ping(ctx context.Context) (err error) {
  26. return s.dao.Ping(ctx)
  27. }
  28. // Close Service
  29. func (s *Service) Close() {
  30. s.dao.Close()
  31. }
  32. // TokenGet .
  33. func (s *Service) TokenGet(ctx context.Context, arg *model.TokenReq, url string) (sig string, err error) {
  34. token := ""
  35. if token, err = s.dao.TokenGetLast(ctx); err != nil {
  36. log.Warnv(ctx, log.KV("log", "weixin token get last fail"))
  37. return
  38. }
  39. if token == "" {
  40. if token, err = s.dao.TokenGet(ctx); err != nil {
  41. log.Warnv(ctx, log.KV("log", "weixin token get fail"))
  42. return
  43. }
  44. }
  45. sig = s.TokenCalc(ctx, token, arg.Noncestr, arg.Timestamp, url)
  46. return
  47. }
  48. // TokenCalc 计算签名
  49. func (s *Service) TokenCalc(ctx context.Context, ticket string, noncestr string, timestamp string, url string) (sig string) {
  50. str := fmt.Sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s", ticket, noncestr, timestamp, url)
  51. hash := sha1.New()
  52. hash.Write([]byte(str))
  53. bs := hash.Sum(nil)
  54. sig = fmt.Sprintf("%x", bs)
  55. return
  56. }