core

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 31, 2021 License: Apache-2.0 Imports: 25 Imported by: 112

Documentation

Overview

Package core 微信支付 API v3 Go SDK HTTPClient 基础库,你可以使用它来创建一个 Client,并向微信支付发送 HTTP 请求

初始化 Client 时,你需要指定以下参数:

  • Credential 用于生成 HTTP Header 中的 Authorization 信息,微信支付 API v3依赖该值来保证请求的真实性和数据的完整性
  • Validator 用于对微信支付的应答进行校验,避免被恶意攻击

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bool added in v0.2.0

func Bool(b bool) *bool

Bool 复制 bool 对象,并返回复制体的指针

func CheckResponse

func CheckResponse(resp *http.Response) error

CheckResponse 校验请求是否成功

当http回包的状态码的范围不是200-299之间的时候,会返回相应的错误信息,主要包括http状态码、回包错误码、回包错误信息提示

func CreateFormField

func CreateFormField(w *multipart.Writer, fieldName, contentType string, fieldValue []byte) error

CreateFormField 设置form-data 中的普通属性

示例内容

Content-Disposition: form-data; name="meta";
Content-Type: application/json

{ "filename": "file_test.mp4", "sha256": " hjkahkjsjkfsjk78687dhjahdajhk " }

如果要设置上述内容

CreateFormField(w, "meta", "application/json", meta)
Example
package main

import (
	"encoding/json"
	"mime/multipart"

	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/core/consts"
)

func main() {
	var w multipart.Writer

	meta := map[string]string{
		"filename": "sample.jpg",
		"sha256":   "5944758444f0af3bc843e39b611a6b0c8c38cca44af653cd461b5765b71dc3f8",
	}

	metaBytes, err := json.Marshal(meta)
	if err != nil {
		// TODO: 处理错误
		return
	}

	err = core.CreateFormField(&w, "meta", consts.ApplicationJSON, metaBytes)
	if err != nil {
		// TODO: 处理错误
	}
}
Output:

func CreateFormFile

func CreateFormFile(w *multipart.Writer, filename, contentType string, file []byte) error

CreateFormFile 设置form-data中的文件

示例内容:

Content-Disposition: form-data; name="file"; filename="file_test.mp4";
Content-Type: video/mp4

pic1  //pic1即为媒体视频的二进制内容

如果要设置上述内容,则CreateFormFile(w, "file_test.mp4", "video/mp4", pic1)

Example
package main

import (
	"mime/multipart"

	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/core/consts"
)

func main() {
	var w multipart.Writer

	var fileContent []byte

	err := core.CreateFormFile(&w, "sample.jpg", consts.ImageJPG, fileContent)
	if err != nil {
		// TODO: 处理错误
	}
}
Output:

func Float32 added in v0.2.0

func Float32(f float32) *float32

Float32 复制 float32 对象,并返回复制体的指针

func Float64 added in v0.2.0

func Float64(f float64) *float64

Float64 复制 float64 对象,并返回复制体的指针

func Int32 added in v0.2.0

func Int32(i int32) *int32

Int32 复制 int64 对象,并返回复制体的指针

func Int64 added in v0.2.0

func Int64(i int64) *int64

Int64 复制 int64 对象,并返回复制体的指针

func ParameterToJSON added in v0.2.0

func ParameterToJSON(obj interface{}) (string, error)

ParameterToJSON 将参数转换为 Json 字符串

func ParameterToString added in v0.2.0

func ParameterToString(obj interface{}, collectionFormat string) string

ParameterToString 将参数转换为字符串,并使用指定分隔符分隔列表参数

func SelectHeaderContentType added in v0.2.0

func SelectHeaderContentType(contentTypes []string) string

SelectHeaderContentType select a content type from the available list.

func String added in v0.2.0

func String(s string) *string

String 复制 string 对象,并返回复制体的指针

func Time added in v0.2.0

func Time(t time.Time) *time.Time

Time 复制 time.Time 对象,并返回复制体的指针

func UnMarshalResponse added in v0.2.0

func UnMarshalResponse(httpResp *http.Response, resp interface{}) error

UnMarshalResponse 将回包组织成结构化数据

Types

type APIError added in v0.2.0

