alipay_server_api.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. newBody := make(BodyMap)
  120. for k, v := range body {
  121. if v != null {
  122. newBody.Set(k, v)
  123. }
  124. }
  125. pKey := FormatAliPayPublicKey(aliPayPublicKey)
  126. signData := sortAliPaySignParams(newBody)
  127. //log.Println("签名字符串:", signData)
  128. err = verifyAliPaySign(signData, notifyRsp.Sign, notifyRsp.SignType, pKey)
  129. if err != nil {
  130. return false, err
  131. }
  132. return true, nil
  133. }
  134. func jsonToString(v interface{}) (str string) {
  135. if v == nil {
  136. return ""
  137. }
  138. bs, err := json.Marshal(v)
  139. if err != nil {
  140. fmt.Println("err:", err)
  141. return ""
  142. }
  143. s := string(bs)
  144. if s == "null" {
  145. return ""
  146. }
  147. return s
  148. }
  149. //格式化秘钥
  150. func FormatPrivateKey(privateKey string) (pKey string) {
  151. buffer := new(bytes.Buffer)
  152. buffer.WriteString("-----BEGIN RSA PRIVATE KEY-----\n")
  153. rawLen := 64
  154. keyLen := len(privateKey)
  155. raws := keyLen / rawLen
  156. temp := keyLen % rawLen
  157. if temp > 0 {
  158. raws++
  159. }
  160. start := 0
  161. end := start + rawLen
  162. for i := 0; i < raws; i++ {
  163. if i == raws-1 {
  164. buffer.WriteString(privateKey[start:])
  165. } else {
  166. buffer.WriteString(privateKey[start:end])
  167. }
  168. buffer.WriteString("\n")
  169. start += rawLen
  170. end = start + rawLen
  171. }
  172. buffer.WriteString("-----END RSA PRIVATE KEY-----\n")
  173. pKey = buffer.String()
  174. return
  175. }
  176. //格式化秘钥
  177. func FormatAliPayPublicKey(publicKey string) (pKey string) {
  178. buffer := new(bytes.Buffer)
  179. buffer.WriteString("-----BEGIN PUBLIC KEY-----\n")
  180. rawLen := 64
  181. keyLen := len(publicKey)
  182. raws := keyLen / rawLen
  183. temp := keyLen % rawLen
  184. if temp > 0 {
  185. raws++
  186. }
  187. start := 0
  188. end := start + rawLen
  189. for i := 0; i < raws; i++ {
  190. if i == raws-1 {
  191. buffer.WriteString(publicKey[start:])
  192. } else {
  193. buffer.WriteString(publicKey[start:end])
  194. }
  195. buffer.WriteString("\n")
  196. start += rawLen
  197. end = start + rawLen
  198. }
  199. buffer.WriteString("-----END PUBLIC KEY-----\n")
  200. pKey = buffer.String()
  201. return
  202. }
  203. func verifyAliPaySign(signData, sign, signType, aliPayPublicKey string) (err error) {
  204. var (
  205. h hash.Hash
  206. hashs crypto.Hash
  207. )
  208. signBytes, err := base64.StdEncoding.DecodeString(sign)
  209. if err != nil {
  210. return err
  211. }
  212. //解析秘钥
  213. block, _ := pem.Decode([]byte(aliPayPublicKey))
  214. if block == nil {
  215. return errors.New("支付宝公钥Decode错误")
  216. }
  217. key, err := x509.ParsePKIXPublicKey(block.Bytes)
  218. if err != nil {
  219. log.Println("x509.ParsePKIXPublicKey:", err)
  220. return err
  221. }
  222. publicKey, ok := key.(*rsa.PublicKey)
  223. if !ok {
  224. return errors.New("支付宝公钥转换错误")
  225. }
  226. //判断签名方式
  227. switch signType {
  228. case "RSA":
  229. hashs = crypto.SHA1
  230. case "RSA2":
  231. hashs = crypto.SHA256
  232. default:
  233. hashs = crypto.SHA256
  234. }
  235. h = hashs.New()
  236. h.Write([]byte(signData))
  237. return rsa.VerifyPKCS1v15(publicKey, hashs, h.Sum(nil), signBytes)
  238. }