alipay

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2023 License: Apache-2.0 Imports: 29 Imported by: 0

README

alipay-go

golang GitHub release pkg.go.dev Apache 2.0 license

支付宝 Go SDK

go get -u github.com/shenghui0779/alipay-go
使用说明
  • 发送HTTP请求,使用 Client.Do(...)
  • 以下场景使用 Action.Encode(...)
    • alipay.trade.app.pay(app支付接口2.0)
    • alipay.fund.auth.order.app.freeze(线上资金授权冻结接口)
  • 以下场景使用 Client.PageExecute(...)
    • alipay.trade.wap.pay(手机网站支付接口2.0)
    • alipay.trade.page.pay(统一收单下单并支付页面接口)
    • alipay.user.certify.open.certify(身份认证开始认证)
  • 验证回调通知,使用 Client.VerifyNotify(...)
  • JSON结果均以 gjson.Result 返回,理论上支持所有 JSON API
  • 解析加密数据,如:授权的用户信息和手机号,使用 Client.DecodeEncryptData(...)

Documentation

Index

Constants

View Source
const (
	HeaderAccept         = "Accept"
	HeaderAuthorization  = "Authorization"
	HeaderContentType    = "Content-Type"
	HeaderMethodOverride = "x-http-method-override"
	HeaderRequestID      = "alipay-request-id"
	HeaderTraceID        = "alipay-trace-id"
	HeaderRootCertSN     = "alipay-root-cert-sn"
	HeaderNonce          = "alipay-nonce"
	HeaderTimestamp      = "alipay-timestamp"
	HeaderEncryptType    = "alipay-encrypt-type"
	HeaderAppAuthToken   = "alipay-app-auth-token"
	HeaderSignature      = "alipay-signature"
)
View Source
const (
	ContentForm = "application/x-www-form-urlencoded"
	ContentJSON = "application/json;charset=utf-8"
	ContentText = "text/plain;charset=utf-8"
)
View Source
const CodeOK = "10000" // API请求成功

Variables

This section is empty.

Functions

func AESDecryptCBC added in v1.0.3

func AESDecryptCBC(key, data []byte) ([]byte, error)

AESDecryptCBC AES-CBC 解密

func AESEncryptCBC added in v1.0.3

func AESEncryptCBC(key, data []byte) ([]byte, error)

AESEncryptCBC AES-CBC 加密

func HeaderEncode

func HeaderEncode(h http.Header) string

func LoadCertFromPfxFile

func LoadCertFromPfxFile(filename, password string) (tls.Certificate, error)

LoadCertFromPfxFile 通过pfx(p12)证书文件生成TLS证书 注意:证书需采用「TripleDES-SHA1」加密方式

func Nonce

func Nonce(size uint) string

Nonce 生成指定长度的随机串 (最好是偶数)

Types

type APIResult

type APIResult struct {
	Code int // HTTP状态码
	Body gjson.Result
}

APIResult API结果 (支付v3)

type Action

type Action struct {
	// contains filtered or unexported fields
}

func NewAction

func NewAction(method string, options ...ActionOption) *Action

NewAction 生成Action

func (*Action) Encode

func (a *Action) Encode(c *Client) (string, error)

Encode 签名并生成请求Body

func (*Action) RespKey

func (a *Action) RespKey() string

RespKey 返回「method」对应的「xxx_response」

type ActionOption

type ActionOption func(a *Action)

ActionOption Action选项

func WithAppAuthToken

func WithAppAuthToken(token string) ActionOption

WithAppAuthToken 设置第三方应用授权Token

func WithAuthToken

func WithAuthToken(token string) ActionOption

WithAuthToken 用户授权令牌

func WithBizContent

func WithBizContent(data X) ActionOption

WithBizContent 设置「biz_content」参数

func WithEncrypt

func WithEncrypt() ActionOption

WithEncrypt 设置请求加密

func WithKVParam

func WithKVParam(k, v string) ActionOption

WithKVParam 设置其它非「biz_content」参数

