Skip to content
ghinkPublic

About

Go common pay utils

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

78 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

payutils

A pluggable payment toolkit for Go

The core dispatches payment operations, routes callbacks, and defines driver contracts It does not manage business orders, inventory, a ledger, or background recovery jobs It depends on neither a payment SDK nor an HTTP framework

  • Payment drivers construct provider clients and implement payment operations
  • HTTP drivers adapt framework routers to standard-library http.HandlerFunc
  • Applications supply order details, credentials, result persistence, and recovery policy

Module

go.gh.ink/payutils/v3
go get go.gh.ink/payutils/v3

Initialization

Import each selected payment driver in your application so its init registers the factory NewClient constructs a separate payment client for each configured upstream Credential keys and creation parameter types are defined in the selected driver's README

import (
    "go.gh.ink/payutils/v3/client"
    "go.gh.ink/payutils/v3/model"
)

// NewPayment constructs payment clients with application-supplied credentials and callbacks
func NewPayment(credentials model.C, contract model.Contract) (*client.Client, error) {
    return client.NewClient(model.Config{
        Endpoint:    "https://api.example.com",
        Credentials: credentials,
        Contract:    contract,
    })
}

Instances is optional To register callback routes automatically, import an HTTP driver and provide model.I{frameworkName: router} in Config.Instances Each configured payment upstream gets POST /{upstream}/callback Ensure any external URL prefix agrees with the router and Endpoint

Creating a payment

Prepare the business order in your application and build the selected driver's creation parameter Pass that value to c.Create(ctx, param) The first driver that claims the parameter type handles the request If none claims it, the method returns ErrNoDriverClaimed

The result has type any and contains the driver's payment credentials or redirect payload See that driver's README for its concrete type and supported platforms Creation alone does not establish that the payment succeeded

Actions and context

Client method Driver capability Purpose
Create(ctx, param) model.PayClient Dispatch a driver-specific creation request
StatusContext(ctx, upstreams, tradeID) model.ContextPayClient Query payment state and available evidence
CloseContext(ctx, upstreams, tradeID) model.ContextPayClient Ask upstreams to close a payment
RefundContext(ctx, upstreams, tradeID, currency, refundID, totalAmount, refundAmount, reason) model.ContextPayClient Submit a refund and return its reported outcome
QueryRefundContext(ctx, upstreams, tradeID, refundID) model.ContextRefundQuerier Query an existing refund

upstreams contains configured payment driver names Query and refund results are keyed by those names Calls visit the requested upstreams sequentially and stop on the first error; there is no transaction across upstreams and completed requests are not rolled back

Use the Context methods when the application has a request deadline or cancellation signal Drivers receive that context for their upstream requests A timeout or cancellation does not prove that an upstream rejected the request; query the payment or refund before deciding how to recover

ctx, cancel := context.WithTimeout(parent, 10*time.Second)
defer cancel()

statuses, err := c.StatusContext(ctx, []string{upstream}, tradeID)
if err != nil {
    return err
}
status := statuses[upstream]
// Inspect status.TradeStatus, ChannelID, Amount, Currency, and Time

Status, Close, Refund, and QueryRefund are also available without a context parameter Context actions do not fall back to these methods when a driver lacks context support: ErrContextActionsNotSupported identifies a missing action capability and ErrRefundQueryNotSupported identifies missing refund-query capability

Refund outcomes

refundID is the application's refund identifier totalAmount is the original payment amount and refundAmount is the requested refund amount Both use the smallest currency unit; currency is an ISO 4217 code Keep refund identities stable when recovering an uncertain request

results, err := c.RefundContext(
    ctx, []string{upstream}, tradeID,
    currencyCode, refundID, totalAmount, refundAmount, reason,
)
if err != nil {
    return err
}
result := results[upstream]
// A nil error can mean acceptance without settlement
// Inspect result.State and use QueryRefundContext or refund notifications to obtain the outcome
model.RefundResult field Meaning
State SUCCESS, PROCESSING, CLOSED, ABNORMAL, or UNKNOWN; empty when the driver provides no outcome
TradeID Payment identifier supplied by the driver
ChannelRefundID Upstream-assigned refund identifier, empty when unavailable
RefundAmount Reported refund amount in minor units, zero when unreported
Currency ISO 4217 code reported by the upstream or determined by its fixed-currency protocol
SuccessTime Upstream refund completion time, zero when unavailable

Do not equate a nil error, a zero amount, or a missing timestamp with completed settlement

Callbacks and contracts

A manually registered route can pass standard HTTP objects directly to the client

// PaymentCallback forwards notifications to the selected payment driver
func PaymentCallback(c *client.Client, upstream string) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        if err := c.Callback(upstream, w, r); err != nil {
            http.Error(w, "payment upstream unavailable", http.StatusBadRequest)
        }
    }
}

