pay.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package pay
  2. import (
  3. "bytes"
  4. "crypto/hmac"
  5. "crypto/md5"
  6. "crypto/sha256"
  7. "encoding/hex"
  8. "encoding/xml"
  9. "errors"
  10. "hash"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/silenceper/wechat/context"
  16. "github.com/silenceper/wechat/util"
  17. )
  18. var payGateway = "https://api.mch.weixin.qq.com/pay/unifiedorder"
  19. // Pay struct extends context
  20. type Pay struct {
  21. *context.Context
  22. }
  23. // Params was NEEDED when request unifiedorder
  24. // 传入的参数,用于生成 prepay_id 的必需参数
  25. type Params struct {
  26. TotalFee string
  27. CreateIP string
  28. Body string
  29. OutTradeNo string
  30. OpenID string
  31. TradeType string
  32. SignType string
  33. }
  34. // Config 是传出用于 js sdk 用的参数
  35. type Config struct {
  36. Timestamp string `json:"timestamp"`
  37. NonceStr string `json:"nonceStr"`
  38. PrePayID string `json:"prePayId"`
  39. SignType string `json:"signType"`
  40. Package string `json:"package"`
  41. PaySign string `json:"paySign"`
  42. }
  43. // PreOrder 是 unifie order 接口的返回
  44. type PreOrder struct {
  45. ReturnCode string `xml:"return_code"`
  46. ReturnMsg string `xml:"return_msg"`
  47. AppID string `xml:"appid,omitempty"`
  48. MchID string `xml:"mch_id,omitempty"`
  49. NonceStr string `xml:"nonce_str,omitempty"`
  50. Sign string `xml:"sign,omitempty"`
  51. ResultCode string `xml:"result_code,omitempty"`
  52. TradeType string `xml:"trade_type,omitempty"`
  53. PrePayID string `xml:"prepay_id,omitempty"`
  54. CodeURL string `xml:"code_url,omitempty"`
  55. ErrCode string `xml:"err_code,omitempty"`
  56. ErrCodeDes string `xml:"err_code_des,omitempty"`
  57. }
  58. //payRequest 接口请求参数
  59. type payRequest struct {
  60. AppID string `xml:"appid"`
  61. MchID string `xml:"mch_id"`
  62. DeviceInfo string `xml:"device_info,omitempty"`
  63. NonceStr string `xml:"nonce_str"`
  64. Sign string `xml:"sign"`
  65. SignType string `xml:"sign_type,omitempty"`
  66. Body string `xml:"body"`
  67. Detail string `xml:"detail,omitempty"`
  68. Attach string `xml:"attach,omitempty"` //附加数据
  69. OutTradeNo string `xml:"out_trade_no"` //商户订单号
  70. FeeType string `xml:"fee_type,omitempty"` //标价币种
  71. TotalFee string `xml:"total_fee"` //标价金额
  72. SpbillCreateIP string `xml:"spbill_create_ip"` //终端IP
  73. TimeStart string `xml:"time_start,omitempty"` //交易起始时间
  74. TimeExpire string `xml:"time_expire,omitempty"` //交易结束时间
  75. GoodsTag string `xml:"goods_tag,omitempty"` //订单优惠标记
  76. NotifyURL string `xml:"notify_url"` //通知地址
  77. TradeType string `xml:"trade_type"` //交易类型
  78. ProductID string `xml:"product_id,omitempty"` //商品ID
  79. LimitPay string `xml:"limit_pay,omitempty"` //
  80. OpenID string `xml:"openid,omitempty"` //用户标识
  81. SceneInfo string `xml:"scene_info,omitempty"` //场景信息
  82. }
  83. // NewPay return an instance of Pay package
  84. func NewPay(ctx *context.Context) *Pay {
  85. pay := Pay{Context: ctx}
  86. return &pay
  87. }
  88. // BridgeConfig get js bridge config
  89. func (pcf *Pay) BridgeConfig(p *Params) (cfg Config, err error) {
  90. var (
  91. buffer strings.Builder
  92. h hash.Hash
  93. timestamp = strconv.FormatInt(time.Now().Unix(), 10)
  94. )
  95. order, err := pcf.PrePayOrder(p)
  96. if err != nil {
  97. return
  98. }
  99. if p.SignType == "" {
  100. p.SignType = "MD5"
  101. }
  102. buffer.WriteString("appId=")
  103. buffer.WriteString(order.AppID)
  104. buffer.WriteString("&nonceStr=")
  105. buffer.WriteString(order.NonceStr)
  106. buffer.WriteString("&package=")
  107. buffer.WriteString("prepay_id=" + order.PrePayID)
  108. buffer.WriteString("&signType=")
  109. buffer.WriteString(p.SignType)
  110. buffer.WriteString("&timeStamp=")
  111. buffer.WriteString(timestamp)
  112. buffer.WriteString("&key=")
  113. buffer.WriteString(pcf.PayKey)
  114. if p.SignType == "MD5" {
  115. h = md5.New()
  116. } else {
  117. h = hmac.New(sha256.New, []byte(pcf.PayKey))
  118. }
  119. h.Write([]byte(buffer.String()))
  120. // 签名
  121. cfg.PaySign = strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
  122. cfg.NonceStr = order.NonceStr
  123. cfg.Timestamp = timestamp
  124. cfg.PrePayID = order.PrePayID
  125. cfg.SignType = p.SignType
  126. cfg.Package = "prepay_id=" + order.PrePayID
  127. return
  128. }
  129. // PrePayOrder return data for invoke wechat payment
  130. func (pcf *Pay) PrePayOrder(p *Params) (payOrder PreOrder, err error) {
  131. nonceStr := util.RandomStr(32)
  132. param := make(map[string]interface{})
  133. param["appid"] = pcf.AppID
  134. param["body"] = p.Body
  135. param["mch_id"] = pcf.PayMchID
  136. param["nonce_str"] = nonceStr
  137. param["notify_url"] = pcf.PayNotifyURL
  138. param["out_trade_no"] = p.OutTradeNo
  139. param["spbill_create_ip"] = p.CreateIP
  140. param["total_fee"] = p.TotalFee
  141. param["trade_type"] = p.TradeType
  142. param["openid"] = p.OpenID
  143. bizKey := "&key=" + pcf.PayKey
  144. str := orderParam(param, bizKey)
  145. sign := util.MD5Sum(str)
  146. request := payRequest{
  147. AppID: pcf.AppID,
  148. MchID: pcf.PayMchID,
  149. NonceStr: nonceStr,
  150. Sign: sign,
  151. Body: p.Body,
  152. OutTradeNo: p.OutTradeNo,
  153. TotalFee: p.TotalFee,
  154. SpbillCreateIP: p.CreateIP,
  155. NotifyURL: pcf.PayNotifyURL,
  156. TradeType: p.TradeType,
  157. OpenID: p.OpenID,
  158. }
  159. rawRet, err := util.PostXML(payGateway, request)
  160. if err != nil {
  161. return
  162. }
  163. err = xml.Unmarshal(rawRet, &payOrder)
  164. if err != nil {
  165. return
  166. }
  167. if payOrder.ReturnCode == "SUCCESS" {
  168. //pay success
  169. if payOrder.ResultCode == "SUCCESS" {
  170. err = nil
  171. return
  172. }
  173. err = errors.New(payOrder.ErrCode + payOrder.ErrCodeDes)
  174. return
  175. }
  176. err = errors.New("[msg : xmlUnmarshalError] [rawReturn : " + string(rawRet) + "] [params : " + str + "] [sign : " + sign + "]")
  177. return
  178. }
  179. // PrePayID will request wechat merchant api and request for a pre payment order id
  180. func (pcf *Pay) PrePayID(p *Params) (prePayID string, err error) {
  181. order, err := pcf.PrePayOrder(p)
  182. if err != nil {
  183. return
  184. }
  185. if order.PrePayID == "" {
  186. err = errors.New("empty prepayid")
  187. }
  188. prePayID = order.PrePayID
  189. return
  190. }
  191. // order params
  192. func orderParam(source interface{}, bizKey string) (returnStr string) {
  193. switch v := source.(type) {
  194. case map[string]string:
  195. keys := make([]string, 0, len(v))
  196. for k := range v {
  197. if k == "sign" {
  198. continue
  199. }
  200. keys = append(keys, k)
  201. }
  202. sort.Strings(keys)
  203. var buf bytes.Buffer
  204. for _, k := range keys {
  205. if v[k] == "" {
  206. continue
  207. }
  208. if buf.Len() > 0 {
  209. buf.WriteByte('&')
  210. }
  211. buf.WriteString(k)
  212. buf.WriteByte('=')
  213. buf.WriteString(v[k])
  214. }
  215. buf.WriteString(bizKey)
  216. returnStr = buf.String()
  217. case map[string]interface{}:
  218. keys := make([]string, 0, len(v))
  219. for k := range v {
  220. if k == "sign" {
  221. continue
  222. }
  223. keys = append(keys, k)
  224. }
  225. sort.Strings(keys)
  226. var buf bytes.Buffer
  227. for _, k := range keys {
  228. if v[k] == "" {
  229. continue
  230. }
  231. if buf.Len() > 0 {
  232. buf.WriteByte('&')
  233. }
  234. buf.WriteString(k)
  235. buf.WriteByte('=')
  236. switch vv := v[k].(type) {
  237. case string:
  238. buf.WriteString(vv)
  239. case int:
  240. buf.WriteString(strconv.FormatInt(int64(vv), 10))
  241. default:
  242. panic("params type not supported")
  243. }
  244. }
  245. buf.WriteString(bizKey)
  246. returnStr = buf.String()
  247. }
  248. return
  249. }