alipay_server_api.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. //==================================
  2. // * Name:Jerry
  3. // * DateTime:2019/6/18 19:24
  4. // * Desc:
  5. //==================================
  6. package gopay
  7. import (
  8. "bytes"
  9. "crypto"
  10. "crypto/rsa"
  11. "crypto/x509"
  12. "encoding/base64"
  13. "encoding/json"
  14. "encoding/pem"
  15. "errors"
  16. "fmt"
  17. "hash"
  18. "log"
  19. "net/http"
  20. )
  21. //解析支付宝支付完成后的Notify信息
  22. func ParseAliPayNotifyResult(req *http.Request) (notifyRsp *AliPayNotifyRequest, err error) {
  23. notifyRsp = new(AliPayNotifyRequest)
  24. notifyRsp.NotifyTime = req.FormValue("notify_time")
  25. notifyRsp.NotifyType = req.FormValue("notify_type")
  26. notifyRsp.NotifyId = req.FormValue("notify_id")
  27. notifyRsp.AppId = req.FormValue("app_id")
  28. notifyRsp.Charset = req.FormValue("charset")
  29. notifyRsp.Version = req.FormValue("version")
  30. notifyRsp.SignType = req.FormValue("sign_type")
  31. notifyRsp.Sign = req.FormValue("sign")
  32. notifyRsp.AuthAppId = req.FormValue("auth_app_id")
  33. notifyRsp.TradeNo = req.FormValue("trade_no")
  34. notifyRsp.OutTradeNo = req.FormValue("out_trade_no")
  35. notifyRsp.OutBizNo = req.FormValue("out_biz_no")
  36. notifyRsp.BuyerId = req.FormValue("buyer_id")
  37. notifyRsp.BuyerLogonId = req.FormValue("buyer_logon_id")
  38. notifyRsp.SellerId = req.FormValue("seller_id")
  39. notifyRsp.SellerEmail = req.FormValue("seller_email")
  40. notifyRsp.TradeStatus = req.FormValue("trade_status")
  41. notifyRsp.TotalAmount = req.FormValue("total_amount")
  42. notifyRsp.ReceiptAmount = req.FormValue("receipt_amount")
  43. notifyRsp.InvoiceAmount = req.FormValue("invoice_amount")
  44. notifyRsp.BuyerPayAmount = req.FormValue("buyer_pay_amount")
  45. notifyRsp.PointAmount = req.FormValue("point_amount")
  46. notifyRsp.RefundFee = req.FormValue("refund_fee")
  47. notifyRsp.Subject = req.FormValue("subject")
  48. notifyRsp.Body = req.FormValue("body")
  49. notifyRsp.GmtCreate = req.FormValue("gmt_create")
  50. notifyRsp.GmtPayment = req.FormValue("gmt_payment")
  51. notifyRsp.GmtRefund = req.FormValue("gmt_refund")
  52. notifyRsp.GmtClose = req.FormValue("gmt_close")
  53. billList := req.FormValue("fund_bill_list")
  54. //log.Println("billList:", billList)
  55. if billList != null {
  56. bills := make([]FundBillListInfo, 0)
  57. err = json.Unmarshal([]byte(billList), &bills)
  58. if err != nil {
  59. return nil, err
  60. }
  61. notifyRsp.FundBillList = bills
  62. } else {
  63. notifyRsp.FundBillList = nil
  64. }
  65. notifyRsp.PassbackParams = req.FormValue("passback_params")
  66. detailList := req.FormValue("voucher_detail_list")
  67. //log.Println("detailList:", detailList)
  68. if detailList != null {
  69. details := make([]VoucherDetailListInfo, 0)
  70. err = json.Unmarshal([]byte(detailList), &details)
  71. if err != nil {
  72. return nil, err
  73. }
  74. notifyRsp.VoucherDetailList = details
  75. } else {
  76. notifyRsp.VoucherDetailList = nil
  77. }
  78. return notifyRsp, err
  79. }
  80. //支付通知的签名验证和参数签名后的Sign
  81. // aliPayPublicKey:支付宝公钥
  82. // notifyRsp:利用 gopay.ParseAliPayNotifyResult() 得到的结构体
  83. // 返回参数ok:是否验证通过
  84. // 返回参数err:错误信息
  85. func VerifyAliPayResultSign(aliPayPublicKey string, notifyRsp *AliPayNotifyRequest) (ok bool, err error) {
  86. body := make(BodyMap)
  87. body.Set("notify_time", notifyRsp.NotifyTime)
  88. body.Set("notify_type", notifyRsp.NotifyType)
  89. body.Set("notify_id", notifyRsp.NotifyId)
  90. body.Set("app_id", notifyRsp.AppId)
  91. body.Set("charset", notifyRsp.Charset)
  92. body.Set("version", notifyRsp.Version)
  93. //body.Set("sign", notifyRsp.Sign) //验签时去掉
  94. //body.Set("sign_type", notifyRsp.SignType) //验签时去掉
  95. body.Set("auth_app_id", notifyRsp.AuthAppId)
  96. body.Set("trade_no", notifyRsp.TradeNo)
  97. body.Set("out_trade_no", notifyRsp.OutTradeNo)
  98. body.Set("out_biz_no", notifyRsp.OutBizNo)
  99. body.Set("buyer_id", notifyRsp.BuyerId)
  100. body.Set("buyer_logon_id", notifyRsp.BuyerLogonId)
  101. body.Set("seller_id", notifyRsp.SellerId)
  102. body.Set("seller_email", notifyRsp.SellerEmail)
  103. body.Set("trade_status", notifyRsp.TradeStatus)
  104. body.Set("total_amount", notifyRsp.TotalAmount)
  105. body.Set("receipt_amount", notifyRsp.ReceiptAmount)
  106. body.Set("invoice_amount", notifyRsp.InvoiceAmount)
  107. body.Set("buyer_pay_amount", notifyRsp.BuyerPayAmount)
  108. body.Set("point_amount", notifyRsp.PointAmount)
  109. body.Set("refund_fee", notifyRsp.RefundFee)
  110. body.Set("subject", notifyRsp.Subject)
  111. body.Set("body", notifyRsp.Body)
  112. body.Set("gmt_create", notifyRsp.GmtCreate)
  113. body.Set("gmt_payment", notifyRsp.GmtPayment)
  114. body.Set("gmt_refund", notifyRsp.GmtRefund)
  115. body.Set("gmt_close", notifyRsp.GmtClose)
  116. body.Set("fund_bill_list", jsonToString(notifyRsp.FundBillList))
  117. body.Set("passback_params", notifyRsp.PassbackParams)
  118. body.Set("voucher_detail_list", jsonToString(notifyRsp.VoucherDetailList))
  119. log.Println("body.get:", body.Get("voucher_detail_list"))
  120. newBody := make(BodyMap)
  121. for k, v := range body {
  122. if v != null {
  123. newBody.Set(k, v)
  124. }
  125. }
  126. pKey := FormatAliPayPublicKey(aliPayPublicKey)
  127. signStr := sortAliPaySignParams(newBody)
  128. log.Println("签名字符串:", signStr)
  129. err = verifyAliPaySign(signStr, notifyRsp.Sign, "RSA", pKey)
  130. if err != nil {
  131. return false, err
  132. }
  133. return true, nil
  134. }
  135. func jsonToString(v interface{}) (str string) {
  136. if v == nil {
  137. return ""
  138. }
  139. bs, err := json.Marshal(v)
  140. if err != nil {
  141. fmt.Println("err:", err)
  142. return ""
  143. }
  144. //log.Println("string:", string(bs))
  145. s := string(bs)
  146. if s == "null" {
  147. return ""
  148. }
  149. return s
  150. }
  151. //格式化秘钥
  152. func FormatPrivateKey(privateKey string) (pKey string) {
  153. buffer := new(bytes.Buffer)
  154. buffer.WriteString("-----BEGIN RSA PRIVATE KEY-----\n")
  155. rawLen := 64
  156. keyLen := len(privateKey)
  157. raws := keyLen / rawLen
  158. temp := keyLen % rawLen
  159. if temp > 0 {
  160. raws++
  161. }
  162. start := 0
  163. end := start + rawLen
  164. for i := 0; i < raws; i++ {
  165. if i == raws-1 {
  166. buffer.WriteString(privateKey[start:])
  167. } else {
  168. buffer.WriteString(privateKey[start:end])
  169. }
  170. buffer.WriteString("\n")
  171. start += rawLen
  172. end = start + rawLen
  173. }
  174. buffer.WriteString("-----END RSA PRIVATE KEY-----\n")
  175. pKey = buffer.String()
  176. return
  177. }
  178. //格式化秘钥
  179. func FormatAliPayPublicKey(publicKey string) (pKey string) {
  180. buffer := new(bytes.Buffer)
  181. buffer.WriteString("-----BEGIN PUBLIC KEY-----\n")
  182. rawLen := 64
  183. keyLen := len(publicKey)
  184. raws := keyLen / rawLen
  185. temp := keyLen % rawLen
  186. if temp > 0 {
  187. raws++
  188. }
  189. start := 0
  190. end := start + rawLen
  191. for i := 0; i < raws; i++ {
  192. if i == raws-1 {
  193. buffer.WriteString(publicKey[start:])
  194. } else {
  195. buffer.WriteString(publicKey[start:end])
  196. }
  197. buffer.WriteString("\n")
  198. start += rawLen
  199. end = start + rawLen
  200. }
  201. buffer.WriteString("-----END PUBLIC KEY-----\n")
  202. pKey = buffer.String()
  203. return
  204. }
  205. func verifyAliPaySign(signData, sign, signType, aliPayPublicKey string) (err error) {
  206. var (
  207. h hash.Hash
  208. hashs crypto.Hash
  209. )
  210. signBytes, err := base64.StdEncoding.DecodeString(sign)
  211. if err != nil {
  212. return err
  213. }
  214. //解析秘钥
  215. block, _ := pem.Decode([]byte(aliPayPublicKey))
  216. if block == nil {
  217. return errors.New("支付宝公钥Decode错误")
  218. }
  219. key, err := x509.ParsePKIXPublicKey(block.Bytes)
  220. if err != nil {
  221. log.Println("x509.ParsePKIXPublicKey:", err)
  222. return err
  223. }
  224. publicKey, ok := key.(*rsa.PublicKey)
  225. if !ok {
  226. return errors.New("支付宝公钥转换错误")
  227. }
  228. //判断签名方式
  229. switch signType {
  230. case "RSA":
  231. hashs = crypto.SHA1
  232. case "RSA2":
  233. hashs = crypto.SHA256
  234. default:
  235. hashs = crypto.SHA256
  236. }
  237. h = hashs.New()
  238. h.Write([]byte(signData))
  239. err = rsa.VerifyPKCS1v15(publicKey, hashs, h.Sum(nil), signBytes)
  240. log.Println("rsa.VerifyPKCS1v15:", err)
  241. return
  242. }