Callback returns an error when the requested upstream is not configured Once dispatched, the driver owns verification, decoding, the HTTP response, and reporting processing failures through Config.ErrorHandler Do not treat Callback returning nil as proof that the notification was accepted

Implement model.Contract for payment notifications Implement model.RefundContract on the same object for refund notifications

type Contract interface {
    StatusUpdater(
        ctx context.Context, r *http.Request, upstream, tradeID string,
        status model.TradeState, at time.Time,
    ) error
}

type RefundContract interface {
    RefundUpdater(
        ctx context.Context, r *http.Request, upstream, refundID string,
        result model.RefundResult,
    ) error
}

The configured wrappers strip TradeIDPrefix and TradeIDSuffix from callback trade and refund identifiers, including RefundResult.TradeID Persist business results idempotently before returning nil from a receiver A receiver error lets the driver respond with a failure so the upstream can retry

Contract: nil means payment results are not delivered to application code Without RefundContract, refund notifications are acknowledged without delivery; use refund results and queries when choosing this configuration

Payment evidence

Within StatusUpdater, read model.TradeEventFrom(ctx) to obtain optional evidence

Evidence Meaning
ChannelID Upstream-assigned payment transaction identifier, not the driver name
Amount Driver-reported transaction amount in minor units
Currency ISO 4217 currency code

TradeEventFrom reports whether a driver attached evidence Missing evidence must not be interpreted as a zero-value payment Active queries expose ChannelID, Amount, and Currency through model.ReturnStatus, alongside TradeStatus, Upstream, and Time Consult each driver for amount semantics and available timestamps

Configuration reference

model.Config field Meaning
Endpoint Required public base URL used to construct notification URLs
Credentials map[upstream]map[key]value; keys are defined by each payment driver
Instances Optional map[framework]router for callback registration
Contract Optional payment receiver, which may also implement RefundContract
ErrorHandler Callback-processing error hook; drivers still control the HTTP response
Debug Enables driver SDK debug logging
TradeIDPrefix / TradeIDSuffix Wrap merchant identifiers sent upstream; wrappers strip them from callback identifiers
NoNewPaymentWindows Minimum remaining lifetime for opening a payment; nil uses 30 seconds
SafetyMargin Time subtracted from the upstream payment expiry; nil uses 10 seconds
Marshal / Unmarshal JSON codecs; nil uses encoding/json

Errors

Use errors.Is with definitions from go.gh.ink/payutils/v3/errors Use errors.As to read *PayutilsError metadata such as UpstreamName, UpstreamCode, UpstreamMessage, UpstreamResponse, and FrameworkName The With* methods return copies without modifying shared error definitions WithCause preserves an underlying error for errors.Is, errors.As, and errors.Unwrap Error() returns the stable error message; metadata and causes are accessed separately

import (
    "errors"
    "log"

    payerrors "go.gh.ink/payutils/v3/errors"
)

// ReportPaymentError classifies an error and reports available upstream metadata
func ReportPaymentError(err error) {
    if errors.Is(err, payerrors.ErrRefundQueryNotSupported) {
        log.Print("refund lookup is unavailable for this driver")
    }
    var detail *payerrors.PayutilsError
    if errors.As(err, &detail) {
        log.Printf("upstream=%s code=%s cause=%v",
            detail.UpstreamName(), detail.UpstreamCode(), errors.Unwrap(detail))
    }
}
Error Meaning
ErrDriverNotRegistered, ErrUpstreamNotFound Missing driver registration or configured payment client
ErrCredentialsMissing Required credential fields are absent
ErrNoDriverClaimed No payment driver accepts the creation parameter
ErrContextActionsNotSupported, ErrRefundQueryNotSupported Driver capability is unavailable
ErrTradeNotExist, ErrRefundNotExist Upstream reports no matching payment or refund
ErrRefundAmountInvalid Refund amount cannot support the reported outcome
ErrNotificationIdentityMismatch Notification belongs to a different application or merchant
ErrNotificationEvidenceInvalid Notification lacks valid identity, status, or amount evidence
ErrNotificationStatusMismatch Notification event and payload status disagree
ErrNoEnoughTimeToPay, ErrUnsupportedCurrency, ErrUnsupportedPlatform, ErrUnsupportedInstance Request or integration configuration is unsupported

Driver contracts

  • A payment driver implements model.PayDriver, constructs a model.PayClient, and registers with driver.RegisterPay
  • Its clients implement model.ContextPayClient for context-aware actions
  • Refund lookup is optional through model.RefundQuerier and model.ContextRefundQuerier
  • A driver verifies notification signatures and ownership before forwarding evidence to configured receivers
  • An HTTP driver implements model.HttpDriver and model.HttpInstance, then registers with driver.RegisterHttp
  • Payment and HTTP drivers interact through net/http types and do not depend on each other

See payment interfaces, callback contracts, and driver interfaces for the complete signatures

License

See LICENSE

About

Go common pay utils

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages