gopay

package module
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 18, 2019 License: Apache-2.0 Imports: 30 Imported by: 0

README

Logo was Loading Faild!

GoPay

微信支付

  • 统一下单:client.UnifiedOrder()
    • JSAPI - JSAPI支付(或小程序支付)
    • NATIVE - Native支付
    • APP - app支付
    • MWEB - H5支付
  • 提交付款码支付:client.Micropay()
  • 查询订单:client.QueryOrder()
  • 关闭订单:client.CloseOrder()
  • 撤销订单:client.Reverse()
  • 申请退款:client.Refund()
  • 查询退款:client.QueryRefund()
  • 下载对账单:client.DownloadBill()
  • 下载资金账单:client.DownloadFundFlow()
  • 拉取订单评价数据:client.BatchQueryComment()

微信公共API

  • gopay.ParseNotifyResult() => 解析并返回微信支付通知的参数
  • gopay.VerifyPayResultSign() => 支付通知的签名验证和参数签名后的Sign
  • gopay.Code2Session() => 登录凭证校验:获取微信用户OpenId、UnionId、SessionKey
  • gopay.GetAccessToken() => 获取小程序全局唯一后台接口调用凭据
  • gopay.GetPaidUnionId() => 用户支付完成后,获取该用户的 UnionId,无需用户授权
  • gopay.GetWeChatUserInfo() => 微信公众号:获取用户基本信息(UnionID机制)
  • gopay.DecryptOpenDataToStruct() => 加密数据,解密到指定结构体

支付宝支付

  • 手机网站支付:client.AliPayTradeWapPay()
  • APP支付:client.AliPayTradeAppPay()

支付宝公共API

  • gopay.FormatPrivateKey() => 格式化应用私钥
  • gopay.FormatAliPayPublicKey() => 格式化支付宝公钥

安装

$ go get -u github.com/iGoogle-ink/gopay

文档

  • 未完成,有问题+微信

微信:

微信支付

注意:具体参数根据请求的不同而不同,请参考微信官方文档的参数说明!

参考文档:微信支付文档

获取微信用户OpenId、UnionId、SessionKey
userIdRsp, err := gopay.Code2Session(appID, secretKey, "")
if err != nil {
	fmt.Println("Error:", err)
	return
}
fmt.Println("OpenID:", userIdRsp.Openid)
fmt.Println("UnionID:", userIdRsp.Unionid)
fmt.Println("SessionKey:", userIdRsp.SessionKey)
微信小程序支付,统一下单后,需要进一步获取微信小程序支付所需要的paySign
  • 小程序支付所需要的参数,paySign由后端计算
    • timeStamp
    • nonceStr
    • package
    • signType
    • paySign

官方文档说明微信小程序支付API

timeStamp := strconv.FormatInt(time.Now().Unix(), 10)
packages := "prepay_id=" + wxRsp.PrepayId   //此处的 wxRsp.PrepayId ,统一下单成功后得到
paySign := gopay.GetMiniPaySign("wxd678efh567hg6787", wxRsp.NonceStr, packages, gopay.SignType_MD5, timeStamp, "192006250b4c09247ec02edce69f6a2d")

//微信小程序支付需要的参数信息
fmt.Println("timeStamp:", timeStamp)
fmt.Println("nonceStr:", wxRsp.NonceStr)
fmt.Println("package:", packages)
fmt.Println("signType:", gopay.SignType_MD5)
fmt.Println("paySign:", paySign)
微信内H5支付,统一下单后,需要进一步获取H5支付所需要的paySign
  • 微信内H5支付所需要的参数,paySign由后端计算
    • appId
    • timeStamp
    • nonceStr
    • package
    • signType
    • paySign

官方文档说明微信内H5支付文档

timeStamp := strconv.FormatInt(time.Now().Unix(), 10)
packages := "prepay_id=" + wxRsp.PrepayId   //此处的 wxRsp.PrepayId ,统一下单成功后得到
paySign := gopay.GetH5PaySign("wxd678efh567hg6787", wxRsp.NonceStr, packages, gopay.SignType_MD5, timeStamp, "192006250b4c09247ec02edce69f6a2d")

//微信内H5支付需要的参数信息
fmt.Println("appId:","wxd678efh567hg6787")
fmt.Println("timeStamp:", timeStamp)
fmt.Println("nonceStr:", wxRsp.NonceStr)
fmt.Println("package:", packages)
fmt.Println("signType:", gopay.SignType_MD5)
fmt.Println("paySign:", paySign)
APP支付,统一下单后,需要进一步获取APP支付所需要的paySign
  • APP支付所需要的参数,paySign由后端计算
    • appid
    • partnerid
    • noncestr
    • prepayid
    • package
    • timestamp
    • sign

官方文档说明APP端调起支付的参数列表文档

timeStamp := strconv.FormatInt(time.Now().Unix(), 10)
//注意:signType:此处签名方式,务必与统一下单时用的签名方式一致
//注意:package:参数因为是固定值,不需开发者再传入
sign := gopay.GetH5PaySign(appid, partnerid, wxRsp.NonceStr, prepayid, gopay.SignType_MD5, timeStamp, apiKey)

//APP支付需要的参数信息
fmt.Println("sign:", sign)
支付结果通知回调:参数解析和Sign值的验证

微信支付后的回调通知文档支付结果通知

//解析支付完成后的回调信息
notifyRsp, err := gopay.ParseNotifyResult(c.Request())
if err != nil {
    fmt.Println("err:", err)
}
fmt.Println("notifyRsp:", notifyRsp)

