wire

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: MIT Imports: 16 Imported by: 0

README

wire-go

Official Go SDK for the Wire payment API.

Install

go get github.com/buildry-wire/wire-go

Quickstart

package main

import (
	"context"
	"fmt"
	"log"

	wire "github.com/buildry-wire/wire-go"
)

func main() {
	client := wire.NewClient("sk_live_...")
	ctx := context.Background()

	pi, err := client.PaymentIntents.Create(ctx, &wire.PaymentIntentCreateParams{
		Amount:   50000, // 500.00 MNT, minor units
		Currency: "MNT",
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(pi.ID, pi.Status)
}

Auto-pagination

it := client.Charges.List(ctx, &wire.ListParams{Limit: 50})
for it.Next() {
	fmt.Println(it.Current().ID)
}
if err := it.Err(); err != nil {
	log.Fatal(err)
}

Webhook verification

func handler(w http.ResponseWriter, r *http.Request) {
	body, _ := io.ReadAll(r.Body)
	event, err := client.Webhooks.Verify(body, r.Header.Get(wire.SignatureHeader), endpointSecret)
	if err != nil {
		http.Error(w, "bad signature", http.StatusBadRequest)
		return
	}
	fmt.Println("event:", event.Type)
}

Errors

var werr *wire.Error
if errors.As(err, &werr) {
	fmt.Println(werr.Code, werr.RequestID, werr.StatusCode)
}

License

MIT

Documentation

Overview

Package wire is the official Go SDK for the Wire payment API (https://wire.mn).

Create a client with an API key and call resource services:

client := wire.NewClient("sk_live_...")
pi, err := client.PaymentIntents.Create(ctx, &wire.PaymentIntentCreateParams{Amount: 50000})

Index

Constants

View Source
const DefaultBaseURL = "https://api.wire.mn"

DefaultBaseURL is the production Wire API endpoint.

View Source
const DefaultTolerance = 300 * time.Second

DefaultTolerance is the max allowed clock skew between signature timestamp and now.

View Source
const SignatureHeader = "WirePayment-Signature"

SignatureHeader is the header carrying the webhook signature.

Variables

View Source
var ErrInvalidSignature = errors.New("wire: webhook signature verification failed")

ErrInvalidSignature is returned when a webhook signature does not verify.

Functions

This section is empty.

Types

type Charge

type Charge struct {
	ID               string  `json:"id"`
	Object           string  `json:"object"`
	PaymentIntent    string  `json:"payment_intent"`
	Operator         string  `json:"operator"`
	OperatorChargeID *string `json:"operator_charge_id"`
	Status           string  `json:"status"`
	Amount           int64   `json:"amount"`
	Fee              int64   `json:"fee"`
	AmountRefunded   int64   `json:"amount_refunded"`
	FailureCode      *string `json:"failure_code"`
	FailureMessage   *string `json:"failure_message"`
	Livemode         bool    `json:"livemode"`
	Created          int64   `json:"created"`
}

Charge is a single attempt to move money via an operator.

type ChargeService

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

ChargeService accesses /v1/charges.

func (*ChargeService) List

func (s *ChargeService) List(ctx context.Context, p *ListParams) *Iter[Charge]

List returns an auto-paginating iterator over charges.

func (*ChargeService) Retrieve

func (s *ChargeService) Retrieve(ctx context.Context, id string) (*Charge, error)

Retrieve fetches a charge by id.

type Client

type Client struct {
	PaymentIntents   *PaymentIntentService
	Charges          *ChargeService
	Events           *EventService
	WebhookEndpoints *WebhookEndpointService
	Webhooks         *WebhooksService
	// contains filtered or unexported fields
}

Client is a Wire API client. Create it with NewClient.

func NewClient

func NewClient(apiKey string, opts ...Option) *Client

NewClient builds a Client with the given API key (sk_live_...).

type Deleted

type Deleted struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Deleted bool   `json:"deleted"`
}

Deleted is the response shape for delete operations.

type Error

type Error struct {
	Type                string `json:"type"`
	Code                string `json:"code"`
	Message             string `json:"message"`
	Param               string `json:"param"`
	RequestID           string `json:"request_id"`
	DocURL              string `json:"doc_url"`
	OperatorDeclineCode string `json:"operator_decline_code"`
	StatusCode          int    `json:"-"`
}

Error is a typed Wire API error. Use errors.As to extract it.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

type Event

type Event struct {
	ID         string          `json:"id"`
	Object     string          `json:"object"`
	Type       string          `json:"type"`
	APIVersion string          `json:"api_version"`
	Data       json.RawMessage `json:"data"`
	Livemode   bool            `json:"livemode"`
	Created    int64           `json:"created"`
}

Event is a record of something that happened, delivered via webhooks.

type EventService

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

EventService accesses /v1/events.

func (*EventService) List

func (s *EventService) List(ctx context.Context, p *ListParams) *Iter[Event]

List returns an auto-paginating iterator over events.

func (*EventService) Retrieve

func (s *EventService) Retrieve(ctx context.Context, id string) (*Event, error)

Retrieve fetches an event by id.

type Iter

type Iter[T any] struct {
	// contains filtered or unexported fields
}

Iter is a lazy auto-paginator over a cursor-paginated collection.

it := client.Charges.List(ctx, nil)
for it.Next() {
    ch := it.Current()
}
if err := it.Err(); err != nil { ... }

func (*Iter[T]) Current

func (it *Iter[T]) Current() T

Current returns the item the iterator is positioned on.

func (*Iter[T]) Err

func (it *Iter[T]) Err() error

Err returns the first error encountered while paginating.

func (*Iter[T]) Next

func (it *Iter[T]) Next() bool

Next advances to the next item, fetching the next page when needed. It returns false when the collection is exhausted or an error occurred (check Err).

type List

type List[T any] struct {
	Object  string `json:"object"`
	Data    []T    `json:"data"`
	HasMore bool   `json:"has_more"`
}

List is one page of a cursor-paginated collection.

type ListParams

type ListParams struct {
	Limit         int
	StartingAfter string
	EndingBefore  string
}

ListParams are shared pagination parameters.

type Option

type Option func(*Client)

Option configures a Client.

func WithBackoff

func WithBackoff(d time.Duration) Option

WithBackoff sets the base backoff duration between retries.

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL overrides the API base URL (e.g. a local dev server).

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

WithHTTPClient injects a custom *http.Client.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets the max retry count for 429/5xx/network errors.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the per-request timeout on the default HTTP client.

type PaymentIntent

type PaymentIntent struct {
	ID                string            `json:"id"`
	Object            string            `json:"object"`
	Amount            int64             `json:"amount"`
	Currency          string            `json:"currency"`
	Status            string            `json:"status"`
	ClientSecret      string            `json:"client_secret"`
	AutomaticOperator bool              `json:"automatic_operator"`
	AllowedOperators  []string          `json:"allowed_operators"`
	SelectedOperator  *string           `json:"selected_operator"`
	NextAction        json.RawMessage   `json:"next_action"`
	Metadata          map[string]string `json:"metadata"`
	Livemode          bool              `json:"livemode"`
	Created           int64             `json:"created"`
	ExpiresAt         *int64            `json:"expires_at"`
}

PaymentIntent is the primary object for accepting a payment.

type PaymentIntentConfirmParams

type PaymentIntentConfirmParams struct {
	ReturnURL      string `json:"return_url,omitempty"`
	IdempotencyKey string `json:"-"`
}

PaymentIntentConfirmParams are the optional inputs to Confirm.

type PaymentIntentCreateParams

type PaymentIntentCreateParams struct {
	Amount            int64             `json:"amount"`
	Currency          string            `json:"currency,omitempty"`
	AutomaticOperator *bool             `json:"automatic_operator,omitempty"`
	AllowedOperators  []string          `json:"allowed_operators,omitempty"`
	Metadata          map[string]string `json:"metadata,omitempty"`
	IdempotencyKey    string            `json:"-"`
}

PaymentIntentCreateParams are the inputs to Create.

type PaymentIntentService

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

PaymentIntentService accesses /v1/payment_intents.

func (*PaymentIntentService) Cancel

Cancel cancels a payment intent.

func (*PaymentIntentService) Confirm

Confirm submits a payment intent for processing.

func (*PaymentIntentService) Create

Create starts a new payment intent.

func (*PaymentIntentService) List

List returns an auto-paginating iterator over payment intents.

func (*PaymentIntentService) Retrieve

func (s *PaymentIntentService) Retrieve(ctx context.Context, id string) (*PaymentIntent, error)

Retrieve fetches a payment intent by id.

type WebhookEndpoint

type WebhookEndpoint struct {
	ID            string   `json:"id"`
	Object        string   `json:"object"`
	URL           string   `json:"url"`
	EnabledEvents []string `json:"enabled_events"`
	Status        string   `json:"status"`
	Secret        string   `json:"secret,omitempty"` // returned only at creation
	Livemode      bool     `json:"livemode"`
	Created       int64    `json:"created"`
}

WebhookEndpoint is a merchant-registered URL that receives events.

type WebhookEndpointCreateParams

type WebhookEndpointCreateParams struct {
	URL            string   `json:"url"`
	EnabledEvents  []string `json:"enabled_events,omitempty"`
	IdempotencyKey string   `json:"-"`
}

WebhookEndpointCreateParams are the inputs to Create.

type WebhookEndpointService

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

WebhookEndpointService accesses /v1/webhook_endpoints.

func (*WebhookEndpointService) Create

Create registers a webhook endpoint. The signing secret is returned once.

func (*WebhookEndpointService) Delete

func (s *WebhookEndpointService) Delete(ctx context.Context, id string) (*Deleted, error)

Delete removes a webhook endpoint.

func (*WebhookEndpointService) List

List returns an auto-paginating iterator over webhook endpoints.

func (*WebhookEndpointService) Retrieve

Retrieve fetches a webhook endpoint by id.

func (*WebhookEndpointService) Update

Update modifies a webhook endpoint (Stripe-style POST update).

type WebhookEndpointUpdateParams

type WebhookEndpointUpdateParams struct {
	URL            *string  `json:"url,omitempty"`
	EnabledEvents  []string `json:"enabled_events,omitempty"`
	Status         *string  `json:"status,omitempty"`
	IdempotencyKey string   `json:"-"`
}

WebhookEndpointUpdateParams are the partial-update inputs.

type WebhooksService

type WebhooksService struct{}

WebhooksService verifies inbound webhook signatures.

func (*WebhooksService) Verify

func (s *WebhooksService) Verify(payload []byte, header, secret string) (*Event, error)

Verify checks a webhook payload's signature and returns the parsed Event. payload must be the raw request body bytes (verify BEFORE JSON parsing).

func (*WebhooksService) VerifyWithTolerance

func (s *WebhooksService) VerifyWithTolerance(payload []byte, header, secret string, tolerance time.Duration) (*Event, error)

VerifyWithTolerance is Verify with a custom timestamp tolerance.

Jump to

Keyboard shortcuts

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