wechat

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: 34 Imported by: 0

README

wechat-go

golang GitHub release pkg.go.dev Apache 2.0 license

微信 Go SDK

go get -u github.com/shenghui0779/wechat-go

除支付(v2)外,JSON结果均以 gjson.Result 返回,理论上支持所有 JSON API

Documentation

Index

Constants

View Source
const (
	HeaderAccept                = "Accept"
	HeaderAuthorization         = "Authorization"
	HeaderContentType           = "Content-Type"
	HeaderRequestID             = "Request-ID"
	HeaderPayNonce              = "Wechatpay-Nonce"
	HeaderPayTimestamp          = "Wechatpay-Timestamp"
	HeaderPaySerial             = "Wechatpay-Serial"
	HeaderPaySignature          = "Wechatpay-Signature"
	HeaderMPAppID               = "Wechatmp-Appid"
	HeaderMPTimestamp           = "Wechatmp-TimeStamp"
	HeaderMPSerial              = "Wechatmp-Serial"
	HeaderMPSignature           = "Wechatmp-Signature"
	HeaderMPSerialDeprecated    = "Wechatmp-Serial-Deprecated"
	HeaderMPSignatureDeprecated = "Wechatmp-Signature-Deprecated"
)
View Source
const (
	ResultSuccess = "SUCCESS"
	ResultFail    = "FAIL"
	ResultNull    = "RESULT NULL" // 查询结果为空
)

支付v2返回结果

View Source
const (
	SystemError        = "SYSTEMERROR"           // 系统繁忙,请稍后再试
	ParamError         = "PARAM_ERROR"           // 参数错误
	SignError          = "SIGNERROR"             // 签名错误
	LackParams         = "LACK_PARAMS"           // 缺少参数
	NotUTF8            = "NOT_UTF8"              // 编码格式错误
	NoAuth             = "NOAUTH"                // 商户无权限
	NotFound           = "NOT_FOUND"             // 数据不存在
	NotEnough          = "NOTENOUGH"             // 余额不足
	NotSupportCard     = "NOTSUPORTCARD"         // 不支持的卡类型
	UserPaying         = "USERPAYING"            // 用户支付中,需要输入密码
	AppIDNotExist      = "APPID_NOT_EXIST"       // APPID不存在
	MchIDNotExist      = "MCHID_NOT_EXIST"       // MCHID不存在
	AppIDMchIDNotMatch = "APPID_MCHID_NOT_MATCH" // appid和mch_id不匹配
	AuthCodeExpire     = "AUTHCODEEXPIRE"        // 二维码已过期,请用户在微信上刷新后再试
	AuthCodeError      = "AUTH_CODE_ERROR"       // 付款码参数错误
	AuthCodeInvalid    = "AUTH_CODE_INVALID"     // 付款码检验错误
	BankError          = "BANKERROR"             // 银行系统异常
	OrderNotExist      = "ORDERNOTEXIST"         // 订单不存在
	OrderPaid          = "ORDERPAID"             // 订单已支付
	OrderClosed        = "ORDERCLOSED"           // 订单已关闭
	OrderReversed      = "ORDERREVERSED"         // 订单已撤销
	RefundNotExist     = "REFUNDNOTEXIST"        // 退款不存在
	BuyerMismatch      = "BUYER_MISMATCH"        // 支付账号错误
	OutTradeNoUsed     = "OUT_TRADE_NO_USED"     // 商户订单号重复
	XmlFormatError     = "XML_FORMAT_ERROR"      // XML格式错误
	RequestPostMethod  = "REQUIRE_POST_METHOD"   // 请使用post方法
	PostDataEmpty      = "POST_DATA_EMPTY"       // post数据为空
	InvalidRequest     = "INVALID_REQUEST"       // 无效请求
	TradeError         = "TRADE_ERROR"           // 交易错误
	URLFormatError     = "URLFORMATERROR"        // URL格式错误
)

支付v2错误码

View Source
const AccessToken = "access_token"
View Source
const ContentJSON = "application/json;charset=utf-8"

Variables