//支付通知的签名验证和参数签名后的Sign
//    apiKey:API秘钥值
//    signType:签名类型 MD5 或 HMAC-SHA256(默认请填写 MD5)
//    notifyRsp:利用 gopay.ParseNotifyResult() 得到的结构体
//    返回参数ok:是否验证通过
//    返回参数sign:根据参数计算的sign值,非微信返回参数中的Sign
ok, sign := gopay.VerifyPayResultSign("192006250b4c09247ec02edce69f6a2d", "MD5", notifyRsp)
log.Println("ok:", ok)
log.Println("sign:", sign)
加密数据,解密到指定结构体

拿小程序获取手机号为例

button按钮获取手机号码:button组件文档

微信解密算法文档:解密算法文档

data := "Kf3TdPbzEmhWMuPKtlKxIWDkijhn402w1bxoHL4kLdcKr6jT1jNcIhvDJfjXmJcgDWLjmBiIGJ5acUuSvxLws3WgAkERmtTuiCG10CKLsJiR+AXVk7B2TUQzsq88YVilDz/YAN3647REE7glGmeBPfvUmdbfDzhL9BzvEiuRhABuCYyTMz4iaM8hFjbLB1caaeoOlykYAFMWC5pZi9P8uw=="
iv := "Cds8j3VYoGvnTp1BrjXdJg=="
sessionKey := "lyY4HPQbaOYzZdG+JcYK9w=="

phone := new(gopay.WeChatUserPhone)
err := gopay.DecryptOpenDataToStruct(data, iv, sessionKey, phone)
if err != nil {
	fmt.Println("err:", err)
	return
}
fmt.Println("PhoneNumber:", phone.PhoneNumber)
fmt.Println("PurePhoneNumber:", phone.PurePhoneNumber)
fmt.Println("CountryCode:", phone.CountryCode)
fmt.Println("Watermark:", phone.Watermark)
付款结果回调,需回复微信平台是否成功

代码中return写法,由于本人用的Echo Web框架,有兴趣的可以尝试一下

rsp := new(gopay.WeChatNotifyResponse) //回复微信的数据

rsp.ReturnCode = "SUCCESS"
rsp.ReturnMsg = "OK"

return c.String(http.StatusOK, rsp.ToXmlString())
统一下单
//初始化微信客户端
//    appId:应用ID
//    mchID:商户ID
//    apiKey:API秘钥值
//    isProd:是否是正式环境
client := gopay.NewWeChatClient("wxd678efh567hg6787", "1230000109", "192006250b4c09247ec02edce69f6a2d", false)

//初始化参数Map
body := make(gopay.BodyMap)
body.Set("nonce_str", gopay.GetRandomString(32))
body.Set("body", "测试支付")
number := gopay.GetRandomString(32)
log.Println("Number:", number)
body.Set("out_trade_no", number)
body.Set("total_fee", 1)
body.Set("spbill_create_ip", "127.0.0.1")   //终端IP
body.Set("notify_url", "http://www.igoogle.ink")
body.Set("trade_type", gopay.TradeType_JsApi)
body.Set("device_info", "WEB")
body.Set("sign_type", gopay.SignType_MD5)
//body.Set("scene_info", `{"h5_info": {"type":"Wap","wap_url": "http://www.igoogle.ink","wap_name": "测试支付"}}`)
body.Set("openid", "o0Df70H2Q0fY8JXh1aFPIRyOBgu6")

//发起下单请求
wxRsp, err := client.UnifiedOrder(body)
if err != nil {
	fmt.Println("Error:", err)
	return
}
fmt.Println("ReturnCode:", wxRsp.ReturnCode)
fmt.Println("ReturnMsg:", wxRsp.ReturnMsg)
fmt.Println("Appid:", wxRsp.Appid)
fmt.Println("MchId:", wxRsp.MchId)
fmt.Println("DeviceInfo:", wxRsp.DeviceInfo)
fmt.Println("NonceStr:", wxRsp.NonceStr)
fmt.Println("Sign:", wxRsp.Sign)
fmt.Println("ResultCode:", wxRsp.ResultCode)
fmt.Println("ErrCode:", wxRsp.ErrCode)
fmt.Println("ErrCodeDes:", wxRsp.ErrCodeDes)
fmt.Println("PrepayId:", wxRsp.PrepayId)
fmt.Println("TradeType:", wxRsp.TradeType)
fmt.Println("CodeUrl:", wxRsp.CodeUrl)
fmt.Println("MwebUrl:", wxRsp.MwebUrl)
提交付款码支付
//初始化微信客户端
//    appId:应用ID
//    mchID:商户ID
//    apiKey:API秘钥值
//    isProd:是否是正式环境
client := gopay.NewWeChatClient("wxd678efh567hg6787", "1230000109", "192006250b4c09247ec02edce69f6a2d", false)

//初始化参数Map
body := make(gopay.BodyMap)
body.Set("nonce_str", gopay.GetRandomString(32))
body.Set("body", "扫用户付款码支付")
number := gopay.GetRandomString(32)
log.Println("Number:", number)
body.Set("out_trade_no", number)
body.Set("total_fee", 1)
body.Set("spbill_create_ip", "127.0.0.1")
body.Set("notify_url", "http://www.igoogle.ink")
body.Set("auth_code", "120061098828009406")
body.Set("sign_type", gopay.SignType_MD5)

//请求支付,成功后得到结果
wxRsp, err := client.Micropay(body)
if err != nil {
	fmt.Println("Error:", err)
}
fmt.Println("Response:", wxRsp)
申请退款
//初始化微信客户端
//    appId:应用ID
//    mchID:商户ID
//    apiKey:API秘钥值
//    isProd:是否是正式环境
client := gopay.NewWeChatClient("wxd678efh567hg6787", "1230000109", "192006250b4c09247ec02edce69f6a2d", false)

