pay.go 5.6 KB

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