jssdk.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package pay
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "time"
  6. "unicode/utf8"
  7. "github.com/yaotian/gowechat/mch/base"
  8. "github.com/yaotian/gowechat/util"
  9. )
  10. //OrderInput 下单
  11. //官网文档 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
  12. type OrderInput struct {
  13. OpenID string //trade_type=JSAPI时(即公众号支付),此参数必传,此参数为微信用户在商户对应appid下的唯一标识
  14. Body string //String(128)
  15. OutTradeNum string //String(32) 20150806125346 商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|*@ ,且在同一个商户号下唯一。
  16. TotalFee int //分为单位
  17. IP string
  18. NotifyURL string //异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数
  19. TradeType string //JSAPI,NATIVE,APP
  20. ProductID string //trade_type=NATIVE时(即扫码支付),此参数必传
  21. }
  22. //Config jssdk支付时需要的配置
  23. type WxPayConfig struct {
  24. AppID string `json:"appId"`
  25. TimeStamp string `json:"timeStamp"`
  26. NonceStr string `json:"nonceStr"`
  27. Package string `json:"package"`
  28. SignType string `json:"signType"`
  29. PaySign string `json:"paySign"`
  30. resultMap map[string]string
  31. }
  32. //ToString wx.chooseWXPay content
  33. func (c *WxPayConfig) ToString() (str string) {
  34. return fmt.Sprintf(`
  35. timestamp: %s,
  36. nonceStr: '%s',
  37. package: '%s',
  38. signType: '%s',
  39. paySign: '%s',
  40. `, c.TimeStamp, c.NonceStr, c.Package, c.SignType, c.PaySign)
  41. }
  42. //ToJSON WeixinJSBridge json content
  43. func (c *WxPayConfig) ToJSON() (str string) {
  44. js, err := json.Marshal(c)
  45. if err == nil {
  46. return string(js)
  47. }
  48. return
  49. }
  50. //ToMap result map[string]string
  51. func (c *WxPayConfig) ToMap() (m map[string]string) {
  52. return c.resultMap
  53. }
  54. /*GetJsAPIConfig 前端JsAPI支付时,需要提交的信息
  55. */
  56. func (c *Pay) GetJsAPIConfig(order OrderInput) (config *WxPayConfig, err error) {
  57. err = c.checkOrder(order)
  58. if err != nil {
  59. return
  60. }
  61. var prepayID string
  62. prepayID, err = c.getPrepayID(order)
  63. if err != nil {
  64. return
  65. }
  66. nocestr := util.RandomStr(8)
  67. timestamp := fmt.Sprint(time.Now().Unix())
  68. result := make(map[string]string)
  69. result["appId"] = c.AppID
  70. result["timeStamp"] = timestamp
  71. result["nonceStr"] = nocestr
  72. result["package"] = "prepay_id=" + prepayID
  73. result["signType"] = "MD5"
  74. sign := base.Sign(result, c.MchAPIKey, nil)
  75. result["paySign"] = sign
  76. config = new(WxPayConfig)
  77. config.NonceStr = util.RandomStr(8)
  78. config.TimeStamp = fmt.Sprint(time.Now().Unix())
  79. config.AppID = c.AppID
  80. config.Package = "prepay_id=" + prepayID
  81. config.SignType = "MD5"
  82. config.PaySign = sign
  83. config.resultMap = result
  84. return
  85. }
  86. // 调用 UnifiedOrder 获得 prepayID
  87. func (c *Pay) getPrepayID(order OrderInput) (prepayID string, err error) {
  88. input := c.createUnifiedOrderMap(order)
  89. var result map[string]string
  90. if result, err = c.UnifiedOrder(input); err == nil { //有prepay_id
  91. prepayID := result["prepay_id"]
  92. if prepayID != "" {
  93. return prepayID, nil
  94. }
  95. err = fmt.Errorf("prepayID is empty")
  96. }
  97. return
  98. }
  99. func (c *Pay) createUnifiedOrderMap(order OrderInput) (input map[string]string) {
  100. input = make(map[string]string)
  101. input["appid"] = c.AppID //设置微信分配的公众账号ID
  102. input["mch_id"] = c.MchID //设置微信支付分配的商户号
  103. input["nonce_str"] = util.RandomStr(5) //设置随机字符串,不长于32位。推荐随机数生成算法
  104. input["body"] = order.Body //获取商品或支付单简要描述的值
  105. input["out_trade_no"] = order.OutTradeNum //设置商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号
  106. input["total_fee"] = util.ToStr(order.TotalFee) //设置订单总金额,只能为整数,详见支付金额
  107. input["spbill_create_ip"] = order.IP //设置APP和网页支付提交用户端ip,Native支付填调用微信支付API的机器IP。
  108. input["notify_url"] = order.NotifyURL //设置接收微信支付异步通知回调地址
  109. input["trade_type"] = order.TradeType
  110. //设置取值如下:JSAPI,NATIVE,APP,详细说明见参数规定
  111. if order.ProductID != "" {
  112. input["product_id"] = order.ProductID //这个
  113. }
  114. input["openid"] = order.OpenID //设置trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。下单前需要调用【网页授权获取用户信息】接口获取到用户的Openid
  115. //sign
  116. sign := base.Sign(input, c.MchAPIKey, nil)
  117. input["sign"] = sign
  118. return
  119. }
  120. func (c *Pay) checkOrder(order OrderInput) (err error) {
  121. tradeType := order.TradeType
  122. if tradeType != "JSAPI" && tradeType != "APP" && tradeType != "NATIVE" {
  123. return fmt.Errorf("tradeType is invalid")
  124. }
  125. if tradeType == "NATIVE" {
  126. if order.ProductID == "" {
  127. err = fmt.Errorf("Native TradeType need ProductID")
  128. return
  129. }
  130. }
  131. if tradeType == "JSAPI" {
  132. if order.OpenID == "" {
  133. err = fmt.Errorf("OpenID can not be empty when pay mode is JSAPI")
  134. return
  135. }
  136. }
  137. if utf8.RuneCountInString(order.Body) > 128 || order.Body == "" {
  138. err = fmt.Errorf("Body is invalid. Size can not exceed 128.")
  139. return
  140. }
  141. if utf8.RuneCountInString(order.OutTradeNum) > 32 || order.OutTradeNum == "" {
  142. err = fmt.Errorf("OutTradeNum is invalid. Size can not exceed 128.")
  143. return
  144. }
  145. if order.TotalFee <= 0 {
  146. err = fmt.Errorf("Order TotalFee is invalid.")
  147. return
  148. }
  149. if order.IP == "" {
  150. err = fmt.Errorf("Order IP is invalid.")
  151. return
  152. }
  153. if order.NotifyURL == "" {
  154. err = fmt.Errorf("Notify URL is invalid.")
  155. return
  156. }
  157. return
  158. }