//初始化参数结构体
body := make(gopay.BodyMap)
body.Set("out_trade_no", "MfZC2segKxh0bnJSELbvKNeH3d9oWvvQ")
body.Set("nonce_str", gopay.GetRandomString(32))
body.Set("sign_type", gopay.SignType_MD5)
s := gopay.GetRandomString(64)
fmt.Println("s:", s)
body.Set("out_refund_no", s)
body.Set("total_fee", 101)
body.Set("refund_fee", 101)

//请求申请退款(沙箱环境下,证书路径参数可传空)
//    body:参数Body
//    certFilePath:cert证书路径
//    keyFilePath:Key证书路径
//    pkcs12FilePath:p12证书路径
wxRsp, err := client.Refund(body, "", "", "")
if err != nil {
	fmt.Println("Error:", err)
}
fmt.Println("Response:", wxRsp)
查询订单
client := gopay.NewWeChatClient("wxd678efh567hg6787", "1230000109", "192006250b4c09247ec02edce69f6a2d", false)

//初始化参数结构体
body := make(gopay.BodyMap)
body.Set("out_trade_no", "CC68aTofMIwVKkVR5UruoBLFFXTAqBfv")
body.Set("nonce_str", gopay.GetRandomString(32))
body.Set("sign_type", gopay.SignType_MD5)

//请求查询订单
wxRsp, err := client.QueryOrder(body)
if err != nil {
	fmt.Println("Error:", err)
	return
}
fmt.Println("Response:", wxRsp)
下载账单
//初始化微信客户端
//    appId:应用ID
//    mchID:商户ID
//    apiKey:API秘钥值
//    isProd:是否是正式环境
client := gopay.NewWeChatClient("wxd678efh567hg6787", "1230000109", "192006250b4c09247ec02edce69f6a2d", false)

//初始化参数结构体
body := make(gopay.BodyMap)
body.Set("nonce_str", gopay.GetRandomString(32))
body.Set("sign_type", gopay.SignType_MD5)
body.Set("bill_date", "20190122")
body.Set("bill_type", "ALL")

//请求下载账单,成功后得到结果(string类型)
wxRsp, err := client.DownloadBill(body)
if err != nil {
	fmt.Println("Error:", err)
}
fmt.Println("Response:", wxRsp)

支付宝支付

注意:具体请求参数根据请求的不同而不同,请参考支付宝官方文档的参数说明!

支付宝官方文档:官方文档

支付宝RSA秘钥生成文档:生成 RSA 密钥

支付宝在线调试:在线调试地址

沙箱环境使用说明:文档地址

手机网站支付
  • 手机网站支付是通过服务端获取支付URL后,然后返回给客户端,请求URL地址即可打开支付页面

文档说明手机网站支付-请求参数说明

文档说明手机网站支付接口2.0

privateKey := "MIIEogIBAAKCAQEAy+CRzKw4krA2RzCDTqg5KJg92XkOY0RN3pW4sYInPqnGtHV7YDHu5nMuxY6un+dLfo91OFOEg+RI+WTOPoM4xJtsOaJwQ1lpjycoeLq1OyetGW5Q8wO+iLWJASaMQM/t/aXR/JHaguycJyqlHSlxANvKKs/tOHx9AhW3LqumaCwz71CDF/+70scYuZG/7wxSjmrbRBswxd1Sz9KHdcdjqT8pmieyPqnM24EKBexHDmQ0ySXvLJJy6eu1dJsPIz+ivX6HEfDXmSmJ71AZVqZyCI1MhK813R5E7XCv5NOtskTe3y8uiIhgGpZSdB77DOyPLcmVayzFVLAQ3AOBDmsY6wIDAQABAoIBAHjsNq31zAw9FcR9orQJlPVd7vlJEt6Pybvmg8hNESfanO+16rpwg2kOEkS8zxgqoJ1tSzJgXu23fgzl3Go5fHcoVDWPAhUAOFre9+M7onh2nPXDd6Hbq6v8OEmFapSaf2b9biHnBHq5Chk08v/r74l501w3PVVOiPqulJrK1oVb+0/YmCvVFpGatBcNaefKUEcA+vekWPL7Yl46k6XeUvRfTwomCD6jpYLUhsAKqZiQJhMGoaLglZvkokQMF/4G78K7FbbVLMM1+JDh8zJ/DDVdY2vHREUcCGhl4mCVQtkzIbpxG++vFg7/g/fDI+PquG22hFILTDdtt2g2fV/4wmkCgYEA6goRQYSiM03y8Tt/M4u1Mm7OWYCksqAsU7rzQllHekIN3WjD41Xrjv6uklsX3sTG1syo7Jr9PGE1xQgjDEIyO8h/3lDQyLyycYnyUPGNNMX8ZjmGwcM51DQ/QfIrY/CXjnnW+MVpmNclAva3L33KXCWjw20VsROV1EA8LCL94BUCgYEA3wH4ANpzo7NqXf+2WlPPMuyRrF0QPIRGlFBNtaKFy0mvoclkREPmK7+N4NIGtMf5JNODS5HkFRgmU4YNdupA2I8lIYpD+TsIobZxGUKUkYzRZYZ1m1ttL69YYvCVz9Xosw/VoQ+RrW0scS5yUKqFMIUOV2R/Imi//c5TdKx6VP8CgYAnJ1ADugC4vI2sNdvt7618pnT3HEJxb8J6r4gKzYzbszlGlURQQAuMfKcP7RVtO1ZYkRyhmLxM4aZxNA9I+boVrlFWDAchzg+8VuunBwIslgLHx0/4EoUWLzd1/OGtco6oU1HXhI9J9pRGjqfO1iiIifN/ujwqx7AFNknayG/YkQKBgD6yNgA/ak12rovYzXKdp14Axn+39k2dPp6J6R8MnyLlB3yruwW6NSbNhtzTD1GZ+wCQepQvYvlPPc8zm+t3tl1r+Rtx3ORf5XBZc3iPkGdPOLubTssrrAnA+U9vph61W+OjqwLJ9sHUNK9pSHhHSIS4k6ycM2YAHyIC9NGTgB0PAoGAJjwd1DgMaQldtWnuXjvohPOo8cQudxXYcs6zVRbx6vtjKe2v7e+eK1SSVrR5qFV9AqxDfGwq8THenRa0LC3vNNplqostuehLhkWCKE7Y75vXMR7N6KU1kdoVWgN4BhXSwuRxmHMQfSY7q3HG3rDGz7mzXo1FVMr/uE4iDGm0IXY="
//初始化支付宝客户端
//    appId:应用ID
//    privateKey:应用秘钥
//    isProd:是否是正式环境
client := gopay.NewAliPayClient("2016091200494382", privateKey, false)
//配置公共参数
client.SetCharset("utf-8").
	SetSignType("RSA2").
	SetReturnUrl("https://www.igoogle.ink").
	SetNotifyUrl("https://www.igoogle.ink")