func WithNotifyURL

func WithNotifyURL(url string) ActionOption

WithNotifyURL 设置异步回调通知URL

func WithOAuthCode

func WithOAuthCode(code string) ActionOption

WithOAuthCode 设置授权码(用授权码来换取授权令牌)

func WithRefreshToken

func WithRefreshToken(token string) ActionOption

WithRefreshToken 设置刷新令牌(用刷新令牌来换取一个新的授权令牌)

func WithReturnURL

func WithReturnURL(url string) ActionOption

WithReturnURL 设置支付成功跳转URL(HTTP/HTTPS开头字符串)

func WithScene

func WithScene(scene string) ActionOption

WithScene 设置业务场景描述

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client 支付宝客户端

func NewClient

func NewClient(appid, aesKey string, options ...Option) *Client

NewClient 生成支付宝客户端

func NewSandbox

func NewSandbox(appid, aesKey string, options ...Option) *Client

NewSandbox 生成支付宝沙箱环境

func (*Client) AppID

func (c *Client) AppID() string

AppID 返回appid

func (*Client) DecodeEncryptData

func (c *Client) DecodeEncryptData(hash crypto.Hash, data, sign string) ([]byte, error)

DecodeEncryptData 解析加密数据,如:授权的用户信息和手机号

func (*Client) Decrypt

func (c *Client) Decrypt(encryptData string) ([]byte, error)

Decrypt 数据解密

func (*Client) Do

func (c *Client) Do(ctx context.Context, method string, options ...ActionOption) (gjson.Result, error)

Do 向支付宝网关发送请求

func (*Client) Encrypt

func (c *Client) Encrypt(data string) (string, error)

Encrypt 数据加密

func (*Client) PageExecute

func (c *Client) PageExecute(method string, options ...ActionOption) (string, error)

PageExecute 致敬官方SDK

func (*Client) Upload

func (c *Client) Upload(ctx context.Context, method string, form UploadForm, options ...ActionOption) (gjson.Result, error)

Upload 文件上传,参考:https://opendocs.alipay.com/apis/api_4/alipay.merchant.item.file.upload

func (*Client) VerifyNotify

func (c *Client) VerifyNotify(form url.Values) (V, error)

VerifyNotify 验证回调通知表单数据

type ClientV3

type ClientV3 struct {
	// contains filtered or unexported fields
}

ClientV3 支付宝V3客户端(仅支持v3版本的接口可用)

func NewClientV3

func NewClientV3(appid, aesKey string, options ...V3Option) *ClientV3

NewClientV3 生成支付宝客户端V3

func NewSandboxV3

func NewSandboxV3(appid, aesKey string, options ...V3Option) *ClientV3

NewSandboxV3 生成支付宝沙箱V3

func (*ClientV3) AppID

func (c *ClientV3) AppID() string

AppID 返回appid

func (*ClientV3) Authorization

func (c *ClientV3) Authorization(method, path string, query url.Values, body []byte, header http.Header) (string, error)

Authorization 生成签名并返回 HTTP Authorization

func (*ClientV3) Decrypt

func (c *ClientV3) Decrypt(encryptData string) ([]byte, error)

Decrypt 数据解密

func (*ClientV3) Encrypt

func (c *ClientV3) Encrypt(data string) (string, error)

Encrypt 数据加密

func (*ClientV3) GetJSON

func (c *ClientV3) GetJSON(ctx context.Context, path string, query url.Values, options ...V3HeaderOption) (*APIResult, error)

GetJSON GET请求JSON数据

func (*ClientV3) PostEncrypt

func (c *ClientV3) PostEncrypt(ctx context.Context, path string, params X, options ...V3HeaderOption) (*APIResult, error)

PostJSON POST加密请求

func (*ClientV3) PostJSON

func (c *ClientV3) PostJSON(ctx context.Context, path string, params X, options ...V3HeaderOption) (*APIResult, error)

PostJSON POST请求JSON数据

func (*ClientV3) Upload