type APIError struct {
	StatusCode int         // 应答报文的 HTTP 状态码
	Header     http.Header // 应答报文的 Header 信息
	Body       string      // 应答报文的 Body 原文
	Code       string      `json:"code"`             // 应答报文的 Body 解析后的错误码信息,仅不符合预期/发生系统错误时存在
	Message    string      `json:"message"`          // 应答报文的 Body 解析后的文字说明信息,仅不符合预期/发生系统错误时存在
	Detail     interface{} `json:"detail,omitempty"` // 应答报文的 Body 解析后的详细信息,仅不符合预期/发生系统错误时存在
}

APIError 微信支付 API v3 标准错误结构

func (*APIError) Error added in v0.2.0

func (e *APIError) Error() string

type APIResult added in v0.2.0

type APIResult struct {
	// 本次请求所使用的 HTTPRequest
	Request *http.Request
	// 本次请求所获得的 HTTPResponse
	Response *http.Response
}

APIResult 微信支付API v3 请求结果

type Client

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

Client 微信支付API v3 基础 Client

func NewClient

func NewClient(ctx context.Context, opts ...ClientOption) (client *Client, err error)

NewClient 初始化一个微信支付API v3 HTTPClient

初始化的时候你可以传递多个配置信息

Example (Default)
package main

import (
	"context"
	"crypto/rsa"
	"crypto/x509"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/core/auth"
	"github.com/wechatpay-apiv3/wechatpay-go/utils"
)

const (
	testPrivateKey = `-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----`

	testWechatCertificateStr = `-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----`
)

var (
	privateKey           *rsa.PrivateKey
	wechatPayCertificate *x509.Certificate

	ctx context.Context
	err error
)

func init() {
	privateKey, err = utils.LoadPrivateKey(testPrivateKey)
	if err != nil {
		panic(fmt.Errorf("load private err:%s", err.Error()))
	}
	wechatPayCertificate, err = utils.LoadCertificate(testWechatCertificateStr)
	if err != nil {
		panic(fmt.Errorf("load certificate err:%s", err.Error()))
	}
	ctx = context.Background()
}

func main() {
	// 示例参数,实际使用时请自行初始化
	var (
		mchID                      string
		mchCertificateSerialNumber string
		mchPrivateKey              *rsa.PrivateKey
		wechatPayCertList          []*x509.Certificate
		customHTTPClient           *http.Client
	)

	ctx := context.Background()
	opts := []core.ClientOption{
		core.WithMerchantCredential(mchID, mchCertificateSerialNumber, mchPrivateKey), // 使用商户信息生成默认 WechatPayCredential
		core.WithWechatPayValidator(wechatPayCertList),                                // 使用微信支付平台证书列表生成默认 SHA256WithRSAVerifier
		core.WithHTTPClient(customHTTPClient),                                         // 设置自定义 HTTPClient 实例,不设置时使用默认 http.Client{}
		core.WithTimeout(2 * time.Second),                                             // 设置自定义超时时间,不设置时使用 http.Client{} 默认超时
	}
	client, err := core.NewClient(ctx, opts...)
	if err != nil {
		log.Printf("new wechat pay client err:%s", err.Error())
		return
	}
	// 接下来使用 client 进行请求发送
	_ = client
}
Output:

func (*Client) Delete

func (client *Client) Delete(ctx context.Context, requestURL string, requestBody interface{}) (*APIResult, error)

Delete 向微信支付发送一个 Http Delete 请求

func (*Client) Get

func (client *Client) Get(ctx context.Context, requestURL string) (*APIResult, error)

Get 向微信支付发送一个 HTTP Get 请求

func (*Client) Patch

func (client *Client) Patch(ctx context.Context, requestURL string, requestBody interface{}) (*APIResult, error)

Patch 向微信支付发送一个 HTTP Patch 请求

func (*Client) Post

func (client *Client) Post(ctx context.Context, requestURL string, requestBody interface{}) (*APIResult, error)

Post 向微信支付发送一个 HTTP Post 请求

func (*Client) Put

func (client *Client) Put(ctx context.Context, requestURL string, requestBody interface{}) (*APIResult, error)

Put 向微信支付发送一个 HTTP Put 请求