//请求参数
body := make(gopay.BodyMap)
body.Set("subject", "测试支付")
body.Set("out_trade_no", "GYWX201901301040355706100409")
body.Set("quit_url", "https://www.igoogle.ink")
body.Set("total_amount", "10.00")
body.Set("product_code", "QUICK_WAP_WAY")
//手机网站支付请求
payUrl, err := client.AliPayTradeWapPay(body)
if err != nil {
	log.Println("err:", err)
	return
}
fmt.Println("payUrl:", payUrl)
APP支付
  • APP支付是通过服务端获取支付参数后,然后通过Android/iOS客户端的SDK调用支付功能

文档说明APP支付-请求参数说明

文档说明APP支付接口2.0

privateKey := "MIIEogIBAAKCAQEAy+CRzKw4krA2RzCDTqg5KJg92XkOY0RN3pW4sYInPqnGtHV7YDHu5nMuxY6un+dLfo91OFOEg+RI+WTOPoM4xJtsOaJwQ1lpjycoeLq1OyetGW5Q8wO+iLWJASaMQM/t/aXR/JHaguycJyqlHSlxANvKKs/tOHx9AhW3LqumaCwz71CDF/+70scYuZG/7wxSjmrbRBswxd1Sz9KHdcdjqT8pmieyPqnM24EKBexHDmQ0ySXvLJJy6eu1dJsPIz+ivX6HEfDXmSmJ71AZVqZyCI1MhK813R5E7XCv5NOtskTe3y8uiIhgGpZSdB77DOyPLcmVayzFVLAQ3AOBDmsY6wIDAQABAoIBAHjsNq31zAw9FcR9orQJlPVd7vlJEt6Pybvmg8hNESfanO+16rpwg2kOEkS8zxgqoJ1tSzJgXu23fgzl3Go5fHcoVDWPAhUAOFre9+M7onh2nPXDd6Hbq6v8OEmFapSaf2b9biHnBHq5Chk08v/r74l501w3PVVOiPqulJrK1oVb+0/YmCvVFpGatBcNaefKUEcA+vekWPL7Yl46k6XeUvRfTwomCD6jpYLUhsAKqZiQJhMGoaLglZvkokQMF/4G78K7FbbVLMM1+JDh8zJ/DDVdY2vHREUcCGhl4mCVQtkzIbpxG++vFg7/g/fDI+PquG22hFILTDdtt2g2fV/4wmkCgYEA6goRQYSiM03y8Tt/M4u1Mm7OWYCksqAsU7rzQllHekIN3WjD41Xrjv6uklsX3sTG1syo7Jr9PGE1xQgjDEIyO8h/3lDQyLyycYnyUPGNNMX8ZjmGwcM51DQ/QfIrY/CXjnnW+MVpmNclAva3L33KXCWjw20VsROV1EA8LCL94BUCgYEA3wH4ANpzo7NqXf+2WlPPMuyRrF0QPIRGlFBNtaKFy0mvoclkREPmK7+N4NIGtMf5JNODS5HkFRgmU4YNdupA2I8lIYpD+TsIobZxGUKUkYzRZYZ1m1ttL69YYvCVz9Xosw/VoQ+RrW0scS5yUKqFMIUOV2R/Imi//c5TdKx6VP8CgYAnJ1ADugC4vI2sNdvt7618pnT3HEJxb8J6r4gKzYzbszlGlURQQAuMfKcP7RVtO1ZYkRyhmLxM4aZxNA9I+boVrlFWDAchzg+8VuunBwIslgLHx0/4EoUWLzd1/OGtco6oU1HXhI9J9pRGjqfO1iiIifN/ujwqx7AFNknayG/YkQKBgD6yNgA/ak12rovYzXKdp14Axn+39k2dPp6J6R8MnyLlB3yruwW6NSbNhtzTD1GZ+wCQepQvYvlPPc8zm+t3tl1r+Rtx3ORf5XBZc3iPkGdPOLubTssrrAnA+U9vph61W+OjqwLJ9sHUNK9pSHhHSIS4k6ycM2YAHyIC9NGTgB0PAoGAJjwd1DgMaQldtWnuXjvohPOo8cQudxXYcs6zVRbx6vtjKe2v7e+eK1SSVrR5qFV9AqxDfGwq8THenRa0LC3vNNplqostuehLhkWCKE7Y75vXMR7N6KU1kdoVWgN4BhXSwuRxmHMQfSY7q3HG3rDGz7mzXo1FVMr/uE4iDGm0IXY="
//初始化支付宝客户端
//    appId:应用ID
//    privateKey:应用秘钥
//    isProd:是否是正式环境
client := gopay.NewAliPayClient("2016091200494382", privateKey, false)
//配置公共参数
client.SetCharset("utf-8").
	SetSignType("RSA2").
	SetNotifyUrl("https://www.igoogle.ink")
