acp

package module
v0.0.0-...-647c431 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2025 License: Apache-2.0 Imports: 20 Imported by: 0

README

Go SDK for the Agentic Commerce Protocol

Go Reference CI Status License

This repo bootstraps Go support for the Agentic Commerce Protocol (ACP). Both the checkout and delegated payment SDKs now live under a single Go module so you can depend on github.com/sumup/acp and call the handlers, models, and helpers you need.

Features

  • Checkout API — plug your own business logic into NewCheckoutHandler by implementing CheckoutSessionService. The handler exposes the official ACP checkout contract over net/http, supports optional signature verification and timestamp skew enforcement, and emits typed responses generated from the OpenAPI spec.
  • Delegated Payment API — payment service providers implement DelegatedPaymentProvider and wire it up via NewDelegatedPaymentHandler (optionally adding DelegatedPaymentWithAuthenticator and signature enforcement) to tokenize credentials and emit delegated vault tokens.

Example Servers

Two runnable samples live under examples:

Checkout sample
go run ./examples/checkout

Once the server is up, try exercising the flow with curl:

# Create a checkout session with two SKUs
curl -sS -X POST http://localhost:8080/checkout_sessions \
  -H 'Content-Type: application/json' \
  -d '{
        "items": [
          {"id": "latte", "quantity": 1},
          {"id": "mug", "quantity": 1}
        ],
        "buyer": {
          "first_name": "Ava",
          "last_name": "Agent",
          "email": "ava.agent@example.com"
        }
      }'

# Complete the session once you have the id from the response above
curl -sS -X POST http://localhost:8080/checkout_sessions/<session_id>/complete \
  -H 'Content-Type: application/json' \
  -d '{
        "payment_data": {
          "provider": "stripe",
          "token": "pm_sample_token"
        }
      }'

Feel free to copy this sample into your own project and swap the in-memory store for your real product catalog, fulfillment rules, and payment hooks.

To see webhook delivery end-to-end, export the environment variables below before starting the sample server. The handler will POST an `order_created` event every time a checkout session completes.

