La referencia de API proviene de los comentarios de documentación de Go en el código fuente y está redactada en inglés.
package wechatpay
import "github.com/nsgo-dev/game/pkg/online/storeverify/wechatpay"Resumen
Package wechatpay is experimental: its API and documented formats may change in a minor release. See the API stability policy. is the server side of WeChat mini game virtual payments (道具直购): it signs the order a client passes to wx.requestMidasPaymentGameItem and verifies the platform's goods delivery notifications, delivering each order exactly once however often the platform retries it.
The package has no NSGo dependency, so it runs in a game's backend. It does not receive the HTTP push itself: the push URL's token check and the safe-mode AES decryption stay with the server that hosts it, which passes the decoded event, Payload and PayEventSig to Handler.Handle and answers {"ErrCode":0,"ErrMsg":"Success"} when Handle returns nil.
Índice
Constantes
const (
EnvProduction = 0
EnvSandbox = 1
)Midas environments for Order.Env, Delivery.Env and Handler.Env.
const EventGoodsDeliver = "minigame_game_pay_goods_deliver_notify"EventGoodsDeliver is the Event of the push WeChat sends to deliver goods bought in the game with wx.requestMidasPaymentGameItem.
Variables
var ErrInvalid = errors.New("wechatpay: invalid request")ErrInvalid reports an order or a notification that fails validation or verification. Handle wraps it with the reason.
Funciones
func PayEventSig(appKey, event, payload string) stringPayEventSig is the signature WeChat puts on a payment push: HMAC-SHA256 with the payment environment's AppKey over event + "&" + payload, in lowercase hex. Handle checks it; tests and mock pushes use it to sign a payload.
func SignOrder(appKey, sessionKey string, o Order) (signDataJSON, paySig, signature string, err error)SignOrder builds the signData JSON for wx.requestMidasPaymentGameItem with its paySig (HMAC-SHA256 with the payment environment's AppKey over "requestMidasPaymentGameItem&" + signData) and the user-state signature (HMAC-SHA256 with the player's session key over signData). Call it on the server: the AppKey must never reach a client. The client passes all three strings to the platform unchanged.
Tipos
type Delivery struct {
OpenID string `json:"OpenId"`
Env int `json:"Env"`
OutTradeNo string `json:"OutTradeNo"`
GoodsInfo GoodsInfo `json:"GoodsInfo"`
}Delivery is the Payload of a goods delivery notification.
func (d Delivery) Validate() errorValidate checks the fields the server uses to grant goods. Platform-specific extension fields remain accepted by the JSON decoder, but the identity and quantity that reach Deliver must be usable and bounded.
type DeliveryStore interface {
// Get reports whether outTradeNo was delivered, with the Payload recorded for it.
Get(ctx context.Context, outTradeNo string) (payload []byte, ok bool, err error)
// Put records outTradeNo as delivered with its Payload. Putting an order already recorded keeps the first record.
Put(ctx context.Context, outTradeNo string, payload []byte) error
}DeliveryStore records the orders a Handler has delivered, keyed by OutTradeNo. A durable store keeps retries that arrive after a restart from delivering again.
type GoodsInfo struct {
ProductID string `json:"ProductId"`
Quantity int `json:"Quantity"`
ZoneID string `json:"ZoneId"`
OrigPrice int `json:"OrigPrice"`
ActualPrice int `json:"ActualPrice"`
Attach string `json:"Attach"`
OrderSource int `json:"OrderSource"`
}GoodsInfo is what a Delivery grants. Prices are in fen.
type Handler struct {
// AppKey is the payment environment's AppKey, which signs every push.
AppKey string
// Env is the environment this server delivers for; a notification from the other environment is refused, so sandbox purchases never grant goods in production.
Env int
// Store records delivered orders.
Store DeliveryStore
// Deliver grants the goods.
Deliver func(context.Context, Delivery) error
// contains filtered or unexported fields
}Handler verifies goods delivery notifications and calls Deliver once per OutTradeNo. Retries of a delivered order, including ones that arrive while the first is still being delivered in the same process, return nil without calling Deliver. A Deliver error is not recorded, so the platform's next retry delivers again.
Several server processes sharing one durable store can still race between Get and Put; there Deliver itself must be idempotent on OutTradeNo, for example by granting in the same database transaction that records the order.
A Handler must not be copied after first use.
func (h *Handler) Handle(ctx context.Context, event, payload, payEventSig string) errorHandle verifies one push's event, Payload and PayEventSig, and delivers the order unless it was delivered before. A nil error means the server should answer {"ErrCode":0,"ErrMsg":"Success"}; any error means a non-zero ErrCode, so the platform retries.
type MemoryStore struct {
// contains filtered or unexported fields
}MemoryStore is an in-process DeliveryStore for tests and single-process servers that can afford to forget deliveries on restart.
func NewMemoryStore() *MemoryStoreNewMemoryStore returns an empty MemoryStore.
func (s *MemoryStore) Get(_ context.Context, outTradeNo string) ([]byte, bool, error)Get implements DeliveryStore.
func (s *MemoryStore) Put(_ context.Context, outTradeNo string, payload []byte) errorPut implements DeliveryStore.
type Order struct {
// OfferID is the offer ID from the mini game's payment settings (mp-支付基础配置).
OfferID string
// ProductID is the item's ID as configured on the platform.
ProductID string
// GoodsPrice is the unit price in fen; the platform checks it against the configured price.
GoodsPrice int
// BuyQuantity is the number of items bought.
BuyQuantity int
// OutTradeNo is the game's order number, the key deliveries are deduplicated by: at most 32 characters of letters, digits and _-|*@, not starting with an underscore.
OutTradeNo string
// Env is EnvProduction or EnvSandbox.
Env int
// ZoneID is the optional zone; the platform defaults it to "1".
ZoneID string
// Attach is optional data the platform passes back in the delivery notification.
Attach string
}Order is one purchase the game's server creates for wx.requestMidasPaymentGameItem. Prices are in fen.