//请求参数
body := make(gopay.BodyMap)
body.Set("subject", "测试APP支付")
body.Set("out_trade_no", "GYWX201901301040355706100411")
body.Set("total_amount", "1.00")
body.Set("product_code", "QUICK_MSECURITY_PAY")
//手机APP支付参数请求
payParam, err := client.AliPayTradeAppPay(body)
if err != nil {
	fmt.Println("err:", err)
	return
}
fmt.Println("payParam:", payParam)

License

Copyright 2019 Jerry

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Documentation

Overview

==================================

  • Name:Jerry
  • Tel:18017448610
  • DateTime:2019/1/13 14:42

==================================

==================================

  • Name:Jerry
  • Tel:18017448610
  • DateTime:2019/1/16 0:30

==================================

==================================

  • Name:Jerry
  • DateTime:2019/6/18 19:24
  • Desc:

==================================

==================================

  • Name:Jerry
  • Tel:18017448610
  • DateTime:2019/1/13 14:03

==================================

==================================

  • Name:Jerry
  • DateTime:2019/5/6 13:16
  • Desc:

==================================

Index

Constants

View Source
const (
	TimeLayout string = "2006-01-02 15:04:05"
	DateLayout string = "2006-01-02"

	//支付类型
	TradeType_Mini   = "JSAPI"
	TradeType_JsApi  = "JSAPI"
	TradeType_App    = "APP"
	TradeType_H5     = "MWEB"
	TradeType_Native = "NATIVE"

	//签名方式
	SignType_MD5         = "MD5"
	SignType_HMAC_SHA256 = "HMAC-SHA256"

	//Debug数据
	ApiKey    = "GFDS8j98rewnmgl45wHTt980jg543wmg"
	AppID     = "wxdaa2ab9ef87b5497"
	APPSecret = "65f42f625a788ed52f6e2e159304879c"
	MchID     = "1368139502"
	MchID2    = "1526665601"
	OpenID    = "o0Df70H2Q0fY8JXh1aFPIRyOBgu8"
)
View Source
const (
	SUCCESS = "SUCCESS"
	FAIL    = "FAIL"
)

Variables

This section is empty.

Functions

func DecryptOpenDataToStruct added in v1.0.7

func DecryptOpenDataToStruct(encryptedData, iv, sessionKey string, beanPtr interface{}) (err error)

解密开放数据

encryptedData:包括敏感数据在内的完整用户信息的加密数据
iv:加密算法的初始向量
sessionKey:会话密钥
beanPtr:需要解析到的结构体指针

func Float32ToString

func Float32ToString(floatNum float32, prec ...int) (floatStr string)

Float32转字符串

floatNum:float32数字
prec:精度位数(不传则默认float数字精度)

func Float64ToString

func Float64ToString(floatNum float64, prec ...int) (floatStr string)

Float64转字符串

floatNum:float64数字
prec:精度位数(不传则默认float数字精度)

func FormatAliPayPublicKey added in v1.1.1

func FormatAliPayPublicKey(publickKey string) (pKey string)

格式化秘钥

func FormatAliPayURLParam added in v1.1.1

func FormatAliPayURLParam(body BodyMap) (urlParam string)

格式化请求URL参数

func FormatDate

func FormatDate(dateStr string) (formatDate string)

格式化

func FormatDateTime

func FormatDateTime(timeStr string) (formatTime string)

格式化Datetime

func FormatPrivateKey added in v1.1.1

func FormatPrivateKey(privateKey string) (pKey string)

格式化秘钥

func GetAppPaySign added in v1.1.0

func GetAppPaySign(appid, partnerid, noncestr, prepayid, signType, timestamp, apiKey string) (paySign string)

APP支付,统一下单获取支付参数后,再次计算APP支付所需要的的sign

signType:此处签名方式,务必与统一下单时用的签名方式一致

func GetH5PaySign added in v1.0.5

func GetH5PaySign(appId, nonceStr, prepayId, signType, timeStamp, apiKey string) (paySign string)

JSAPI支付,统一下单获取支付参数后,再次计算出微信内H5支付需要用的paySign

func GetMiniPaySign

func GetMiniPaySign(appId, nonceStr, prepayId, signType, timeStamp, apiKey string) (paySign string)

JSAPI支付,统一下单获取支付参数后,再次计算出小程序用的paySign

func GetRandomString

func GetRandomString(length int) string

获取随机字符串

length:字符串长度

func HttpAgent added in v1.0.6

func HttpAgent() (agent *gorequest.SuperAgent)

func Int2String

func Int2String(intNum int) (intStr string)

Int转字符串

func Int642String

func Int642String(intNum int64) (int64Str string)

Int64转字符串

func NewAliPayClient added in v1.1.1

func NewAliPayClient(appId, privateKey string, isProd bool) (client *aliPayClient)

初始化支付宝客户端

appId:应用ID
privateKey:应用私钥
isProd:是否是正式环境

func NewWeChatClient

func NewWeChatClient(appId, mchId, apiKey string, isProd bool) (client *weChatClient)

初始化微信客户端 ok

appId:应用ID
MchID:商户ID
apiKey:API秘钥值
isProd:是否是正式环境

func PKCS7UnPadding added in v1.0.7

func PKCS7UnPadding(plainText []byte) []byte

解密填充模式(去除补全码) PKCS7UnPadding 解密时,需要在最后面去掉加密时添加的填充byte

func ParseDateTime

func ParseDateTime(timeStr string) (datetime time.Time)

解析时间

func String2Float

func String2Float(floatStr string) (floatNum float64)

字符串转Float

func String2Int

func String2Int(intStr string) (intNum int)

字符串转Int