```bash
export ACP_WEBHOOK_ENDPOINT="https://webhook.site/your-endpoint"
export ACP_WEBHOOK_HEADER="Merchant_Name-Signature"
export ACP_WEBHOOK_SECRET="super-secret"
go run ./examples/checkout
Delegated payment sample
go run ./examples/delegated_payment

Then call it with:

curl -sS -X POST http://localhost:8080/agentic_commerce/delegate_payment \
  -H 'Content-Type: application/json' \
  -d '{
        "payment_method": {
          "type": "card",
          "card_number_type": "fpan",
          "number": "4242424242424242",
          "exp_month": "11",
          "exp_year": "2026",
          "display_last4": "4242",
          "display_card_funding_type": "credit",
          "metadata": {"issuer": "demo-bank"}
        },
        "allowance": {
          "reason": "one_time",
          "max_amount": 2000,
          "currency": "usd",
          "checkout_session_id": "cs_000001",
          "merchant_id": "demo-merchant",
          "expires_at": "2025-12-31T23:59:59Z"
        },
        "risk_signals": [
          {"type": "card_testing", "action": "manual_review", "score": 10}
        ],
        "metadata": {"source": "sample"}
      }'

License

Apache 2.0

Documentation

Overview

Package acp documents the Go SDK for the Agentic Commerce Protocol (ACP). It aggregates the checkout and delegated payment packages under a single module so merchants and PSPs can share common helpers, models, and documentation.

Checkout

Use NewCheckoutHandler with your CheckoutProvider implementation to expose the ACP checkout contract over `net/http`. Handler options such as WithSignatureVerifier and WithRequireSignedRequests enforce the canonical JSON signatures and timestamp skew requirements spelled out in the spec.

Delegated Payment

Payment service providers can call NewDelegatedPaymentHandler with their own DelegatedPaymentProvider to accept delegate payment payloads, validate them, and emit vault tokens scoped to a checkout session. Optional helpers such as WithAuthenticator and [DelegatedPaymentWithSignatureVerifier] keep API keys and signed requests in sync with ACP's security requirements.

How it works

  • Buyers check out using their preferred payment method and save it in ChatGPT.
  • The delegated payment payload is sent to the merchant’s PSP or vault directly. The delegated payment is single-use and set with allowances.
  • The PSP or vault returns a payment token scoped to the delegated payment outside of PCI scope.
  • OpenAI forwards the token during the complete-checkout call to enable the merchant to complete the transaction.

Index

Constants

View Source
const APIVersion = "2025-12-11"

APIVersion matches the published Agentic Commerce Protocol API. Emitted via the API-Version header on all HTTP responses returned by the handlers.

Variables

This section is empty.

Functions

func WithOffendingParam

func WithOffendingParam(jsonPath string) errorOption

WithOffendingParam sets the JSON path for the field that triggered the error.

func WithRetryAfter

func WithRetryAfter(d time.Duration) errorOption

WithRetryAfter specifies how long clients should wait before retrying.

func WithStatusCode

func WithStatusCode(status int) errorOption

WithStatusCode overrides the HTTP status code returned to the client.

Types

type Address

type Address struct {
	Name       string  `json:"name"`
	LineOne    string  `json:"line_one"`
	LineTwo    *string `json:"line_two,omitempty"`
	PostalCode string  `json:"postal_code"`
	City       string  `json:"city"`
	State      string  `json:"state"`
	Country    string  `json:"country"`
}

Address defines model for Address.

type Allowance

type Allowance struct {
	// Current possible values: "one_time".
	Reason AllowanceReason `json:"reason" validate:"required,eq=one_time"`
	// Max amount the payment method can be charged for.
	MaxAmount int `json:"max_amount" validate:"required,gt=0"`
	// Currency.
	Currency string `json:"currency" validate:"required,currency"`
	// Reference to checkout_session_id.
	CheckoutSessionID string `json:"checkout_session_id" validate:"required"`
	// Merchant identifying descriptor.
	MerchantID string `json:"merchant_id" validate:"required"`
	// Time formatted as an RFC 3339 string.
	ExpiresAt time.Time `json:"expires_at" validate:"required"`
}

Allowance scopes token use per the spec.

type AllowanceReason

type AllowanceReason string
const (
	AllowanceReasonOneTime AllowanceReason = "one_time"
)

type Authenticator

type Authenticator interface {
	Authenticate(ctx context.Context, apiKey string) error
}

Authenticator validates Authorization header API keys before the request reaches the provider.

type AuthenticatorFunc

type AuthenticatorFunc func(ctx context.Context, apiKey string) error

AuthenticatorFunc lifts bare functions into Authenticator.

func (AuthenticatorFunc) Authenticate

func (f AuthenticatorFunc) Authenticate(ctx context.Context, apiKey string) error

Authenticate validates the API key using the wrapped function.

type Buyer

type Buyer struct {
	Email       string  `json:"email"`
	FirstName   string  `json:"first_name"`
	LastName    string  `json:"last_name"`
	PhoneNumber *string `json:"phone_number,omitempty"`
}

Buyer defines model for Buyer.

type CardChecksPerformed

type CardChecksPerformed string
const (
	CardChecksPerformedAVS  CardChecksPerformed = "avs"
	CardChecksPerformedCVV  CardChecksPerformed = "cvv"
	CardChecksPerformedANI  CardChecksPerformed = "ani"
	CardChecksPerformedAUTH CardChecksPerformed = "auth0"
)

type CardFundingType

type CardFundingType string
const (
	CardFundingTypeCredit  CardFundingType = "credit"
	CardFundingTypeDebit   CardFundingType = "debit"
	CardFundingTypePrepaid CardFundingType = "prepaid"
)

type CardNumberType

type CardNumberType string
const (
	CardCardNumberTypeFPAN         CardNumberType = "fpan"
	CardCardNumberTypeNetworkToken CardNumberType = "network_token"
)

type CheckoutHandler

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

CheckoutHandler wires ACP checkout routes to a CheckoutProvider.

func NewCheckoutHandler

func NewCheckoutHandler(service CheckoutProvider, opts ...Option) *CheckoutHandler

NewCheckoutHandler builds a CheckoutHandler backed by net/http's ServeMux.

func (*CheckoutHandler) GetWebhookSender

func (h *CheckoutHandler) GetWebhookSender(endpoint, merchantName string, secret []byte, opts ...WebhookOption) (WebhookSender, error)

GetWebhookSender returns a configued WebhookSender that allows your implementation to deliver webhooks back to the agent.

Parameters:

  • endpoint is the absolute URL provided by OpenAI for receiving webhook events.
  • merchantName controls the signature header name (the header name is Merchant_Name-Signature).
  • secret is the HMAC secret provided by OpenAI for signing webhook payloads.

func (*CheckoutHandler) ServeHTTP

func (h *CheckoutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP satisfies http.Handler.

type CheckoutProvider

type CheckoutProvider interface {
	CreateSession(ctx context.Context, req CheckoutSessionCreateRequest) (*CheckoutSession, error)
	UpdateSession(ctx context.Context, id string, req CheckoutSessionUpdateRequest) (*CheckoutSession, error)
	GetSession(ctx context.Context, id string) (*CheckoutSession, error)
	CompleteSession(ctx context.Context, id string, req CheckoutSessionCompleteRequest) (*SessionWithOrder, error)
	CancelSession(ctx context.Context, id string) (*CheckoutSession, error)
}

CheckoutProvider is implemented by business logic that owns checkout sessions.

type CheckoutSession

type CheckoutSession struct {
	ID                  string                `json:"id"`
	Buyer               *Buyer                `json:"buyer,omitempty"`
	Currency            string                `json:"currency"`
	FulfillmentAddress  *Address              `json:"fulfillment_address,omitempty"`
	FulfillmentOptionId *string               `json:"fulfillment_option_id,omitempty"`
	FulfillmentOptions  []FulfillmentOption   `json:"fulfillment_options"`
	LineItems           []LineItem            `json:"line_items"`
	Links               []Link                `json:"links"`
	Messages            []Message             `json:"messages"`
	PaymentProvider     *PaymentProvider      `json:"payment_provider,omitempty"`
	Status              CheckoutSessionStatus `json:"status"`
	Totals              []Total               `json:"totals"`
}

CheckoutSession defines model for CheckoutSession.

type CheckoutSessionCompleteRequest

type CheckoutSessionCompleteRequest struct {
	Buyer       *Buyer      `json:"buyer,omitempty"`
	PaymentData PaymentData `json:"payment_data"`
}

CheckoutSessionCompleteRequest defines model for CheckoutSessionCompleteRequest.

func (CheckoutSessionCompleteRequest) Validate

Validate ensures CheckoutSessionCompleteRequest satisfies payment requirements.

type CheckoutSessionCreateRequest

type CheckoutSessionCreateRequest struct {
	Buyer              *Buyer   `json:"buyer,omitempty"`
	FulfillmentAddress *Address `json:"fulfillment_address,omitempty"`
	Items              []Item   `json:"items"`
}

CheckoutSessionCreateRequest defines model for CheckoutSessionCreateRequest.

func (CheckoutSessionCreateRequest) Validate

func (r CheckoutSessionCreateRequest) Validate() error

Validate ensures CheckoutSessionCreateRequest satisfies required schema constraints.

type CheckoutSessionStatus

type CheckoutSessionStatus string

CheckoutSessionStatus defines model for CheckoutSessionBase.Status.

const (
	CheckoutSessionStatusCanceled           CheckoutSessionStatus = "canceled"
	CheckoutSessionStatusCompleted          CheckoutSessionStatus = "completed"
	CheckoutSessionStatusInProgress         CheckoutSessionStatus = "in_progress"
	CheckoutSessionStatusNotReadyForPayment CheckoutSessionStatus = "not_ready_for_payment"
	CheckoutSessionStatusReadyForPayment    CheckoutSessionStatus = "ready_for_payment"
)

Defines values for CheckoutSessionBaseStatus.

type CheckoutSessionUpdateRequest

type CheckoutSessionUpdateRequest struct {
	Buyer               *Buyer   `json:"buyer,omitempty"`
	FulfillmentAddress  *Address `json:"fulfillment_address,omitempty"`
	FulfillmentOptionId *string  `json:"fulfillment_option_id,omitempty"`
	Items               *[]Item  `json:"items,omitempty"`
}

CheckoutSessionUpdateRequest defines model for CheckoutSessionUpdateRequest.

func (CheckoutSessionUpdateRequest) Validate

func (r CheckoutSessionUpdateRequest) Validate() error

Validate ensures CheckoutSessionUpdateRequest maintains schema constraints.

type DelegatedPaymentHandler

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

DelegatedPaymentHandler exposes the ACP delegate payment API over net/http.

func NewDelegatedPaymentHandler

func NewDelegatedPaymentHandler(service DelegatedPaymentProvider, opts ...Option) *DelegatedPaymentHandler

NewDelegatedPaymentHandler wires the delegate payment routes to the provided DelegatedPaymentProvider.

func (*DelegatedPaymentHandler) ServeHTTP

ServeHTTP satisfies http.Handler.

type DelegatedPaymentProvider

type DelegatedPaymentProvider interface {
	DelegatePayment(ctx context.Context, req PaymentRequest) (*VaultToken, error)
}

DelegatedPaymentProvider owns the delegated payment tokenization lifecycle. To integrate your Payments Service Provider with the Delegate Payment Spec implement this interface.

type Error

type Error struct {
	Type    ErrorType `json:"type"`
	Code    ErrorCode `json:"code"`
	Message string    `json:"message"`
	Param   *string   `json:"param,omitempty"`
	// contains filtered or unexported fields
}

Error represents a structured ACP error payload.

func NewHTTPError

func NewHTTPError(status int, typ ErrorType, code ErrorCode, message string, opts ...errorOption) *Error

NewHTTPError allows callers to control the status code explicitly.

func NewInvalidRequestError

func NewInvalidRequestError(message string, opts ...errorOption) *Error

NewInvalidRequestError builds a Bad Request ACP error payload.

func NewProcessingError

func NewProcessingError(message string, opts ...errorOption) *Error

NewProcessingError builds an Internal Server Error ACP error payload.

func NewRateLimitExceededError

func NewRateLimitExceededError(message string, opts ...errorOption) *Error

NewRateLimitExceededError builds a Too Many Requests ACP error payload.

func NewServiceUnavailableError

func NewServiceUnavailableError(message string, opts ...errorOption) *Error

NewServiceUnavailableError builds a Service Unavailable ACP error payload.

func (*Error) Error

func (e *Error) Error() string

Error makes *Error satisfy the stdlib error interface.

func (*Error) RetryAfter

func (e *Error) RetryAfter() time.Duration

RetryAfter returns the duration clients should wait before retrying.

type ErrorCode

type ErrorCode string

ErrorCode is a machine-readable identifier for the specific failure.

const (
	DuplicateRequest     ErrorCode = "duplicate_request"     // Safe duplicate with the same idempotency key.
	IdempotencyConflict  ErrorCode = "idempotency_conflict"  // Same idempotency key but different parameters.
	InvalidCard          ErrorCode = "invalid_card"          // Credential failed basic validation (such as length or expiry).
	InvalidSignature     ErrorCode = "invalid_signature"     // Signature is missing or does not match the payload.
	SignatureRequired    ErrorCode = "signature_required"    // Signed requests are required but headers were missing.
	StaleTimestamp       ErrorCode = "stale_timestamp"       // Timestamp skew exceeded the allowed window.
	MissingAuthorization ErrorCode = "missing_authorization" // Authorization header missing.
	InvalidAuthorization ErrorCode = "invalid_authorization" // Authorization header malformed or API key invalid.
	RequestNotIdempotent ErrorCode = "request_not_idempotent"
)

type ErrorType

type ErrorType string

ErrorType mirrors the ACP error.type field.

const (
	InvalidRequest     ErrorType = "invalid_request"     // Missing or malformed field.
	ProcessingError    ErrorType = "processing_error"    // Downstream gateway or network failure.
	RateLimitExceeded  ErrorType = "rate_limit_exceeded" // Too many requests.
	ServiceUnavailable ErrorType = "service_unavailable" // Temporary outage or maintenance.
)

type EventData

type EventData interface {
	// contains filtered or unexported methods
}

EventData is implemented by webhook payloads.

type EventDataType

type EventDataType string

EventDataType labels the payload for a webhook event.

const (
	EventDataTypeOrder EventDataType = "order"
)

type FulfillmentOption

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

FulfillmentOption defines model for CheckoutSessionBase.fulfillment_options.Item.

func (FulfillmentOption) AsFulfillmentOptionDigital

func (t FulfillmentOption) AsFulfillmentOptionDigital() (FulfillmentOptionDigital, error)

AsFulfillmentOptionDigital returns the union data inside the CheckoutSessionBase_FulfillmentOptions_Item as a FulfillmentOptionDigital

func (FulfillmentOption) AsFulfillmentOptionShipping

func (t FulfillmentOption) AsFulfillmentOptionShipping() (FulfillmentOptionShipping, error)

AsFulfillmentOptionShipping returns the union data inside the CheckoutSessionBase_FulfillmentOptions_Item as a FulfillmentOptionShipping

func (*FulfillmentOption) FromFulfillmentOptionDigital

func (t *FulfillmentOption) FromFulfillmentOptionDigital(v FulfillmentOptionDigital) error

FromFulfillmentOptionDigital overwrites any union data inside the CheckoutSessionBase_FulfillmentOptions_Item as the provided FulfillmentOptionDigital

func (*FulfillmentOption) FromFulfillmentOptionShipping

func (t *FulfillmentOption) FromFulfillmentOptionShipping(v FulfillmentOptionShipping) error

FromFulfillmentOptionShipping overwrites any union data inside the CheckoutSessionBase_FulfillmentOptions_Item as the provided FulfillmentOptionShipping

func (FulfillmentOption) MarshalJSON

func (t FulfillmentOption) MarshalJSON() ([]byte, error)

MarshalJSON serializes the underlying union for CheckoutSessionBase_FulfillmentOptions_Item.

func (*FulfillmentOption) MergeFulfillmentOptionDigital

func (t *FulfillmentOption) MergeFulfillmentOptionDigital(v FulfillmentOptionDigital) error

MergeFulfillmentOptionDigital performs a merge with any union data inside the CheckoutSessionBase_FulfillmentOptions_Item, using the provided FulfillmentOptionDigital

func (*FulfillmentOption) MergeFulfillmentOptionShipping

func (t *FulfillmentOption) MergeFulfillmentOptionShipping(v FulfillmentOptionShipping) error

MergeFulfillmentOptionShipping performs a merge with any union data inside the CheckoutSessionBase_FulfillmentOptions_Item, using the provided FulfillmentOptionShipping

func (*FulfillmentOption) UnmarshalJSON

func (t *FulfillmentOption) UnmarshalJSON(b []byte) error

UnmarshalJSON loads union data for CheckoutSessionBase_FulfillmentOptions_Item.

type FulfillmentOptionDigital

type FulfillmentOptionDigital struct {
	ID       string  `json:"id"`
	Subtitle *string `json:"subtitle,omitempty"`
	Subtotal int     `json:"subtotal"`
	Tax      int     `json:"tax"`
	Title    string  `json:"title"`
	Total    int     `json:"total"`
	Type     string  `json:"type"`
}

FulfillmentOptionDigital defines model for FulfillmentOptionDigital.

type FulfillmentOptionShipping

type FulfillmentOptionShipping struct {
	ID                   string     `json:"id"`
	Carrier              *string    `json:"carrier,omitempty"`
	EarliestDeliveryTime *time.Time `json:"earliest_delivery_time,omitempty"`
	LatestDeliveryTime   *time.Time `json:"latest_delivery_time,omitempty"`
	Subtitle             *string    `json:"subtitle,omitempty"`
	Subtotal             int        `json:"subtotal"`
	Tax                  int        `json:"tax"`
	Title                string     `json:"title"`
	Total                int        `json:"total"`
	Type                 string     `json:"type"`
}

FulfillmentOptionShipping defines model for FulfillmentOptionShipping.

type Item

type Item struct {
	ID       string `json:"id"`
	Quantity int    `json:"quantity"`
}

Item defines model for Item.

type LineItem

type LineItem struct {
	ID         string `json:"id"`
	BaseAmount int    `json:"base_amount"`
	Discount   int    `json:"discount"`
	Item       Item   `json:"item"`
	Subtotal   int    `json:"subtotal"`
	Tax        int    `json:"tax"`
	Total      int    `json:"total"`
}

LineItem defines model for LineItem.

type Link struct {
	Type LinkType `json:"type"`
	Url  string   `json:"url"`
}

Link defines model for Link.

type LinkType

type LinkType string

LinkType defines model for Link.Type.

const (
	PrivacyPolicy      LinkType = "privacy_policy"
	SellerShopPolicies LinkType = "seller_shop_policies"
	TermsOfUse         LinkType = "terms_of_use"
)

Defines values for LinkType.

type Message

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

Message defines model for CheckoutSessionBase.messages.Item.

func (Message) AsMessageInfo

func (t Message) AsMessageInfo() (MessageInfo, error)

AsMessageInfo returns the union data inside the CheckoutSessionBase_Messages_Item as a MessageInfo

func (*Message) FromMessageInfo

func (t *Message) FromMessageInfo(v MessageInfo) error

FromMessageInfo overwrites any union data inside the CheckoutSessionBase_Messages_Item as the provided MessageInfo

func (Message) MarshalJSON

func (t Message) MarshalJSON() ([]byte, error)

MarshalJSON serializes the underlying union for CheckoutSessionBase_Messages_Item.

func (*Message) MergeMessageInfo

func (t *Message) MergeMessageInfo(v MessageInfo) error

MergeMessageInfo performs a merge with any union data inside the CheckoutSessionBase_Messages_Item, using the provided MessageInfo

func (*Message) UnmarshalJSON

func (t *Message) UnmarshalJSON(b []byte) error

UnmarshalJSON loads union data for CheckoutSessionBase_Messages_Item.

type MessageErrorCode

type MessageErrorCode string

MessageErrorCode defines model for MessageError.Code.

const (
	Invalid         MessageErrorCode = "invalid"
	Missing         MessageErrorCode = "missing"
	OutOfStock      MessageErrorCode = "out_of_stock"
	PaymentDeclined MessageErrorCode = "payment_declined"
	Requires3ds     MessageErrorCode = "requires_3ds"
	RequiresSignIn  MessageErrorCode = "requires_sign_in"
)

Defines values for MessageErrorCode.

type MessageErrorContentType

type MessageErrorContentType string

MessageErrorContentType defines model for MessageError.ContentType.

const (
	MessageErrorContentTypeMarkdown MessageErrorContentType = "markdown"
	MessageErrorContentTypePlain    MessageErrorContentType = "plain"
)

Defines values for MessageErrorContentType.

type MessageInfo

type MessageInfo struct {
	Content     string                 `json:"content"`
	ContentType MessageInfoContentType `json:"content_type"`

	// Param RFC 9535 JSONPath
	Param *string `json:"param,omitempty"`
	Type  string  `json:"type"`
}

MessageInfo defines model for MessageInfo.

type MessageInfoContentType

type MessageInfoContentType string

MessageInfoContentType defines model for MessageInfo.ContentType.

const (
	MessageInfoContentTypeMarkdown MessageInfoContentType = "markdown"
	MessageInfoContentTypePlain    MessageInfoContentType = "plain"
)

Defines values for MessageInfoContentType.

type Middleware

type Middleware func(http.HandlerFunc) http.HandlerFunc

Middleware is an HTTP middleware applied to the ACP handlers.

type Option

type Option func(*config)

Option customizes the handler behavior.

func WithAuthenticator

func WithAuthenticator(auth Authenticator) Option

WithAuthenticator enables Authorization header API key validation.

func WithMaxClockSkew

func WithMaxClockSkew(skew time.Duration) Option

WithMaxClockSkew sets the tolerated absolute difference between the Timestamp header and the server clock when verifying signed requests.

func WithMiddleware

func WithMiddleware(mw ...Middleware) Option

WithMiddleware appends custom middleware in the order provided.

func WithRequireSignedRequests

func WithRequireSignedRequests() Option

WithRequireSignedRequests enforces that every request carries Signature and Timestamp headers when a verifier is configured.

func WithSignatureVerifier

func WithSignatureVerifier(verifier signature.Verifier) Option

WithSignatureVerifier enables canonical JSON signature enforcement.

type Order

type Order struct {
	ID                string `json:"id"`
	CheckoutSessionId string `json:"checkout_session_id"`
	PermalinkUrl      string `json:"permalink_url"`
}

Order defines model for Order.

type OrderCreate

type OrderCreate struct {
	Type              EventDataType `json:"type"`
	CheckoutSessionID string        `json:"checkout_session_id"`
	PermalinkURL      string        `json:"permalink_url"`
	Status            OrderStatus   `json:"status"`
	Refunds           []Refund      `json:"refunds"`
}

OrderCreate emits order data after the order is created.

type OrderStatus

type OrderStatus string

OrderStatus defines model for webhook data status.

const (
	OrderStatusCreated      OrderStatus = "created"
	OrderStatusManualReview OrderStatus = "manual_review"
	OrderStatusConfirmed    OrderStatus = "confirmed"
	OrderStatusCanceled     OrderStatus = "canceled"
	OrderStatusShipped      OrderStatus = "shipped"
	OrderStatusFulfilled    OrderStatus = "fulfilled"
)

type OrderUpdated

type OrderUpdated struct {
	Type              EventDataType `json:"type"`
	CheckoutSessionID string        `json:"checkout_session_id"`
	PermalinkURL      string        `json:"permalink_url"`
	Status            OrderStatus   `json:"status"`
	Refunds           []Refund      `json:"refunds"`
}

OrderUpdated emits order data whenever the order status changes.

type PaymentData

type PaymentData struct {
	BillingAddress *Address            `json:"billing_address,omitempty"`
	Provider       PaymentDataProvider `json:"provider"`
	Token          string              `json:"token"`
}

PaymentData defines model for PaymentData.

type PaymentDataProvider

type PaymentDataProvider string

PaymentDataProvider defines model for PaymentData.Provider.

type PaymentMethodCard

type PaymentMethodCard struct {
	// The type of payment method used. Currently only card.
	Type PaymentMethodCardType `json:"type" validate:"required,eq=card"`
	// The type of card number. Network tokens are preferred with fallback to FPAN. See [PCI Scope] for more details.
	//
	// [PCI Scope]: https://developers.openai.com/commerce/guides/production#security-and-compliance
	CardNumberType CardNumberType `json:"card_number_type" validate:"required,oneof=fpan network_token"`
	// Card number.
	Number secret.Secret[string] `json:"number" validate:"required"`
	// Expiry month.
	ExpMonth *string `json:"exp_month,omitempty" validate:"omitempty,len=2,numeric"`
	// Expiry year.
	ExpYear *string `json:"exp_year,omitempty" validate:"omitempty,len=4,numeric"`
	// Cardholder name.
	Name *string `json:"name,omitempty"`
	// Card CVC number.
	CVC *string `json:"cvc,omitempty" validate:"omitempty,numeric"`
	// In case of non-PAN, this is the original last 4 digits of the card for customer display.
	DisplayLast4 *string `json:"display_last4,omitempty" validate:"omitempty,len=4"`
	// Funding type of the card to display.
	DisplayCardFundingType CardFundingType `json:"display_card_funding_type" validate:"required,oneof=credit debit prepaid"`
	// Brand of the card to display.
	//
	// Exapmple: "Visa", "amex", "discover"
	DisplayBrand *string `json:"display_brand,omitempty"`
	// If the card came via a digital wallet, what type of wallet.
	DisplayWalletType *string `json:"display_wallet_type,omitempty"`
	// Institution Identification Number (aka BIN). The first 6 digits on a card identifying the issuer.
	IIN *string `json:"iin,omitempty" validate:"omitempty,max=6"`
	// Cryptogram provided with network tokens.
	Cryptogram *string `json:"cryptogram,omitempty"`
	// Electronic Commerce Indicator / Security Level Indicator provided with network tokens.
	ECIValue *string `json:"eci_value,omitempty"`
	// Checks already performed on the card.
	ChecksPerformed []CardChecksPerformed `json:"checks_performed,omitempty" validate:"omitempty,dive,required"`
	// Arbitrary key/value pairs.
	Metadata map[string]string `json:"metadata" validate:"required,map_present"`
}

PaymentMethodCard captures the delegated card credential.

type PaymentMethodCardType

type PaymentMethodCardType string
const (
	PaymentMethodCardTypeCard PaymentMethodCardType = "card"
)

type PaymentProvider

type PaymentProvider struct {
	Provider                PaymentProviderProvider   `json:"provider"`
	SupportedPaymentMethods []SupportedPaymentMethods `json:"supported_payment_methods"`
}

PaymentProvider defines model for PaymentProvider.

type PaymentProviderProvider

type PaymentProviderProvider string

PaymentProviderProvider defines model for PaymentProvider.Provider.

type PaymentRequest

type PaymentRequest struct {
	// Type of credential. The only accepted value is "CARD".
	PaymentMethod PaymentMethodCard `json:"payment_method" validate:"required"`
	// Use cases that the stored credential can be applied to.
	Allowance Allowance `json:"allowance" validate:"required"`
	// Address associated with the payment method.
	BillingAddress *Address `json:"billing_address,omitempty" validate:"omitempty"`
	// Arbitrary key/value pairs.
	Metadata map[string]string `json:"metadata" validate:"required,map_present"`
	// List of risk signals.
	RiskSignals []RiskSignal `json:"risk_signals" validate:"required,min=1,dive"`
}

PaymentRequest mirrors the ACP DelegatePaymentRequest payload described in the spec: https://developers.openai.com/commerce/specs/payment.

func (PaymentRequest) Validate

func (r PaymentRequest) Validate() error

Validate ensures the request complies with the ACP Delegate Payment spec by running go-playground/validator rules plus custom constraints.

type Refund

type Refund struct {
	Type   RefundType `json:"type"`
	Amount int        `json:"amount"`
}

Refund describes a refund emitted in webhook events.

type RefundType

type RefundType string

RefundType captures the source of refunded funds.

const (
	RefundTypeStoreCredit     RefundType = "store_credit"
	RefundTypeOriginalPayment RefundType = "original_payment"
)

type RequestContext

type RequestContext struct {
	// API Key used to make requests
	//
	// Example: Bearer api_key_123
	Authorization string
	// The preferred locale for content like messages and errors
	//
	// Example: en-US
	AcceptLanguage string
	// Information about the client making this request
	//
	// Example: ChatGPT/2.0 (Mac OS X 15.0.1; arm64; build 0)
	UserAgent string
	// Key used to ensure requests are idempotent
	//
	// Example: idempotency_key_123
	IdempotencyKey string
	// Unique key for each request for tracing purposes
	//
	// Example: request_id_123
	RequestID string
	// Base64 encoded signature of the request body
	//
	// Example: eyJtZX...
	Signature string
	// Formatted as an RFC 3339 string.
	//
	// Example: 2025-09-25T10:30:00Z
	Timestamp string
	// API version
	//
	// Example: 2025-09-12
	APIVersion string
}

func RequestContextFromContext

func RequestContextFromContext(ctx context.Context) *RequestContext

RequestContextFromContext extracts the HTTP request metadata previously stored in the context.

type RiskSignal

type RiskSignal struct {
	// The type of risk signal.
	Type RiskSignalType `json:"type" validate:"required,oneof=card_testing"`
	// Action taken.
	Action RiskSignalAction `json:"action" validate:"required,oneof=manual_review authorized blocked"`
	// Details of the risk signal.
	Score int `json:"score" validate:"gte=0"`
}

RiskSignal provides PSPs with fraud intelligence references.

type RiskSignalAction

type RiskSignalAction string
const (
	RiskSignalActionManualReview RiskSignalAction = "manual_review"
	RiskSignalActionAuthorized   RiskSignalAction = "authorized"
	RiskSignalActionBlocked      RiskSignalAction = "blocked"
)

type RiskSignalType

type RiskSignalType string
const (
	RiskSignalTypeCardTesting RiskSignalType = "card_testing"
)

type SessionWithOrder

type SessionWithOrder struct {
	CheckoutSession
	Order Order `json:"order"`
}

SessionWithOrder defines model for SessionWithOrder.

type SupportedPaymentMethods

type SupportedPaymentMethods string

SupportedPaymentMethods defines model for PaymentProvider.SupportedPaymentMethods.

const (
	Card SupportedPaymentMethods = "card"
)

Defines values for PaymentProviderSupportedPaymentMethods.

type Total

type Total struct {
	Amount      int       `json:"amount"`
	Description *string   `json:"description,omitempty"`
	DisplayText string    `json:"display_text"`
	Type        TotalType `json:"type"`
}

Total defines model for Total.

type TotalType

type TotalType string

TotalType defines model for Total.Type.

const (
	TotalTypeDiscount        TotalType = "discount"
	TotalTypeFee             TotalType = "fee"
	TotalTypeFulfillment     TotalType = "fulfillment"
	TotalTypeItemsBaseAmount TotalType = "items_base_amount"
	TotalTypeItemsDiscount   TotalType = "items_discount"
	TotalTypeSubtotal        TotalType = "subtotal"
	TotalTypeTax             TotalType = "tax"
	TotalTypeTotal           TotalType = "total"
)

Defines values for TotalType.

type VaultToken

type VaultToken struct {
	// Unique vault token identifier vt_….
	ID string `json:"id" validate:"required"`
	// Time formatted as an RFC 3339 string.
	Created time.Time `json:"created" validate:"required"`
	// Arbitrary key/value pairs for correlation (e.g., source, merchant_id, idempotency_key).
	Metadata map[string]string `json:"metadata" validate:"omitempty"`
}

VaultToken is emitted by PSPs after tokenizing the delegated payment payload.

type WebhookEventType

type WebhookEventType string

WebhookEventType enumerates the supported checkout webhook events.

const (
	WebhookEventTypeOrderCreated WebhookEventType = "order_created"
	WebhookEventTypeOrderUpdated WebhookEventType = "order_updated"
)

type WebhookOption

type WebhookOption func(*webhookSender)

func WebhookWithClient

func WebhookWithClient(client *http.Client) WebhookOption

WebhookWithClient allows overriding the HTTP client used for delivering webhook events.

type WebhookSender

type WebhookSender interface {
	// Send sends webhook to the configured webhook endpoint.
	Send(context.Context, EventData) error
}

WebhookSender is an interface of a webhook delivery implementation.

Directories

Path Synopsis
examples
checkout command

Jump to

Keyboard shortcuts

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