func (c *ClientV3) Upload(ctx context.Context, path string, form UploadForm, options ...V3HeaderOption) (*APIResult, error)

Upload 文件上传,参考:https://opendocs.alipay.com/open-v3/054oog?pathHash=7834d743

func (*ClientV3) Verify

func (c *ClientV3) Verify(header http.Header, body []byte) error

Verify 验证签名

type FormFileFunc

type FormFileFunc func(w io.Writer) error

FormFileFunc 将文件写入表单流

type GrantType

type GrantType string
const (
	OAuthCode    GrantType = "authorization_code"
	RefreshToken GrantType = "refresh_token"
)

type HTTPClient

type HTTPClient interface {
	// Do 发送HTTP请求
	// 注意:应该使用Context设置请求超时时间
	Do(ctx context.Context, method, reqURL string, body []byte, options ...HTTPOption) (*http.Response, error)

	// Upload 上传文件
	// 注意:应该使用Context设置请求超时时间
	Upload(ctx context.Context, reqURL string, form UploadForm, options ...HTTPOption) (*http.Response, error)
}

HTTPClient HTTP客户端

func NewDefaultHTTPClient

func NewDefaultHTTPClient() HTTPClient

NewDefaultHTTPClient 生成一个默认的HTTP客户端

func NewHTTPClient

func NewHTTPClient(cli *http.Client) HTTPClient

NewHTTPClient 通过官方 `http.Client` 生成一个HTTP客户端

type HTTPOption

type HTTPOption func(o *httpOptions)

HTTPOption HTTP请求选项

func HeaderToHttpOption

func HeaderToHttpOption(h http.Header) []HTTPOption

func WithHTTPClose

func WithHTTPClose() HTTPOption

WithHTTPClose 请求结束后关闭请求

func WithHTTPCookies

func WithHTTPCookies(cookies ...*http.Cookie) HTTPOption

WithHTTPCookies 设置HTTP请求Cookie

func WithHTTPHeader

func WithHTTPHeader(key string, vals ...string) HTTPOption

WithHTTPHeader 设置HTTP请求头

type Option

type Option func(c *Client)

Option 自定义设置项

func WithHttpCli

func WithHttpCli(cli *http.Client) Option

WithHttpCli 设置自定义 HTTP Client

func WithLogger

func WithLogger(f func(ctx context.Context, data map[string]string)) Option

WithLogger 设置日志记录

func WithPrivateKey

func WithPrivateKey(key *PrivateKey) Option

WithPrivateKey 设置商户RSA私钥

func WithPublicKey

func WithPublicKey(key *PublicKey) Option

WithPublicKey 设置平台RSA公钥

type PrivateKey

type PrivateKey struct {
	// contains filtered or unexported fields
}

PrivateKey RSA私钥

func NewPrivateKeyFromPemBlock

func NewPrivateKeyFromPemBlock(padding RSAPadding, pemBlock []byte) (*PrivateKey, error)

NewPrivateKeyFromPemBlock 通过PEM字节生成RSA私钥

func NewPrivateKeyFromPemFile

func NewPrivateKeyFromPemFile(padding RSAPadding, pemFile string) (*PrivateKey, error)

NewPrivateKeyFromPemFile 通过PEM文件生成RSA私钥

func NewPrivateKeyFromPfxFile

func NewPrivateKeyFromPfxFile(pfxFile, password string) (*PrivateKey, error)

NewPrivateKeyFromPfxFile 通过pfx(p12)证书生成RSA私钥 注意:证书需采用「TripleDES-SHA1」加密方式

func (*PrivateKey) Decrypt

func (pk *PrivateKey) Decrypt(cipherText []byte) ([]byte, error)

Decrypt RSA私钥 PKCS#1 v1.5 解密

func (*PrivateKey) DecryptOAEP

func (pk *PrivateKey) DecryptOAEP(hash crypto.Hash, cipherText []byte) ([]byte, error)