func String2Int64

func String2Int64(intStr string) (int64Num int64)

字符串转Int64

func VerifyPayResultSign added in v1.0.9

func VerifyPayResultSign(apiKey string, signType string, notifyRsp *WeChatNotifyRequest) (ok bool, sign string)

支付通知的签名验证和参数签名后的Sign

apiKey:API秘钥值
signType:签名类型 MD5 或 HMAC-SHA256(默认请填写 MD5)
notifyRsp:利用 gopay.ParseNotifyResult() 得到的结构体
返回参数ok:是否验证通过
返回参数sign:根据参数计算的sign值,非微信返回参数中的Sign

Types

type AccessToken added in v1.0.7

type AccessToken struct {
	AccessToken string `json:"access_token"` //获取到的凭证
	ExpiresIn   int    `json:"expires_in"`   //SessionKey超时时间(秒)
	Errcode     int    `json:"errcode"`      //错误码
	Errmsg      string `json:"errmsg"`       //错误信息
}

func GetAccessToken added in v1.0.6

func GetAccessToken(appId, appSecret string) (accessToken *AccessToken, err error)

获取小程序全局唯一后台接口调用凭据(AccessToken:157字符)

appId:APPID
appSecret:AppSecret

type AliPayAppInfo added in v1.1.1

type AliPayAppInfo struct {
	Code            string `json:"code"`
	Msg             string `json:"msg"`
	SubCode         string `json:"sub_code"`
	SubMsg          string `json:"sub_msg"`
	OutTradeNo      string `json:"out_trade_no"`
	TradeNo         string `json:"trade_no"`
	TotalAmount     string `json:"total_amount"`
	SellerId        string `json:"seller_id"`
	MerchantOrderNo string `json:"merchant_order_no"`
}

type AliPayTradePayAppResponse added in v1.1.1

type AliPayTradePayAppResponse struct {
	AlipayTradeAppPayResponse AliPayAppInfo `json:"alipay_trade_app_pay_response"`
	Sign                      string        `json:"sign"`
}

type BodyMap

type BodyMap map[string]interface{}

func (BodyMap) Get

func (bm BodyMap) Get(key string) string

获取参数

func (BodyMap) Remove

func (bm BodyMap) Remove(key string)

删除参数

func (BodyMap) Set

func (bm BodyMap) Set(key string, value interface{})

设置参数

type Code2SessionRsp added in v1.0.6

type Code2SessionRsp struct {
	SessionKey string `json:"session_key"` //会话密钥
	ExpiresIn  int    `json:"expires_in"`  //SessionKey超时时间(秒)
	Openid     string `json:"openid"`      //用户唯一标识
	Unionid    string `json:"unionid"`     //用户在开放平台的唯一标识符
	Errcode    int    `json:"errcode"`     //错误码
	Errmsg     string `json:"errmsg"`      //错误信息
}

func Code2Session added in v1.0.6

func Code2Session(appId, appSecret, wxCode string) (sessionRsp *Code2SessionRsp, err error)

获取微信用户的OpenId、SessionKey、UnionId

appId:APPID
appSecret:AppSecret
wxCode:小程序调用wx.login 获取的code

type PaidUnionId added in v1.0.7

type PaidUnionId struct {
	Unionid string `json:"unionid"` //用户在开放平台的唯一标识符
	Errcode int    `json:"errcode"` //错误码
	Errmsg  string `json:"errmsg"`  //错误信息
}

func GetPaidUnionId added in v1.0.6

func GetPaidUnionId(accessToken, openId, transactionId string) (unionId *PaidUnionId, err error)

用户支付完成后,获取该用户的 UnionId,无需用户授权。

accessToken:接口调用凭据
openId:用户的OpenID
transactionId:微信支付订单号

type ReturnMessage

type ReturnMessage struct {
	ReturnCode string `json:"return_code"`
	ReturnMsg  string `json:"return_msg"`
}

type WeChatCloseOrderResponse

type WeChatCloseOrderResponse struct {
	ReturnCode string `xml:"return_code"`
	ReturnMsg  string `xml:"return_msg"`
	Appid      string `xml:"appid"`
	MchId      string `xml:"mch_id"`
	DeviceInfo string `xml:"device_info"`
	NonceStr   string `xml:"nonce_str"`
	Sign       string `xml:"sign"`
	ResultCode string `xml:"result_code"`
	ErrCode    string `xml:"err_code"`
	ErrCodeDes string `xml:"err_code_des"`
}

type WeChatMicropayResponse

type WeChatMicropayResponse struct {
	ReturnCode         string `xml:"return_code"`
	ReturnMsg          string `xml:"return_msg"`
	Appid              string `xml:"appid"`
	MchId              string `xml:"mch_id"`
	DeviceInfo         string `xml:"device_info"`
	NonceStr           string `xml:"nonce_str"`
	Sign               string `xml:"sign"`
	ResultCode         string `xml:"result_code"`
	ErrCode            string `xml:"err_code"`
	ErrCodeDes         string `xml:"err_code_des"`
	Openid             string `xml:"openid"`
	IsSubscribe        string `xml:"is_subscribe"`
	TradeType          string `xml:"trade_type"`
	BankType           string `xml:"bank_type"`
	FeeType            string `xml:"fee_type"`
	TotalFee           int    `xml:"total_fee"`
	SettlementTotalFee int    `xml:"settlement_total_fee"`
	CouponFee          int    `xml:"coupon_fee"`
	CashFeeType        string `xml:"cash_fee_type"`
	CashFee            int    `xml:"cash_fee"`
	TransactionId      string `xml:"transaction_id"`
	OutTradeNo         string `xml:"out_trade_no"`
	Attach             string `xml:"attach"`
	TimeEnd            string `xml:"time_end"`
	PromotionDetail    string `xml:"promotion_detail"`
}