func (*Client) Request added in v0.2.0

func (client *Client) Request(
	ctx context.Context,
	method, requestPath string,
	headerParams http.Header,
	queryParams url.Values,
	postBody interface{},
	contentType string) (result *APIResult, err error)

Request 向微信支付发送请求

相比于 Get / Post / Put / Patch / Delete 方法,本方法可以设置更多内容

func (*Client) Upload

func (client *Client) Upload(ctx context.Context, requestURL, meta, reqBody, formContentType string) (*APIResult, error)

Upload 向微信支付发送上传文件

type ClientOption added in v0.2.0

type ClientOption interface {
	Apply(settings *dialSettings)
}

ClientOption 一个ClientOption可以作为微信支付api v3 client的配置

func WithCredential added in v0.2.0

func WithCredential(credential auth.Credential) ClientOption

WithCredential 返回一个指定credential的ClientOption,用于生成http request header 中authorization信息

func WithHTTPClient added in v0.2.0

func WithHTTPClient(client *http.Client) ClientOption

WithHTTPClient 返回一个指定网络通信为HttpClient的ClientOption,指定后使用用户自动创建的的http.client,如果用户不创建,则帮助用户 创建一个默认的http.client

func WithHeader added in v0.2.0

func WithHeader(header http.Header) ClientOption

WithHeader 返回一个为http client设置额外header信息的ClientOption

func WithMerchantCredential added in v0.2.0

func WithMerchantCredential(mchID, certificateSerialNo string, privateKey *rsa.PrivateKey) ClientOption

WithMerchantCredential 通过商户号、商户证书序列号、商户私钥构建一个默认的 Credential,用于生成请求头中的 Authorization 信息

func WithTimeout added in v0.2.0

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout 返回一个指定超时时间的ClientOption

func WithValidator added in v0.2.0

func WithValidator(validator auth.Validator) ClientOption

WithValidator 返回一个指定validator的ClientOption,用于校验http response header

func WithWechatPayValidator added in v0.2.0

func WithWechatPayValidator(certificateList []*x509.Certificate) ClientOption

WithWechatPayValidator 设置微信支付平台证书信息,返回一个指定validator的ClientOption,用于校验http response header

func WithoutValidator added in v0.2.0

func WithoutValidator() ClientOption

WithoutValidator 返回一个指定validator的ClientOption,不进行验签 用于下载证书和下载账单等不需要进行验签的接口

type ParameterError added in v0.2.0

type ParameterError struct {
	FieldName string
	Message   string
}

ParameterError 请求参数错误

func (*ParameterError) Error added in v0.2.0

func (e *ParameterError) Error() string

Directories

Path Synopsis
Package auth 微信支付 API v3 Go SDK 安全验证相关接口 Package auth 微信支付 API v3 Go SDK 安全验证相关接口 Package auth 微信支付 API v3 Go SDK 安全验证相关接口 Package auth 微信支付 API v3 Go SDK 安全验证相关接口
Package auth 微信支付 API v3 Go SDK 安全验证相关接口 Package auth 微信支付 API v3 Go SDK 安全验证相关接口 Package auth 微信支付 API v3 Go SDK 安全验证相关接口 Package auth 微信支付 API v3 Go SDK 安全验证相关接口
credentials
Package credentials 微信支付 API v3 Go SDK 请求报文头 Authorization 信息生成器
Package credentials 微信支付 API v3 Go SDK 请求报文头 Authorization 信息生成器
signers
Package signers 微信支付 API v3 Go SDK 数字签名生成器
Package signers 微信支付 API v3 Go SDK 数字签名生成器
validators
Package validators 微信支付 API v3 Go SDK 应答报文签名验证器 Package validators 微信支付 API v3 Go SDK 应答报文验证器
Package validators 微信支付 API v3 Go SDK 应答报文签名验证器 Package validators 微信支付 API v3 Go SDK 应答报文验证器
verifiers
Package verifiers 微信支付 API v3 Go SDK 数字签名验证器
Package verifiers 微信支付 API v3 Go SDK 数字签名验证器
Package consts 微信支付 API v3 Go SDK 常量
Package consts 微信支付 API v3 Go SDK 常量

Jump to

Keyboard shortcuts

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