DecryptOAEP RSA私钥 PKCS#1 OAEP 解密

func (*PrivateKey) Sign

func (pk *PrivateKey) Sign(hash crypto.Hash, data []byte) ([]byte, error)

Sign RSA私钥签名

type PublicKey

type PublicKey struct {
	// contains filtered or unexported fields
}

PublicKey RSA公钥

func NewPublicKeyFromDerBlock

func NewPublicKeyFromDerBlock(pemBlock []byte) (*PublicKey, error)

NewPublicKeyFromDerBlock 通过DER字节生成RSA公钥 注意PEM格式: -----BEGIN CERTIFICATE----- | -----END CERTIFICATE----- DER转换命令: openssl x509 -inform der -in cert.cer -out cert.pem

func NewPublicKeyFromDerFile

func NewPublicKeyFromDerFile(pemFile string) (*PublicKey, error)

NewPublicKeyFromDerFile 通过DER证书生成RSA公钥 注意PEM格式: -----BEGIN CERTIFICATE----- | -----END CERTIFICATE----- DER转换命令: openssl x509 -inform der -in cert.cer -out cert.pem

func NewPublicKeyFromPemBlock

func NewPublicKeyFromPemBlock(padding RSAPadding, pemBlock []byte) (*PublicKey, error)

NewPublicKeyFromPemBlock 通过PEM字节生成RSA公钥

func NewPublicKeyFromPemFile

func NewPublicKeyFromPemFile(padding RSAPadding, pemFile string) (*PublicKey, error)

NewPublicKeyFromPemFile 通过PEM文件生成RSA公钥

func (*PublicKey) Encrypt

func (pk *PublicKey) Encrypt(plainText []byte) ([]byte, error)

Encrypt RSA公钥 PKCS#1 v1.5 加密

func (*PublicKey) EncryptOAEP

func (pk *PublicKey) EncryptOAEP(hash crypto.Hash, plainText []byte) ([]byte, error)

EncryptOAEP RSA公钥 PKCS#1 OAEP 加密

func (*PublicKey) Verify

func (pk *PublicKey) Verify(hash crypto.Hash, data, signature []byte) error

Verify RSA公钥验签

type RSAPadding added in v1.0.2

type RSAPadding int

RSAPadding RSA PEM 填充模式

const (
	RSA_PKCS1 RSAPadding = 1 // PKCS#1 (格式:`RSA PRIVATE KEY` 和 `RSA PUBLIC KEY`)
	RSA_PKCS8 RSAPadding = 8 // PKCS#8 (格式:`PRIVATE KEY` 和 `PUBLIC KEY`)
)

func FormatPKCS1PrivateKey

func FormatPKCS1PrivateKey(pemStr string) (RSAPadding, []byte)