type WeChatNotifyRequest

type WeChatNotifyRequest struct {
	ReturnCode         string `xml:"return_code"`
	ReturnMsg          string `xml:"return_msg"`
	ResultCode         string `xml:"result_code"`
	ErrCode            string `xml:"err_code"`
	ErrCodeDes         string `xml:"err_code_des"`
	Appid              string `xml:"appid"`
	MchId              string `xml:"mch_id"`
	DeviceInfo         string `xml:"device_info"`
	NonceStr           string `xml:"nonce_str"`
	Sign               string `xml:"sign"`
	SignType           string `xml:"sign_type"`
	Openid             string `xml:"openid"`
	IsSubscribe        string `xml:"is_subscribe"`
	TradeType          string `xml:"trade_type"`
	BankType           string `xml:"bank_type"`
	TotalFee           int    `xml:"total_fee"`
	SettlementTotalFee int    `xml:"settlement_total_fee"`
	FeeType            string `xml:"fee_type"`
	CashFee            int    `xml:"cash_fee"`
	CashFeeType        string `xml:"cash_fee_type"`
	CouponFee          int    `xml:"coupon_fee"`
	CouponCount        int    `xml:"coupon_count"`
	CouponType0        string `xml:"coupon_type_0"`
	CouponId0          string `xml:"coupon_id_0"`
	CouponFee0         int    `xml:"coupon_fee_0"`
	TransactionId      string `xml:"transaction_id"`
	OutTradeNo         string `xml:"out_trade_no"`
	Attach             string `xml:"attach"`
	TimeEnd            string `xml:"time_end"`
}

func ParseNotifyResult

func ParseNotifyResult(req *http.Request) (notifyRsp *WeChatNotifyRequest, err error)

解析支付完成后的回调信息

type WeChatNotifyResponse

type WeChatNotifyResponse struct {
	ReturnCode string `xml:"return_code"`
	ReturnMsg  string `xml:"return_msg"`
}

func (*WeChatNotifyResponse) ToXmlString

func (this *WeChatNotifyResponse) ToXmlString() (xmlStr string)

返回数据给微信

type WeChatQueryOrderResponse

type WeChatQueryOrderResponse struct {
	ReturnCode         string `xml:"return_code"`
	ReturnMsg          string `xml:"return_msg"`
	Appid              string `xml:"appid"`
	MchId              string `xml:"mch_id"`
	NonceStr           string `xml:"nonce_str"`
	Sign               string `xml:"sign"`
	ResultCode         string `xml:"result_code"`
	ErrCode            string `xml:"err_code"`
	ErrCodeDes         string `xml:"err_code_des"`
	DeviceInfo         string `xml:"device_info"`
	Openid             string `xml:"openid"`
	IsSubscribe        string `xml:"is_subscribe"`
	TradeType          string `xml:"trade_type"`
	TradeState         string `xml:"trade_state"`
	BankType           string `xml:"bank_type"`
	TotalFee           int    `xml:"total_fee"`
	SettlementTotalFee int    `xml:"settlement_total_fee"`
	FeeType            string `xml:"fee_type"`
	CashFee            int    `xml:"cash_fee"`
	CashFeeType        string `xml:"cash_fee_type"`
	CouponFee          int    `xml:"coupon_fee"`
	CouponCount        int    `xml:"coupon_count"`
	CouponType0        string `xml:"coupon_type_0"`
	CouponId0          string `xml:"coupon_id_0"`
	CouponFee0         int    `xml:"coupon_fee_0"`
	TransactionId      string `xml:"transaction_id"`
	OutTradeNo         string `xml:"out_trade_no"`
	Attach             string `xml:"attach"`
	TimeEnd            string `xml:"time_end"`
	TradeStateDesc     string `xml:"trade_state_desc"`
}

type WeChatQueryRefundResponse

type WeChatQueryRefundResponse struct {
	ReturnCode           string `xml:"return_code"`
	ReturnMsg            string `xml:"return_msg"`
	ResultCode           string `xml:"result_code"`
	ErrCode              string `xml:"err_code"`
	ErrCodeDes           string `xml:"err_code_des"`
	Appid                string `xml:"appid"`
	MchId                string `xml:"mch_id"`
	NonceStr             string `xml:"nonce_str"`
	Sign                 string `xml:"sign"`
	TotalRefundCount     int    `xml:"total_refund_count"`
	TransactionId        string `xml:"transaction_id"`
	OutTradeNo           string `xml:"out_trade_no"`
	TotalFee             int    `xml:"total_fee"`
	SettlementTotalFee   int    `xml:"settlement_total_fee"`
	FeeType              string `xml:"fee_type"`
	CashFee              int    `xml:"cash_fee"`
	RefundCount          int    `xml:"refund_count"`
	OutRefundNo0         string `xml:"out_refund_no_0"`
	RefundId0            string `xml:"refund_id_0"`
	RefundChannel0       string `xml:"refund_channel_0"`
	RefundFee0           int    `xml:"refund_fee_0"`
	SettlementRefundFee0 int    `xml:"settlement_refund_fee_0"`
	CouponType00         string `xml:"coupon_type_0_0"`
	CouponRefundFee0     int    `xml:"coupon_refund_fee_0"`
	CouponRefundCount0   int    `xml:"coupon_refund_count_0"`
	CouponRefundId00     string `xml:"coupon_refund_id_0_0"`
	CouponRefundFee00    int    `xml:"coupon_refund_fee_0_0"`
	RefundStatus0        string `xml:"refund_status_0"`
	RefundAccount0       string `xml:"refund_account_0"`
	RefundRecvAccout0    string `xml:"refund_recv_accout_0"`
	RefundSuccessTime0   string `xml:"refund_success_time_0"`
}