This section is empty.

Functions

func AESDecryptCBC added in v1.0.3

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

AESDecryptCBC AES-CBC 解密(pkcs#7)

func AESDecryptECB added in v1.0.3

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

AESDecryptECB AES-ECB 解密(pkcs#7)

func AESDecryptGCM added in v1.0.3

func AESDecryptGCM(key, nonce []byte, data, aad []byte) ([]byte, error)

AESDecryptGCM AES-GCM 解密 (NonceSize = 12 & TagSize = 16)

func DecodeBytesToUint32

func DecodeBytesToUint32(b []byte) uint32

DecodeBytesToUint32 从 4 字节的网络字节序里解析出整数 uint32

func EncodeUint32ToBytes

func EncodeUint32ToBytes(i uint32) []byte

EncodeUint32ToBytes 把整数 uint32 格式化成 4 字节的网络字节序

func EventDecrypt

func EventDecrypt(receiveID, encodingAESKey, cipherText string) ([]byte, error)

EventDecrypt 事件消息解密 [参考](https://developer.work.weixin.qq.com/document/path/90968)

func FormatVToXML

func FormatVToXML(vals V) ([]byte, error)

FormatVToXML format map to xml

func HMacSHA256

func HMacSHA256(key, str string) string

HMacSHA256 计算hmac-sha256值

func HeaderEncode

func HeaderEncode(h http.Header) string

func LoadCertFromPfxFile

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

LoadCertFromPfxFile 通过pfx(p12)证书文件生成TLS证书

func MD5

func MD5(s string) string

MD5 计算md5值

func MarshalNoEscapeHTML

func MarshalNoEscapeHTML(v interface{}) ([]byte, error)

MarshalNoEscapeHTML 不带HTML转义的JSON序列化

func NewECBDecrypter

func NewECBDecrypter(b cipher.Block) cipher.BlockMode

NewECBDecrypter 生成ECB解密器

func NewECBEncrypter

func NewECBEncrypter(b cipher.Block) cipher.BlockMode

NewECBEncrypter 生成ECB加密器

func Nonce

func Nonce(size uint) string

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

func NonceByte

func NonceByte(size uint) []byte

NonceByte 生成指定长度的随机字节 (最好是偶数)

func SHA1

func SHA1(s string) string

SHA1 计算sha1值

func SHA256

func SHA256(s string) string

SHA256 计算sha256值

func SignWithSHA1

func SignWithSHA1(token string, items ...string) string

SignWithSHA1 事件消息sha1签名

Types

type APIResult

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

APIResult API结果 (支付v3)

type AuthScope

type AuthScope string

AuthScope 网页授权作用域

const (
	SnsapiBase        AuthScope = "snsapi_base"        // 静默授权,可获取基础信息
	SnsapiUser        AuthScope = "snsapi_userinfo"    // 手动授权(公众号),可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息
	SnsapiPrivateInfo AuthScope = "snsapi_privateinfo" // 手动授权(企业微信),可获取成员的详细信息,包含头像、二维码等敏感信息
)

type CDATA

type CDATA string

CDATA XML `CDATA` 标记

func (CDATA) MarshalXML

func (c CDATA) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML XML 带 `CDATA` 标记序列化

type CipherText added in v1.0.3

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

CipherText 加密文本

func AESEncryptCBC added in v1.0.3

func AESEncryptCBC(key, iv, data []byte) (*CipherText, error)

AESEncryptCBC AES-CBC 加密(pkcs#7, 32位填充)

func AESEncryptECB added in v1.0.3

func AESEncryptECB(key, data []byte) (*CipherText, error)

AESEncryptECB AES-ECB 加密(pkcs#7, 32位填充)

func AESEncryptGCM added in v1.0.3

func AESEncryptGCM(key, nonce, data, aad []byte) (*CipherText, error)

AESEncryptGCM AES-GCM 加密 (NonceSize = 12 & TagSize = 16)

func EventEncrypt

func EventEncrypt(receiveID, encodingAESKey, nonce string, plainText []byte) (*CipherText, error)

EventEncrypt 时间消息加密 [参考](https://developer.work.weixin.qq.com/document/path/90968)

func (*CipherText) Bytes added in v1.0.3

func (ct *CipherText) Bytes() []byte

Bytes 获取加密数据的bytes

func (*CipherText) Data added in v1.0.3

func (ct *CipherText) Data() []byte

Data 获取GCM加密数据的真实数据

func (*CipherText) String added in v1.0.3

func (ct *CipherText) String() string

Bytes 返回加密数据base64字符串

func (*CipherText) Tag added in v1.0.3

func (ct *CipherText) Tag() []byte

Tag 获取GCM加密数据的tag

type Corp

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

Corp 企业微信(企业内部开发)

func NewCorp

func NewCorp(corpid, secret string, options ...CorpOption) *Corp

NewCorp 生成一个企业微信(企业内部开发)实例

func (*Corp) AccessToken

func (c *Corp) AccessToken(ctx context.Context) (gjson.Result, error)

AccessToken 获取接口调用凭据 (开发者应在 WithAccessToken 回调函数中使用该方法,并自行实现存/取)

func (*Corp) CorpID

func (c *Corp) CorpID() string

AppID 返回AppID

func (*Corp) DecodeEventMsg

func (c *Corp) DecodeEventMsg(signature, timestamp, nonce, encryptMsg string) (V, error)

DecodeEventMsg 解析事件消息,使用:msg_signature、timestamp、nonce、msg_encrypt [参考](https://developer.work.weixin.qq.com/document/path/90930)

func (*Corp) GetBuffer

func (c *Corp) GetBuffer(ctx context.Context, accessToken, path string, query url.Values) ([]byte, error)

GetBuffer GET请求获取buffer (如:获取媒体资源)

func (*Corp) GetJSON

func (c *Corp) GetJSON(ctx context.Context, accessToken, path string, query url.Values) (gjson.Result, error)

GetJSON GET请求JSON数据

func (*Corp) OAuthURL

func (c *Corp) OAuthURL(scope AuthScope, redirectURI, state, agentID string) string

OAuthURL 生成网页授权URL [参考](https://developer.work.weixin.qq.com/document/path/91022)

func (*Corp) PostBuffer

func (c *Corp) PostBuffer(ctx context.Context, accessToken, path string, params X) ([]byte, error)

PostBuffer POST请求获取buffer (如:获取二维码)

func (*Corp) PostJSON

func (c *Corp) PostJSON(ctx context.Context, accessToken, path string, params X) (gjson.Result, error)

PostJSON POST请求JSON数据

func (*Corp) ReplyEventMsg

func (c *Corp) ReplyEventMsg(msg V) (V, error)

ReplyEventMsg 事件消息回复

func (*Corp) Secret

func (c *Corp) Secret() string

Secret 返回Secret

func (*Corp) Upload

func (c *Corp) Upload(ctx context.Context, accessToken, path string, form UploadForm) (gjson.Result, error)

Upload 上传媒体资源

func (*Corp) VerifyURL

func (c *Corp) VerifyURL(signature, timestamp, nonce, echoStr string) (string, error)

VerifyURL 服务器URL验证,使用:msg_signature、timestamp、nonce、echostr(若验证成功,解密echostr后返回msg字段内容) [参考](https://developer.work.weixin.qq.com/document/path/90930)

type CorpOption

type CorpOption func(c *Corp)

CorpOption 企业微信设置项

func WithCorpHttpCli

func WithCorpHttpCli(cli *http.Client) CorpOption

WithCorpHttpCli 设置企业微信请求的 HTTP Client

func WithCorpLogger

func WithCorpLogger(f func(ctx context.Context, data map[string]string)) CorpOption

WithCorpLogger 设置企业微信日志记录

func WithCorpSrvCfg

func WithCorpSrvCfg(token, aeskey string) CorpOption

WithCorpSrvCfg 设置企业微信服务器配置 [参考](https://developer.work.weixin.qq.com/document/path/90968)

type DownloadResult

type DownloadResult struct {
	HashType  string
	HashValue string
	Buffer    []byte
}

DownloadResult 资源下载结果 (支付v3)

type FormFileFunc

type FormFileFunc func(w io.Writer) error

FormFileFunc 将文件写入表单流

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(certs ...tls.Certificate) 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 MPOption

type MPOption func(mp *MiniProgram)

MPOption 小程序设置项

func WithMPAesKey

func WithMPAesKey(serialNO, key string) MPOption

WithMPAesKey 设置小程序 AES-GCM 加密Key

func WithMPHttpCli

func WithMPHttpCli(c *http.Client) MPOption

WithMPHttpCli 设置小程序请求的 HTTP Client

func WithMPLogger

func WithMPLogger(f func(ctx context.Context, data map[string]string)) MPOption

WithMPLogger 设置小程序日志记录

func WithMPPrivateKey

func WithMPPrivateKey(key *PrivateKey) MPOption

WithMPPrivateKey 设置小程序RSA私钥

func WithMPPublicKey

func WithMPPublicKey(serialNO string, key *PublicKey) MPOption

WithMPPublicKey 设置小程序平台RSA公钥

func WithMPSrvCfg

func WithMPSrvCfg(token, aeskey string) MPOption

WithMPSrvCfg 设置小程序服务器配置 [参考](https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/message-push.html)

type MiniProgram

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

MiniProgram 小程序

func NewMiniProgram

func NewMiniProgram(appid, secret string, options ...MPOption) *MiniProgram

NewMiniProgram 生成一个小程序实例

func (*MiniProgram) AccessToken

func (mp *MiniProgram) AccessToken(ctx context.Context) (gjson.Result, error)

AccessToken 获取接口调用凭据

func (*MiniProgram) AppID

func (mp *MiniProgram) AppID() string

AppID 返回appid

func (*MiniProgram) Code2Session

func (mp *MiniProgram) Code2Session(ctx context.Context, code string) (gjson.Result, error)

Code2Session 通过临时登录凭证code完成登录流程

func (*MiniProgram) DecodeEncryptData

func (mp *MiniProgram) DecodeEncryptData(sessionKey, iv, encryptData string) ([]byte, error)

DecodeEncryptData 解析加密数据,如:授权的用户信息和手机号 [参考](https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html)

func (*MiniProgram) DecodeEventMsg

func (mp *MiniProgram) DecodeEventMsg(signature, timestamp, nonce, encryptMsg string) (V, error)

DecodeEventMsg 解析事件消息,使用:msg_signature、timestamp、nonce、msg_encrypt [参考](https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/message-push.html)

func (*MiniProgram) GetBuffer

func (mp *MiniProgram) GetBuffer(ctx context.Context, accessToken, path string, query url.Values) ([]byte, error)

GetBuffer GET请求获取buffer (如:获取媒体资源)

func (*MiniProgram) GetJSON

func (mp *MiniProgram) GetJSON(ctx context.Context, accessToken, path string, query url.Values) (gjson.Result, error)

GetJSON GET请求JSON数据

func (*MiniProgram) PostBuffer

func (mp *MiniProgram) PostBuffer(ctx context.Context, accessToken, path string, params X) ([]byte, error)

PostBuffer POST请求获取buffer (如:获取二维码)

func (*MiniProgram) PostJSON

func (mp *MiniProgram) PostJSON(ctx context.Context, accessToken, path string, params X) (gjson.Result, error)

PostJSON POST请求JSON数据

func (*MiniProgram) ReplyEventMsg

func (mp *MiniProgram) ReplyEventMsg(msg V) (V, error)

ReplyEventMsg 事件消息回复

func (*MiniProgram) SafePostBuffer

func (mp *MiniProgram) SafePostBuffer(ctx context.Context, accessToken, path string, params X) ([]byte, error)

SafePostBuffer POST请求获取buffer (如:获取二维码) 安全鉴权模式 https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/getting_started/api_signature.html 支持的api可参考 https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc

func (*MiniProgram) SafePostJSON

func (mp *MiniProgram) SafePostJSON(ctx context.Context, accessToken, path string, params X) (gjson.Result, error)

SafePostJSON POST请求JSON数据 安全鉴权模式 https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/getting_started/api_signature.html 支持的api可参考 https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc

func (*MiniProgram) Secret

func (mp *MiniProgram) Secret() string

Secret 返回secret

func (*MiniProgram) StableAccessToken

func (mp *MiniProgram) StableAccessToken(ctx context.Context, forceRefresh bool) (gjson.Result, error)

StableAccessToken 获取稳定版接口调用凭据,有两种调用模式: 1. 普通模式,access_token有效期内重复调用该接口不会更新access_token,绝大部分场景下使用该模式; 2. 强制刷新模式,会导致上次获取的access_token失效,并返回新的access_token

func (*MiniProgram) Upload

func (mp *MiniProgram) Upload(ctx context.Context, accessToken, path string, form UploadForm) (gjson.Result, error)

Upload 上传媒体资源

func (*MiniProgram) VerifyURL

func (mp *MiniProgram) VerifyURL(signature, timestamp, nonce string) error

VerifyURL 服务器URL验证,使用:signature、timestamp、nonce(若验证成功,请原样返回echostr参数内容) [参考](https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/message-push.html)

type OAOption

type OAOption func(oa *OfficialAccount)

OAOption 公众号设置项

func WithOAHttpCli

func WithOAHttpCli(c *http.Client) OAOption

WithOAHttpCli 设置公众号请求的 HTTP Client

func WithOALogger

func WithOALogger(f func(ctx context.Context, data map[string]string)) OAOption

WithOALogger 设置公众号日志记录

func WithOASrvCfg

func WithOASrvCfg(token, aeskey string) OAOption

WithOASrvCfg 设置公众号服务器配置 [参考](https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html)

type OfficialAccount

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

OfficialAccount 微信公众号

func NewOfficialAccount

func NewOfficialAccount(appid, secret string, options ...OAOption) *OfficialAccount

NewOfficialAccount 生成一个公众号实例

func (*OfficialAccount) AccessToken

func (oa *OfficialAccount) AccessToken(ctx context.Context) (gjson.Result, error)

AccessToken 获取接口调用凭据

func (*OfficialAccount) AppID

func (oa *OfficialAccount) AppID() string

AppID returns appid

func (*OfficialAccount) Code2OAuthToken

func (oa *OfficialAccount) Code2OAuthToken(ctx context.Context, code string) (gjson.Result, error)

Code2OAuthToken 获取网页授权Token

func (*OfficialAccount) DecodeEventMsg

func (oa *OfficialAccount) DecodeEventMsg(signature, timestamp, nonce, encryptMsg string) (V, error)

DecodeEventMsg 解析事件消息,使用:msg_signature、timestamp、nonce、msg_encrypt [参考](https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/message-push.html)

func (*OfficialAccount) GetBuffer

func (oa *OfficialAccount) GetBuffer(ctx context.Context, accessToken, path string, query url.Values) ([]byte, error)

GetBuffer GET请求获取buffer (如:获取媒体资源)

func (*OfficialAccount) GetJSON

func (oa *OfficialAccount) GetJSON(ctx context.Context, accessToken, path string, query url.Values) (gjson.Result, error)

GetJSON GET请求JSON数据

func (*OfficialAccount) OAuth2URL

func (oa *OfficialAccount) OAuth2URL(scope AuthScope, redirectURI, state string) string

OAuth2URL 生成网页授权URL [参考](https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html)

func (*OfficialAccount) PostBuffer

func (oa *OfficialAccount) PostBuffer(ctx context.Context, accessToken, path string, params X) ([]byte, error)

PostBuffer POST请求获取buffer (如:获取二维码)

func (*OfficialAccount) PostJSON

func (oa *OfficialAccount) PostJSON(ctx context.Context, accessToken, path string, params X) (gjson.Result, error)

PostJSON POST请求JSON数据

func (*OfficialAccount) RefreshOAuthToken

func (oa *OfficialAccount) RefreshOAuthToken(ctx context.Context, refreshToken string) (gjson.Result, error)

RefreshOAuthToken 刷新网页授权Token

func (*OfficialAccount) ReplyEventMsg

func (oa *OfficialAccount) ReplyEventMsg(msg V) (V, error)

ReplyEventMsg 事件消息回复

func (*OfficialAccount) Secret

func (oa *OfficialAccount) Secret() string

Secret returns app secret

func (*OfficialAccount) StableAccessToken

func (oa *OfficialAccount) StableAccessToken(ctx context.Context, forceRefresh bool) (gjson.Result, error)

StableAccessToken 获取稳定版接口调用凭据,有两种调用模式: 1. 普通模式,access_token 有效期内重复调用该接口不会更新 access_token,绝大部分场景下使用该模式; 2. 强制刷新模式,会导致上次获取的 access_token 失效,并返回新的 access_token

func (*OfficialAccount) SubscribeMsgAuthURL

func (oa *OfficialAccount) SubscribeMsgAuthURL(scene, templateID, redirectURL, reserved string) string

SubscribeMsgAuthURL 公众号一次性订阅消息授权URL [参考](https://developers.weixin.qq.com/doc/offiaccount/Message_Management/One-time_subscription_info.html)

func (*OfficialAccount) Upload

func (oa *OfficialAccount) Upload(ctx context.Context, accessToken, path string, form UploadForm) (gjson.Result, error)

Upload 上传媒体资源

func (*OfficialAccount) VerifyURL

func (oa *OfficialAccount) VerifyURL(signature, timestamp, nonce string) error

VerifyURL 服务器URL验证,使用:signature、timestamp、nonce(若验证成功,请原样返回echostr参数内容) [参考](https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/message-push.html)

type Pay

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

Pay 微信支付

func NewPay

func NewPay(mchid, apikey string, options ...PayOption) *Pay

NewPay 生成一个微信支付实例

func (*Pay) APPAPI

func (p *Pay) APPAPI(appid, prepayID string) V

APPAPI 用于APP拉起支付

func (*Pay) ApiKey

func (p *Pay) ApiKey() string

ApiKey 返回apikey

func (*Pay) DecryptRefund

func (p *Pay) DecryptRefund(encrypt string) (V, error)

DecryptRefund 退款结果通知解密

func (*Pay) JSAPI

func (p *Pay) JSAPI(appid, prepayID string) V

JSAPI 用于JS拉起支付

func (*Pay) MchID

func (p *Pay) MchID() string

MchID 返回mchid

func (*Pay) MinipRedpackJSAPI

func (p *Pay) MinipRedpackJSAPI(appid, pkg string) V

MinipRedpackJSAPI 小程序领取红包

func (*Pay) PostBuffer

func (p *Pay) PostBuffer(ctx context.Context, path string, params V) ([]byte, error)

PostBuffer POST请求获取buffer (无证书请求,如:下载交易订单)

func (*Pay) PostTLSBuffer

func (p *Pay) PostTLSBuffer(ctx context.Context, path string, params V) ([]byte, error)

PostBuffer POST请求获取buffer (带证书请求,如:下载资金账单)

func (*Pay) PostTLSXML

func (p *Pay) PostTLSXML(ctx context.Context, path string, params V) (V, error)

PostTLSXML POST请求XML数据 (带证书请求)

func (*Pay) PostXML

func (p *Pay) PostXML(ctx context.Context, path string, params V) (V, error)

PostXML POST请求XML数据 (无证书请求)

func (*Pay) Sign

func (p *Pay) Sign(v V) string

func (*Pay) Verify

func (p *Pay) Verify(v V) error

type PayOption

type PayOption func(p *Pay)

PayOption 微信支付设置项

func WithPayHttpCli

func WithPayHttpCli(c *http.Client) PayOption

WithPayHttpCli 设置支付无证书 HTTP Client

func WithPayLogger

func WithPayLogger(f func(ctx context.Context, data map[string]string)) PayOption

WithPayLogger 设置支付日志记录

func WithPayTLSCert

func WithPayTLSCert(cert tls.Certificate) PayOption

WithPayTLSCert 设置支付TLS证书

func WithPayTLSCli

func WithPayTLSCli(c *http.Client) PayOption

WithPayTLSCli 设置支付带证书 HTTP Client

type PayV3

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

PayV3 微信支付V3

func NewPayV3

func NewPayV3(mchid, apikey string, options ...PayV3Option) *PayV3

NewPayV3 生成一个微信支付(v3)实例

func (*PayV3) APPAPI

func (p *PayV3) APPAPI(appid, prepayID string) (V, error)

APPAPI 用于APP拉起支付

func (*PayV3) ApiKey

func (p *PayV3) ApiKey() string

ApiKey 返回apikey

func (*PayV3) Authorization

func (p *PayV3) Authorization(method, path string, query url.Values, body string) (string, error)

Authorization 生成签名并返回 HTTP Authorization

func (*PayV3) Download

func (p *PayV3) Download(ctx context.Context, downloadURL string, w io.Writer) error

Download 下载资源 (需先获取download_url)

func (*PayV3) GetJSON

func (p *PayV3) GetJSON(ctx context.Context, path string, query url.Values) (*APIResult, error)

GetJSON GET请求JSON数据

func (*PayV3) JSAPI

func (p *PayV3) JSAPI(appid, prepayID string) (V, error)

JSAPI 用于JS拉起支付

func (*PayV3) MchID

func (p *PayV3) MchID() string

MchID 返回mchid

func (*PayV3) PostJSON

func (p *PayV3) PostJSON(ctx context.Context, path string, params X) (*APIResult, error)

PostJSON POST请求JSON数据

func (*PayV3) Upload

func (p *PayV3) Upload(ctx context.Context, path string, form UploadForm) (*APIResult, error)

Upload 上传资源

func (*PayV3) Verify

func (p *PayV3) Verify(ctx context.Context, header http.Header, body []byte) error

Verify 验证微信签名

type PayV3Option

type PayV3Option func(p *PayV3)

PayV3Option 微信支付(v3)设置项

func WithPayV3HttpCli

func WithPayV3HttpCli(c *http.Client) PayV3Option

WithPayV3HttpCli 设置支付(v3)请求的 HTTP Client

func WithPayV3Logger

func WithPayV3Logger(f func(ctx context.Context, data map[string]string)) PayV3Option

WithPayV3Logger 设置支付(v3)日志记录

func WithPayV3PrivateKey

func WithPayV3PrivateKey(serialNO string, key *PrivateKey) PayV3Option

WithPayV3PrivateKey 设置支付(v3)商户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(data []byte) ([]byte, error)

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

func (*PrivateKey) DecryptOAEP

func (pk *PrivateKey) DecryptOAEP(hash crypto.Hash, data []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(data []byte) ([]byte, error)

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

func (*PublicKey) EncryptOAEP

func (pk *PublicKey) EncryptOAEP(hash crypto.Hash, data []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`)
)

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)

SetReqBody 设置请求Body

func (*ReqLog) SetReqHeader

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

SetReqHeader 设置请求头

func (*ReqLog) SetRespBody

func (l *ReqLog) SetRespBody(v string)

SetRespBody 设置返回报文

func (*ReqLog) SetRespHeader

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

SetRespHeader 设置返回头

func (*ReqLog) SetStatusCode

func (l *ReqLog) SetStatusCode(code int)

SetStatusCode 设置HTTP状态码

type SafeMode

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

SafeMode 安全鉴权模式配置

type ServerConfig

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

ServerConfig 服务器配置

type SignAlgo

type SignAlgo string

SignAlgo 签名算法

const (
	SignMD5        SignAlgo = "MD5"
	SignHMacSHA256 SignAlgo = "HMAC-SHA256"
)

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 EventReply

func EventReply(receiveID, token, encodingAESKey string, msg V) (V, error)

func ParseXMLToV

func ParseXMLToV(b []byte) (V, error)

ParseXMLToV parse xml to map

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 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