FormatPKCS1PrivateKey 格式化支付宝应用私钥(PKCS#1)

func FormatPKCS1PublicKey

func FormatPKCS1PublicKey(pemStr string) (RSAPadding, []byte)

FormatPKCS1PublicKey 格式化支付宝应用公钥(PKCS#1)

func FormatPKCS8PrivateKey

func FormatPKCS8PrivateKey(pemStr string) (RSAPadding, []byte)

FormatPKCS8PrivateKey 格式化支付宝应用私钥(PKCS#8)

func FormatPKCS8PublicKey

func FormatPKCS8PublicKey(pemStr string) (RSAPadding, []byte)

FormatPKCS8PublicKey 格式化支付宝应用公钥(PKCS#8)

type ReqLog

type ReqLog struct {
	// contains filtered or unexported fields
}

ReqLog 请求日志

func NewReqLog

func NewReqLog(method, reqURL string) *ReqLog

NewReqLog 生成请求日志

func (*ReqLog) Do

func (l *ReqLog) Do(ctx context.Context, log func(ctx context.Context, data map[string]string))

Do 日志记录

func (*ReqLog) Set

func (l *ReqLog) Set(k, v string)

Set 设置日志K-V

func (*ReqLog) SetReqBody

func (l *ReqLog) SetReqBody(v string)

SetBody 设置请求Body

func (*ReqLog) SetReqHeader

func (l *ReqLog) SetReqHeader(h http.Header)

SetReqHeader 设置请求头

func (*ReqLog) SetRespBody

func (l *ReqLog) SetRespBody(v string)

SetResp 设置返回报文

func (*ReqLog) SetRespHeader

func (l *ReqLog) SetRespHeader(h http.Header)

SetRespHeader 设置返回头

func (*ReqLog) SetStatusCode

func (l *ReqLog) SetStatusCode(code int)

SetStatusCode 设置HTTP状态码

type UploadField

type UploadField func(form *uploadform)

UploadField 文件上传表单字段

func WithFormField

func WithFormField(name, value string) UploadField

WithFormField 设置表单普通字段

func WithFormFile

func WithFormFile(fieldname, filename string, fn FormFileFunc) UploadField

WithFormFile 设置表单文件字段

type UploadForm

type UploadForm interface {
	// Field 返回表单普通字段
	Field(name string) string

	// Write 将表单文件写入流
	Write(w *multipart.Writer) error
}

UploadForm HTTP文件上传表单

func NewUploadForm

func NewUploadForm(fields ...UploadField) UploadForm

NewUploadForm 生成一个文件上传表单

type V

type V map[string]string

V 用于处理 k-v 需要格式化的场景,如:签名

func (V) Del

func (v V) Del(key string)

Del 删除Key

func (V) Encode

func (v V) Encode(sym, sep string, options ...VEncOption) string

Encode 通过自定义的符号和分隔符按照key的ASCII码升序格式化为字符串。 例如:("=", "&") ---> bar=baz&foo=quux; 例如:(":", "#") ---> bar:baz#foo:quux;

func (V) Get

func (v V) Get(key string) string

Get 获取值

func (V) Has

func (v V) Has(key string) bool

Has 判断Key是否存在

func (V) Set

func (v V) Set(key, value string)

Set 设置 k-v

type V3HeaderOption

type V3HeaderOption func(h http.Header)

func WithV3AppAuthToken

func WithV3AppAuthToken(token string) V3HeaderOption

func WithV3MethodOverride

func WithV3MethodOverride(method string) V3HeaderOption

func WithV3RootCertSN

func WithV3RootCertSN(sn string) V3HeaderOption

type V3Option

type V3Option func(c *ClientV3)

V3Option 自定义设置项

func WithV3Client

func WithV3Client(cli *http.Client) V3Option

WithV3Client 设置自定义 HTTP Client

func WithV3Logger

func WithV3Logger(f func(ctx context.Context, data map[string]string)) V3Option

WithV3Logger 设置日志记录

func WithV3PrivateKey

func WithV3PrivateKey(key *PrivateKey) V3Option

WithV3PrivateKey 设置商户RSA私钥

func WithV3PublicKey

func WithV3PublicKey(key *PublicKey) V3Option

WithV3PublicKey 设置平台RSA公钥

type VEmptyMode added in v1.0.4

type VEmptyMode int

VEmptyMode 值为空时的Encode模式

const (
	EmptyDefault VEmptyMode = iota // 默认:bar=baz&foo=
	EmptyIgnore                    // 忽略:bar=baz
	EmptyOnlyKey                   // 仅保留Key:bar=baz&foo
)

type VEncOption

type VEncOption func(o *vEncOptions)

VEncOption V Encode 选项

func WithEmptyMode added in v1.0.4

func WithEmptyMode(mode VEmptyMode) VEncOption

WithEmptyMode 设置值为空时的Encode模式

func WithIgnoreKeys

func WithIgnoreKeys(keys ...string) VEncOption

WithIgnoreKeys 设置Encode时忽略的key

func WithKVEscape

func WithKVEscape() VEncOption

WithKVEscape 设置K-V是否需要QueryEscape

type X

type X map[string]any

X 类型别名

Jump to

Keyboard shortcuts

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