type WeChatRefundResponse

type WeChatRefundResponse struct {
	ReturnCode          string `xml:"return_code"`
	ReturnMsg           string `xml:"return_msg"`
	ResultCode          string `xml:"result_code"`
	ErrCode             string `xml:"err_code"`
	ErrCodeDes          string `xml:"err_code_des"`
	Appid               string `xml:"appid"`
	MchId               string `xml:"mch_id"`
	NonceStr            string `xml:"nonce_str"`
	Sign                string `xml:"sign"`
	TransactionId       string `xml:"transaction_id"`
	OutTradeNo          string `xml:"out_trade_no"`
	OutRefundNo         string `xml:"out_refund_no"`
	RefundId            string `xml:"refund_id"`
	RefundFee           int    `xml:"refund_fee"`
	SettlementRefundFee int    `xml:"settlement_refund_fee"`
	TotalFee            int    `xml:"total_fee"`
	SettlementTotalFee  int    `xml:"settlement_total_fee"`
	FeeType             string `xml:"fee_type"`
	CashFee             int    `xml:"cash_fee"`
	CashFeeType         string `xml:"cash_fee_type"`
	CashRefundFee       int    `xml:"cash_refund_fee"`
	CouponType0         string `xml:"coupon_type_0"`
	CouponRefundFee     int    `xml:"coupon_refund_fee"`
	CouponRefundFee0    int    `xml:"coupon_refund_fee_0"`
	CouponRefundCount   int    `xml:"coupon_refund_count"`
	CouponRefundId0     string `xml:"coupon_refund_id_0"`
}

type WeChatReverseResponse

type WeChatReverseResponse struct {
	ReturnCode string `xml:"return_code"`
	ReturnMsg  string `xml:"return_msg"`
	Appid      string `xml:"appid"`
	MchId      string `xml:"mch_id"`
	NonceStr   string `xml:"nonce_str"`
	Sign       string `xml:"sign"`
	ResultCode string `xml:"result_code"`
	ErrCode    string `xml:"err_code"`
	ErrCodeDes string `xml:"err_code_des"`
	Recall     string `xml:"recall"`
}

type WeChatUnifiedOrderResponse

type WeChatUnifiedOrderResponse struct {
	ReturnCode string `xml:"return_code"`
	ReturnMsg  string `xml:"return_msg"`
	Appid      string `xml:"appid"`
	MchId      string `xml:"mch_id"`
	DeviceInfo string `xml:"device_info"`
	NonceStr   string `xml:"nonce_str"`
	Sign       string `xml:"sign"`
	ResultCode string `xml:"result_code"`
	ErrCode    string `xml:"err_code"`
	ErrCodeDes string `xml:"err_code_des"`
	TradeType  string `xml:"trade_type"`
	PrepayId   string `xml:"prepay_id"`
	CodeUrl    string `xml:"code_url"`
	MwebUrl    string `xml:"mweb_url"`
}

type WeChatUserInfo added in v1.0.7

type WeChatUserInfo struct {
	Subscribe      int    `json:"subscribe"`       //用户是否订阅该公众号标识,值为0时,代表此用户没有关注该公众号,拉取不到其余信息。
	Openid         string `json:"openid"`          //用户唯一标识
	Nickname       string `json:"nickname"`        //用户的昵称
	Sex            int    `json:"sex"`             //用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
	Language       string `json:"language"`        //用户的语言,简体中文为zh_CN
	City           string `json:"city"`            //用户所在城市
	Province       string `json:"province"`        //用户所在省份
	Country        string `json:"country"`         //用户所在国家
	Headimgurl     string `json:"headimgurl"`      //用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。
	SubscribeTime  int    `json:"subscribe_time"`  //用户关注时间,为时间戳。如果用户曾多次关注,则取最后关注时间
	Unionid        string `json:"unionid"`         //只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。
	Remark         string `json:"remark"`          //公众号运营者对粉丝的备注,公众号运营者可在微信公众平台用户管理界面对粉丝添加备注
	Groupid        int    `json:"groupid"`         //用户所在的分组ID(兼容旧的用户分组接口)
	TagidList      []int  `json:"tagid_list"`      //用户被打上的标签ID列表
	SubscribeScene string `json:"subscribe_scene"` //返回用户关注的渠道来源,ADD_SCENE_SEARCH 公众号搜索,ADD_SCENE_ACCOUNT_MIGRATION 公众号迁移,ADD_SCENE_PROFILE_CARD 名片分享,ADD_SCENE_QR_CODE 扫描二维码,ADD_SCENEPROFILE LINK 图文页内名称点击,ADD_SCENE_PROFILE_ITEM 图文页右上角菜单,ADD_SCENE_PAID 支付后关注,ADD_SCENE_OTHERS 其他
	QrScene        int    `json:"qr_scene"`        //二维码扫码场景(开发者自定义)
	QrSceneStr     string `json:"qr_scene_str"`    //二维码扫码场景描述(开发者自定义)
	Errcode        int    `json:"errcode"`         //错误码
	Errmsg         string `json:"errmsg"`          //错误信息
}

func GetWeChatUserInfo added in v1.0.7

func GetWeChatUserInfo(accessToken, openId string, lang ...string) (userInfo *WeChatUserInfo, err error)

获取用户基本信息(UnionID机制)

accessToken:接口调用凭据
openId:用户的OpenID
lang:默认为 zh_CN ,可选填 zh_CN 简体,zh_TW 繁体,en 英语

type WeChatUserPhone added in v1.0.7

type WeChatUserPhone struct {
	PhoneNumber     string        `json:"phoneNumber"`
	PurePhoneNumber string        `json:"purePhoneNumber"`
	CountryCode     string        `json:"countryCode"`
	Watermark       watermarkInfo `json:"watermark"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL