pay.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package model
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "fmt"
  6. "sort"
  7. "strconv"
  8. "go-common/library/log"
  9. xtime "go-common/library/time"
  10. )
  11. // MsgContent 支付回调 msgContent 字段的结构
  12. // 由于 MsgContent 可能增/减字段故使用 map 兼容
  13. type MsgContent map[string]string
  14. // Charge 支付回调结构体
  15. type Charge struct {
  16. ID string
  17. Paid bool
  18. Refunded bool
  19. OrderID int64
  20. DeviceType int64
  21. Channel int64
  22. Amount int64
  23. TimePaid xtime.Time
  24. }
  25. // ValidSign 签名校验
  26. func (m MsgContent) ValidSign() (ok bool) {
  27. sign := m["sign"]
  28. delete(m, "sign")
  29. var keys []string
  30. for key := range m {
  31. keys = append(keys, key)
  32. }
  33. sort.Strings(keys)
  34. buf := bytes.Buffer{}
  35. for _, k := range keys {
  36. if buf.Len() > 0 {
  37. buf.WriteByte('&')
  38. }
  39. buf.WriteString(k)
  40. buf.WriteString("=")
  41. buf.WriteString(m[k])
  42. }
  43. fmt.Println(buf.String())
  44. h := md5.New()
  45. ok = string(h.Sum(buf.Bytes())) == sign
  46. return
  47. }
  48. // ToCharge 生成 charge 结构
  49. func (m MsgContent) ToCharge() (charge *Charge, err error) {
  50. charge = &Charge{}
  51. charge.ID = m["txId"]
  52. charge.Paid = true
  53. charge.Refunded = false
  54. orderID, err := strconv.ParseInt(m["orderId"], 10, 64)
  55. if err != nil {
  56. log.Error("MsgContent.ToCharge() strconv.ParseInt(orderId: %s) error(%v)", m["orderId"], err)
  57. return
  58. }
  59. charge.OrderID = orderID
  60. deviceType, err := strconv.ParseInt(m["deviceType"], 10, 64)
  61. if err != nil {
  62. log.Error("MsgContent.ToCharge() strconv.ParseInt(deviceType: %s) error(%v)", m["deviceType"], err)
  63. return
  64. }
  65. charge.DeviceType = deviceType
  66. payChannel, err := strconv.ParseInt(m["payChannel"], 10, 64)
  67. if err != nil {
  68. log.Error("MsgContent.ToCharge() strconv.ParseInt(payChannel: %s) error(%v)", m["payChannel"], err)
  69. return
  70. }
  71. charge.Channel = payChannel
  72. amount, err := strconv.ParseInt(m["amount"], 10, 64)
  73. if err != nil {
  74. log.Error("MsgContent.ToCharge() strconv.ParseInt(amount: %s) error(%v)", m["amount"], err)
  75. return
  76. }
  77. charge.Amount = amount
  78. if err = charge.TimePaid.Scan(m["orderPayTime"]); err != nil {
  79. log.Error("MsgContent.ToCharge() TimePaid.Scan(%v) error(%v)", m["orderPayTime"], err)
  80. return
  81. }
  82. return
  83. }