{"id":13601506,"url":"https://github.com/smartwalle/alipay","last_synced_at":"2025-05-13T17:08:37.087Z","repository":{"id":37663956,"uuid":"79306723","full_name":"smartwalle/alipay","owner":"smartwalle","description":"支付宝 AliPay SDK for Go, 集成简单，功能完善，持续更新，支持公钥证书和普通公钥进行签名和验签，支持文件上传和接口内容加密。","archived":false,"fork":false,"pushed_at":"2025-03-30T13:08:37.000Z","size":675,"stargazers_count":1949,"open_issues_count":13,"forks_count":434,"subscribers_count":39,"default_branch":"master","last_synced_at":"2025-04-24T02:01:45.346Z","etag":null,"topics":["alipay","alipaysdk","go","golang","pay"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/smartwalle.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"security_risk_complaint.go","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2017-01-18T05:28:22.000Z","updated_at":"2025-04-19T12:35:51.000Z","dependencies_parsed_at":"2023-09-22T16:41:49.094Z","dependency_job_id":"69d6b145-0099-4439-b1b1-011ce205be4a","html_url":"https://github.com/smartwalle/alipay","commit_stats":{"total_commits":368,"total_committers":38,"mean_commits":9.68421052631579,"dds":"0.15760869565217395","last_synced_commit":"62fa92c8377ae8a61ed1983149005e8625bd51e3"},"previous_names":[],"tags_count":74,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/smartwalle%2Falipay","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/smartwalle%2Falipay/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/smartwalle%2Falipay/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/smartwalle%2Falipay/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/smartwalle","download_url":"https://codeload.github.com/smartwalle/alipay/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253990467,"owners_count":21995774,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["alipay","alipaysdk","go","golang","pay"],"created_at":"2024-08-01T18:01:03.761Z","updated_at":"2025-05-13T17:08:32.074Z","avatar_url":"https://github.com/smartwalle.png","language":"Go","funding_links":[],"categories":["Misc","开源类库","Go","Open source library","Repositories"],"sub_categories":["SDK"],"readme":"AliPay SDK for Golang\n\n## 鸣谢\n\n[![jetbrains.svg](jetbrains.svg)](https://www.jetbrains.com/?from=AliPay%20SDK%20for%20Go)\n\n## 安装\n\n#### 启用 Go module\n\n```go\ngo get github.com/smartwalle/alipay/v3\n```\n\n```go\nimport github.com/smartwalle/alipay/v3\n```\n\n#### 未启用 Go module\n\n```go\ngo get github.com/smartwalle/alipay\n```\n\n```go\nimport github.com/smartwalle/alipay\n```\n\n## 帮助\n\n在集成的过程中有遇到问题，欢迎加 QQ 群 203357977 讨论。\n\n## 其它支付\n\n苹果支付 [https://github.com/smartwalle/apple](https://github.com/smartwalle/apple)\n\nPayPal [https://github.com/smartwalle/paypal](https://github.com/smartwalle/paypal)\n\n银联支付 [https://github.com/smartwalle/unionpay](https://github.com/smartwalle/unionpay)\n\n## 关于各分支（版本)\n\n* v1 - 最老的版本，实现了完整的支付功能，目前已停止更新维护；\n* v2 - 在 v1 的基础上进行了一些优化和规范调整，目前已停止更新维护；\n* v3 - 支持**公钥证书**和**普通公钥**进行签名验证，详情可以参考 [https://docs.open.alipay.com/291/105974/](https://docs.open.alipay.com/291/105974/) 和 [https://docs.open.alipay.com/291/105971/](https://docs.open.alipay.com/291/105971/)，为目前主要维护分支；\n* master - 和主要维护分支同步；\n\n**推荐使用 v3 版本**\n\n## v3 版本如何初始化\n\n**下面用到的 privateKey 需要特别注意一下，如果是通过“支付宝开发平台开发助手”创建的CSR文件，在 CSR 文件所在的目录下会生成相应的私钥文件，我们需要使用该私钥进行签名。**\n\n```go\nvar client, err = alipay.New(appID, privateKey, isProduction)\n```\n\n#### 关于应用私钥 (privateKey)\n\n应用私钥是我们通过工具生成的私钥，调用支付宝接口的时候，我们需要使用该私钥对参数进行签名。\n\n#### 关于 alipay.New() 函数中的最后一个参数 isProduction\n\n支付宝提供了用于开发时测试的 sandbox 环境，对接的时候需要注意相关的 app id 和密钥是 sandbox 环境还是 production 环境的。如果是 sandbox 环境，本参数应该传 false，否则为 true。\n\n### 公钥证书模式\n\n如果采用公钥证书方式进行验证签名，需要调用以下几个方法加载证书信息，所有证书都是从支付宝创建的应用处下载，参考 [https://docs.open.alipay.com/291/105971/](https://docs.open.alipay.com/291/105971/) 和 [https://docs.open.alipay.com/291/105972/](https://docs.open.alipay.com/291/105972/)\n\n```go\nclient.LoadAppCertPublicKeyFromFile(\"/路径/appCertPublicKey_2017011104995404.crt\") // 加载应用公钥证书\nclient.LoadAliPayRootCertFromFile(\"/路径/alipayRootCert.crt\")                // 加载支付宝根证书\nclient.LoadAlipayCertPublicKeyFromFile(\"/路径/alipayCertPublicKey_RSA2.crt\") // 加载支付宝公钥证书\n```\n\n### 普通公钥模式\n\n需要注意此处用到的公钥是**支付宝公钥**，不是我们用工具生成的应用公钥。\n\n[如何查看支付宝公钥？](https://opendocs.alipay.com/common/057aqe)\n\n```go\nclient.LoadAliPayPublicKey(\"aliPublicKey\")\n```\n\n特别注意：**公钥证书**和**普通公钥**不能同时存在，只能选择其中一种。\n\n### 接口内容加密\n\n详细内容访问 [https://opendocs.alipay.com/common/02mse3](https://opendocs.alipay.com/common/02mse3) 进行了解。\n\n如果需要开启该功能，只需调用一下 SetEncryptKey() 方法。\n\n```go\nclient.SetEncryptKey(\"key\")\n```\n\n如果不需要开启该功能，则不用调用该方法。\n\n### 签名验证\n\n内部已实现对支付宝返回的数据进行签名验证，详细信息请参考[自行实现验签](https://doc.open.alipay.com/docs/doc.htm?docType=1\u0026articleId=106120)。\n\n需要自行对签名验证的场景有 **同步回调(return_url)** 和 **异步通知(notify_url)** 的 HTTP 处理函数。\n\n#### 同步回调(return_url)\n\n发起支付(网页支付)的时候，如果有提供 ReturnURL 参数，那么支付成功之后，支付宝会将浏览器重定向到该 URL，并附带上相关的参数。\n\n```go\nvar p = alipay.TradeWapPay{}\np.ReturnURL = \"http://xxx/return\"\n```\n\n对支付宝提供的参数进行签名验证：\n\n```go\nhttp.HandleFunc(\"/return\", func (writer http.ResponseWriter, request *http.Request) {\nrequest.ParseForm()\nif err := client.VerifySign(request.Form); err != nil {\n// 如果 err 不为空，则表示验签失败\nfmt.Println(err)\nreturn\n}\n// 业务处理\n}\n```\n\n#### 异步通知(notify_url)\n\n有支付或者其它动作发生后，支付宝服务器会调用我们提供的 NotifyURL，并向其传递相关的信息。参考[手机网站支付结果异步通知](https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.XM5C4a\u0026treeId=203\u0026articleId=105286\u0026docType=1)。\n\n```go\nvar p = alipay.TradeWapPay{}\np.NotifyURL = \"http://xxx/return\"\n```\n\n解析通知并验证签名：\n\n```go\nhttp.HandleFunc(\"/notify\", func (writer http.ResponseWriter, request *http.Request) {\nrequest.ParseForm()\n\n// DecodeNotification 内部已调用 VerifySign 方法验证签名\nvar noti, err = client.DecodeNotification(request.Form)\nif err != nil {\n// 错误处理\nfmt.Println(err)\nreturn\n}\n// 业务处理\n// 如果通知消息没有问题，我们需要确认收到通知消息，不然支付宝后续会继续推送相同的消息\nalipay.ACKNotification(writer)\n})\n```\n\n#### 支持 RSA2 签名及验证\n\n采用 RSA2 签名，不再提供 RSA 的支持。\n\n#### 特别注意\n\n提供给支付宝的 NotifyURL 和 ReturnURL 最好不要附带任何参数，支付宝在生成签名信息的时候不会包含 URL 中的参数，而 VerifySign() 方法在验证签名的时候会将收到的所有参数一起验证。\n\n如果确实需要附带参数，可以在调用 VerifySign() 方法前，将附带的参数从 request.Form 中删除。\n\n## 已实现接口\n\n```\n中线(-)后面的名称是该接口在 Client 结构体中对应的方法名。\n```\n\n* **手机网站支付接口**\n\n  alipay.trade.wap.pay - **TradeWapPay()**\n\n* **电脑网站支付**\n\n  alipay.trade.page.pay - **TradePagePay()**\n\n* **统一收单线下交易查询**\n\n  alipay.trade.query - **TradeQuery()**\n\n* **统一收单交易支付接口**\n\n  alipay.trade.pay - **TradePay()**\n\n* **统一收单交易创建接口**\n\n  alipay.trade.create - **TradeCreate()**\n\n* **统一收单线下交易预创建**\n\n  alipay.trade.precreate - **TradePreCreate()**\n\n* **统一收单交易撤销接口**\n\n  alipay.trade.cancel - **TradeCancel()**\n\n* **统一收单交易关闭接口**\n\n  alipay.trade.close - **TradeClose()**\n\n* **统一收单交易退款接口**\n\n  alipay.trade.refund - **TradeRefund()**\n\n* **App 支付接口**\n\n  alipay.trade.app.pay - **TradeAppPay()**\n\n* **统一收单交易退款查询**\n\n  alipay.trade.fastpay.refund.query - **TradeFastpayRefundQuery()**\n\n* **支付宝订单信息同步接口**\n\n  alipay.trade.orderinfo.sync - **TradeOrderInfoSync()**\n\n* **单笔转账到支付宝账户接口**\n\n  alipay.fund.trans.toaccount.transfer - **FundTransToAccountTransfer()**\n\n* **查询转账订单接口**\n\n  alipay.fund.trans.order.query - **FundTransOrderQuery()**\n\n* **资金授权发码接口**\n\n  alipay.fund.auth.order.voucher.create - **FundAuthOrderVoucherCreate()**\n\n* **资金授权操作查询接口**\n\n  alipay.fund.auth.operation.detail.query - **FundAuthOperationDetailQuery()**\n\n* **资金授权撤销接口**\n\n  alipay.fund.auth.operation.cancel - **FundAuthOperationCancel()**\n\n* **资金授权解冻接口**\n\n  alipay.fund.auth.order.unfreeze - **FundAuthOrderUnfreeze()**\n\n* **资金授权冻结接口**\n\n  alipay.fund.auth.order.freeze - **FundAuthOrderFreeze()**\n\n* **线上资金授权冻结接口**\n\n  alipay.fund.auth.order.app.freeze - **FundAuthOrderAppFreeze()**\n\n* **查询对账单下载地址**\n\n  alipay.data.dataservice.bill.downloadurl.query - **BillDownloadURLQuery()**\n\n* **支付宝商家账户当前余额查询**\n\n  alipay.data.bill.balance.query - **BillBalanceQuery()**\n\n* **身份认证初始化服务**\n\n  alipay.user.certify.open.initialize - **UserCertifyOpenInitialize()**\n\n* **身份认证开始认证**\n\n  alipay.user.certify.open.certify - **UserCertifyOpenCertify()**\n\n* **身份认证记录查询**\n\n  alipay.user.certify.open.query - **UserCertifyOpenQuery()**\n\n* **用户信息授权(网站支付宝登录快速接入)**\n\n  生成授权链接 - **PublicAppAuthorize()**\n\n* **换取授权访问令牌**\n\n  alipay.system.oauth.token - **SystemOauthToken()**\n\n* **支付宝会员授权信息查询**\n\n  alipay.user.info.share - **UserInfoShare()**\n\n* **App支付宝登录**\n\n  com.alipay.account.auth - **AccountAuth()**\n\n* **支付宝个人协议页面签约**\n\n  alipay.user.agreement.page.sign - **AgreementPageSign()**\n\n* **支付宝个人代扣协议查询**\n\n  alipay.user.agreement.query - **AgreementQuery()**\n\n* **支付宝个人代扣协议解约**\n\n  alipay.user.agreement.unsign - **AgreementUnsign()**\n\n* **支单笔转账接口**\n\n  alipay.fund.trans.uni.transfer - **FundTransUniTransfer()**\n\n* **转账业务单据查询接口**\n\n  alipay.fund.trans.common.query - **FundTransCommonQuery()**\n\n* **支付宝资金账户资产查询接口**\n\n  alipay.fund.account.query - **FundAccountQuery()**\n\n* **小程序获取会员手机号数据解析**\n\n  my.getPhoneNumber - **DecodePhoneNumber()**\n\n## 集成流程\n\n从[支付宝开放平台](https://open.alipay.com/)申请创建相关的应用，使用自己的支付宝账号登录即可。\n\n### 沙箱环境\n\n支付宝开放平台为每一个应用提供了沙箱环境，供开发人员开发测试使用。\n\n沙箱环境是独立的，每一个应用都会有一个商家账号和买家账号。\n\n#### 沙箱环境网关地址\n\n沙箱环境目前有两个网关地址：\n\n* 老地址: [https://openapi.alipaydev.com/gateway.do](https://openapi.alipaydev.com/gateway.do)\n* 新地址: [https://openapi-sandbox.dl.alipaydev.com/gateway.do](https://openapi-sandbox.dl.alipaydev.com/gateway.do)\n\n大家在对接的时候一定要确认清楚是新地址还是老地址。\n\n本 SDK 目前默认使用的是 **【新地址】**，如果需要使用老地址，只需要在初始化的时候通过 alipay.WithPastSandboxGateway() 指定即可。\n\n```go\nalipay.New(appId, privateKey, isProduction, alipay.WithPastSandboxGateway())\n```\n\n### 应用信息配置\n\n参考[官网文档](https://docs.open.alipay.com/200/105894) 进行应用的配置。\n\n本 SDK 中的签名方法默认为 **RSA2**，采用支付宝提供的 [RSA签名\u0026验签工具](https://docs.open.alipay.com/291/105971) 生成秘钥时，秘钥长度推荐 **2048**。所以在支付宝管理后台请注意配置 **RSA2(SHA256)密钥**。\n\n生成秘钥对之后，将公钥提供给支付宝（通过支付宝后台上传）对我们请求的数据进行签名验证，我们的代码中将使用私钥对请求数据签名。\n\n请参考 [如何生成 RSA 密钥](https://docs.open.alipay.com/291/105971)。\n\n### 创建 Wap 支付\n\n```go\nvar privateKey = \"xxx\" // 必须，上一步中使用 RSA签名验签工具 生成的私钥\nvar client, err = alipay.New(appId, privateKey, false)\nif err != nil {\nfmt.Println(err)\nreturn\n}\n\n// 加载应用公钥证书\nif err = client.LoadAppCertPublicKeyFromFile(\"appCertPublicKey_2017011104995404.crt\"); err != nil {\n// 错误处理\n}\n\n// 加载支付宝根证书\nif err = client.LoadAliPayRootCertFromFile(\"alipayRootCert.crt\"); err != nil {\n// 错误处理\n}\n\n// 加载支付宝公钥证书\nif err = client.LoadAlipayCertPublicKeyFromFile(\"alipayCertPublicKey_RSA2.crt\"); err != nil {\n// 错误处理\n}\n\n// 加载内容密钥，可选\nif err = client.SetEncryptKey(\"FtVd5SgrsUzYQRAPBmejHQ==\"); err != nil {\n// 错误处理\n}\n\nvar p = alipay.TradeWapPay{}\np.NotifyURL = \"http://xxx\"\np.ReturnURL = \"http://xxx\"\np.Subject = \"标题\"\np.OutTradeNo = \"传递一个唯一单号\"\np.TotalAmount = \"10.00\"\np.ProductCode = \"QUICK_WAP_WAY\"\n\nvar url, err = client.TradeWapPay(p)\nif err != nil {\nfmt.Println(err)\n}\n\n// 这个 payURL 即是用于打开支付宝支付页面的 URL，可将输出的内容复制，到浏览器中访问该 URL 即可打开支付页面。\nvar payURL = url.String()\nfmt.Println(payURL)\n```\n\n## 自定义请求\n\n对于本库还未实现接口，可使用 alipay.Payload 结构体作为参数调用 alipay.Client 结构体的 Request() 方法。\n\n```go\nvar p = alipay.NewPayload(\"这里是接口名称，如：alipay.trade.query\")\n// 添加公共请求参数，如：app_auth_token\np.AddParam(\"key\", \"value\")\n// 添加请求参数(业务相关)\np.AddBizField(\"key\", \"value\")\n\n// 应用场景一：需要向支付宝服务器发起网络请求，如交易查询接口（alipay.trade.query）\nvar result map[string]interface{}\n// result 也可以为结构体，可参照 alipay.TradeQueryRsp\nvar err = client.Request(p, \u0026result)\nif err != nil {\n...\n}\n\n// 应用场景二：只需要生成 URL，如网页支付（alipay.trade.page.pay）\nvar url, err = clietn.BuildURL(p)\n...\n\n// 应用场景三：只需要对参数进行签名，如 App 支付（alipay.trade.app.pay）\nvar s, err = client.EncodeParam(p)\n...\n```\n\n[更多信息](https://github.com/smartwalle/alipay/blob/master/trade_test.go#L104)\n\n## 文件上传\n\n使用 **自定义请求** 实现 [alipay.open.file.upload(支付宝文件上传接口)](https://opendocs.alipay.com/mini/05snwo) 功能，需要注意本接口是小程序应用的功能，需要在小程序应用中开启 **搜素直达** 才能正常使用。\n\n```go\nvar p = alipay.NewPayload(\"alipay.open.file.upload\")\np.Encrypt = false // 文件上传不支持接口内容加密\n\n// 设置参数\np.AddParam(\"biz_code\", \"content_creation\")\n\n// 添加文件\np.AddFilePath(\"file_content\", \"a.jpg\", \"path/a.jpg\")\n// 或者\np.AddFileObject(\"file_content\", \"a.jpg\", io.Reader)\n\nvar result map[string]interface{}\nvar err = client.Request(p, \u0026result)\n```\n\n## 链路跟踪\n\n```go\n// HTTP客户端\nhttpClient := \u0026http.Client{\n    Timeout: 30 * time.Second,\n    Transport: otelhttp.NewTransport(\n        http.DefaultTransport,\n        otelhttp.WithSpanNameFormatter(func(operation string, r *http.Request) string {\n            return r.Method + \" \" + r.URL.Path\n        }),\n    ),\n}\n\n// 初始化支付宝客户端\nclient, err := alipay.New(appId, privateKey, false, alipay.WithHTTPClient(httpClient))\nif err != nil {\n    fmt.Println(err)\n}\n```\n\n## 示例\n\n[网页支付](https://github.com/smartwalle/alipay/blob/master/examples/main.go)\n\n## 感谢你的支持\n\n如果对你有帮助，请我喝杯咖啡吧！\n\n![支付宝](https://i.imgs.ovh/2023/12/08/fMYl5.jpeg)\n![微信](https://i.imgs.ovh/2023/12/08/fMdbs.jpeg)\n\n## License\n\nThis project is licensed under the MIT License.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsmartwalle%2Falipay","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsmartwalle%2Falipay","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsmartwalle%2Falipay/lists"}