boltgo

package module
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2024 License: GPL-3.0, MIT Imports: 13 Imported by: 0

README

Bolt Go SDK

Summary

Bolt API Reference: A comprehensive Bolt API reference for interacting with Accounts, Payments, Orders and more.

Table of Contents

SDK Installation

To add the SDK as a dependency to your project:

go get github.com/BoltApp/bolt-go

SDK Example Usage

Example
package main

import (
	"context"
	boltgo "github.com/BoltApp/bolt-go"
	"github.com/BoltApp/bolt-go/models/components"
	"log"
)

func main() {
	ctx := context.Background()

	s := boltgo.New(
		boltgo.WithSecurity(components.Security{
			Oauth:  boltgo.String("<YOUR_OAUTH_HERE>"),
			APIKey: boltgo.String("<YOUR_API_KEY_HERE>"),
		}),
	)

	res, err := s.Account.GetDetails(ctx, "<value>", boltgo.String("<value>"))
	if err != nil {
		log.Fatal(err)
	}
	if res.Account != nil {
		// handle response
	}
}

Available Resources and Operations

Available methods
Account
OAuth
Orders
  • OrdersCreate - Create an order that was prepared outside the Bolt ecosystem.
Payments
Payments.Guest
Payments.LoggedIn
Testing

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or an error, they will never return both.

By Default, an API error will return sdkerrors.SDKError. When custom error responses are specified for an operation, the SDK may also return their associated error. You can refer to respective Errors tables in SDK docs for more details on possible error types for each operation.

For example, the GetDetails function may return the following errors:

Error Type Status Code Content Type
sdkerrors.AccountGetResponseBody 4XX application/json
sdkerrors.SDKError 5XX */*
Example
package main

import (
	"context"
	"errors"
	boltgo "github.com/BoltApp/bolt-go"
	"github.com/BoltApp/bolt-go/models/components"
	"github.com/BoltApp/bolt-go/models/sdkerrors"
	"log"
)

func main() {
	ctx := context.Background()

	s := boltgo.New(
		boltgo.WithSecurity(components.Security{
			Oauth:  boltgo.String("<YOUR_OAUTH_HERE>"),
			APIKey: boltgo.String("<YOUR_API_KEY_HERE>"),
		}),
	)

	res, err := s.Account.GetDetails(ctx, "<value>", boltgo.String("<value>"))
	if err != nil {

		var e *sdkerrors.AccountGetResponseBody
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}

		var e *sdkerrors.SDKError
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}
	}
}

Server Selection

Server Variables

The default server https://{environment}.bolt.com/v3 contains variables and is set to https://api-sandbox.bolt.com/v3 by default. To override default values, the following options are available when initializing the SDK client instance:

  • WithEnvironment(environment ServerEnvironment)
Override Server URL Per-Client

The default server can also be overridden globally using the WithServerURL(serverURL string) option when initializing the SDK client instance. For example:

package main

import (
	"context"
	boltgo "github.com/BoltApp/bolt-go"
	"github.com/BoltApp/bolt-go/models/components"
	"log"
)

func main() {
	ctx := context.Background()

	s := boltgo.New(
		boltgo.WithServerURL("https://api-sandbox.bolt.com/v3"),
		boltgo.WithSecurity(components.Security{
			Oauth:  boltgo.String("<YOUR_OAUTH_HERE>"),
			APIKey: boltgo.String("<YOUR_API_KEY_HERE>"),
		}),
	)

	res, err := s.Account.GetDetails(ctx, "<value>", boltgo.String("<value>"))
	if err != nil {
		log.Fatal(err)
	}
	if res.Account != nil {
		// handle response
	}
}

Custom HTTP Client

The Go SDK makes API calls that wrap an internal HTTP client. The requirements for the HTTP client are very simple. It must match this interface:

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

The built-in net/http client satisfies this interface and a default client based on the built-in is provided by default. To replace this default with a client of your own, you can implement this interface yourself or provide your own client configured as desired. Here's a simple example, which adds a client with a 30 second timeout.

import (
	"net/http"
	"time"
	"github.com/myorg/your-go-sdk"
)

var (
	httpClient = &http.Client{Timeout: 30 * time.Second}
	sdkClient  = sdk.New(sdk.WithClient(httpClient))
)

This can be a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration.

Authentication

Per-Client Security Schemes

This SDK supports the following security schemes globally:

Name Type Scheme
Oauth oauth2 OAuth2 token
APIKey apiKey API key

You can set the security parameters through the WithSecurity option when initializing the SDK client instance. The selected scheme will be used by default to authenticate with the API for all operations that support it. For example:

package main

import (
	"context"
	boltgo "github.com/BoltApp/bolt-go"
	"github.com/BoltApp/bolt-go/models/components"
	"log"
)

func main() {
	ctx := context.Background()

	s := boltgo.New(
		boltgo.WithSecurity(components.Security{
			Oauth:  boltgo.String("<YOUR_OAUTH_HERE>"),
			APIKey: boltgo.String("<YOUR_API_KEY_HERE>"),
		}),
	)

	res, err := s.Account.GetDetails(ctx, "<value>", boltgo.String("<value>"))
	if err != nil {
		log.Fatal(err)
	}
	if res.Account != nil {
		// handle response
	}
}

Per-Operation Security Schemes

Some operations in this SDK require the security scheme to be specified at the request level. For example:

package main

import (
	"context"
	boltgo "github.com/BoltApp/bolt-go"
	"github.com/BoltApp/bolt-go/models/components"
	"github.com/BoltApp/bolt-go/models/operations"
	"log"
)

func main() {
	ctx := context.Background()

	s := boltgo.New()

	res, err := s.Payments.Guest.Initialize(ctx, operations.GuestPaymentsInitializeSecurity{
		APIKey: "<YOUR_API_KEY_HERE>",
	}, "<value>", components.GuestPaymentInitializeRequest{
		Profile: components.ProfileCreationData{
			CreateAccount: true,
			FirstName:     "Alice",
			LastName:      "Baker",
			Email:         "alice@example.com",
			Phone:         boltgo.String("+14155550199"),
		},
		Cart: components.Cart{
			OrderReference:   "order_100",
			OrderDescription: boltgo.String("Order #1234567890"),
			DisplayID:        boltgo.String("215614191"),
			Shipments: []components.CartShipment{
				components.CartShipment{
					Address: boltgo.Pointer(components.CreateAddressReferenceInputAddressReferenceExplicitInput(
						components.AddressReferenceExplicitInput{
							DotTag:         components.AddressReferenceExplicitTagExplicit,
							FirstName:      "Alice",
							LastName:       "Baker",
							StreetAddress1: "535 Mission St, Ste 1401",
							Locality:       "San Francisco",
							PostalCode:     "94105",
							Region:         boltgo.String("CA"),
							CountryCode:    components.CountryCodeUs,
						},
					)),
					Cost: &components.Amount{
						Currency: components.CurrencyUsd,
						Units:    10000,
					},
					Carrier: boltgo.String("FedEx"),
				},
			},
			Discounts: []components.CartDiscount{
				components.CartDiscount{
					Amount: components.Amount{
						Currency: components.CurrencyUsd,
						Units:    10000,
					},
					Code:       boltgo.String("SUMMER10DISCOUNT"),
					DetailsURL: boltgo.String("https://www.example.com/SUMMER-SALE"),
				},
			},
			Items: []components.CartItem{
				components.CartItem{
					Name:        "Bolt Swag Bag",
					Reference:   "item_100",
					Description: boltgo.String("Large tote with Bolt logo."),
					TotalAmount: components.Amount{
						Currency: components.CurrencyUsd,
						Units:    9000,
					},
					UnitPrice: 1000,
					Quantity:  9,
					ImageURL:  boltgo.String("https://www.example.com/products/123456/images/1.png"),
				},
			},
			Total: components.Amount{
				Currency: components.CurrencyUsd,
				Units:    9000,
			},
			Tax: components.Amount{
				Currency: components.CurrencyUsd,
				Units:    100,
			},
		},
		PaymentMethod: components.CreatePaymentMethodInputPaymentMethodCreditCardInput(
			components.PaymentMethodCreditCardInput{
				DotTag: components.DotTagCreditCard,
				BillingAddress: components.CreateAddressReferenceInputAddressReferenceExplicitInput(
					components.AddressReferenceExplicitInput{
						DotTag:         components.AddressReferenceExplicitTagExplicit,
						FirstName:      "Alice",
						LastName:       "Baker",
						Company:        boltgo.String("ACME Corporation"),
						StreetAddress1: "535 Mission St, Ste 1401",
						StreetAddress2: boltgo.String("c/o Shipping Department"),
						Locality:       "San Francisco",
						PostalCode:     "94105",
						Region:         boltgo.String("CA"),
						CountryCode:    components.CountryCodeUs,
						Email:          boltgo.String("alice@example.com"),
						Phone:          boltgo.String("+14155550199"),
					},
				),
				Network:    components.CreditCardNetworkVisa,
				Bin:        "411111",
				Last4:      "1004",
				Expiration: "2025-03",
				Token:      "a1B2c3D4e5F6G7H8i9J0k1L2m3N4o5P6Q7r8S9t0",
			},
		),
	}, boltgo.String("<value>"))
	if err != nil {
		log.Fatal(err)
	}
	if res.PaymentResponse != nil {
		// handle response
	}
}

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a retry.Config object to the call by using the WithRetries option:

package main

import (
	"context"
	boltgo "github.com/BoltApp/bolt-go"
	"github.com/BoltApp/bolt-go/models/components"
	"github.com/BoltApp/bolt-go/retry"
	"log"
	"models/operations"
)

func main() {
	ctx := context.Background()

	s := boltgo.New(
		boltgo.WithSecurity(components.Security{
			Oauth:  boltgo.String("<YOUR_OAUTH_HERE>"),
			APIKey: boltgo.String("<YOUR_API_KEY_HERE>"),
		}),
	)

	res, err := s.Account.GetDetails(ctx, "<value>", boltgo.String("<value>"), operations.WithRetries(
		retry.Config{
			Strategy: "backoff",
			Backoff: &retry.BackoffStrategy{
				InitialInterval: 1,
				MaxInterval:     50,
				Exponent:        1.1,
				MaxElapsedTime:  100,
			},
			RetryConnectionErrors: false,
		}))
	if err != nil {
		log.Fatal(err)
	}
	if res.Account != nil {
		// handle response
	}
}

If you'd like to override the default retry strategy for all operations that support retries, you can use the WithRetryConfig option at SDK initialization:

package main

import (
	"context"
	boltgo "github.com/BoltApp/bolt-go"
	"github.com/BoltApp/bolt-go/models/components"
	"github.com/BoltApp/bolt-go/retry"
	"log"
)

func main() {
	ctx := context.Background()

	s := boltgo.New(
		boltgo.WithRetryConfig(
			retry.Config{
				Strategy: "backoff",
				Backoff: &retry.BackoffStrategy{
					InitialInterval: 1,
					MaxInterval:     50,
					Exponent:        1.1,
					MaxElapsedTime:  100,
				},
				RetryConnectionErrors: false,
			}),
		boltgo.WithSecurity(components.Security{
			Oauth:  boltgo.String("<YOUR_OAUTH_HERE>"),
			APIKey: boltgo.String("<YOUR_API_KEY_HERE>"),
		}),
	)

	res, err := s.Account.GetDetails(ctx, "<value>", boltgo.String("<value>"))
	if err != nil {
		log.Fatal(err)
	}
	if res.Account != nil {
		// handle response
	}
}

Development

Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.

Contributions

While we value open-source contributions to this SDK, this library is generated programmatically. Feel free to open a PR or a Github issue as a proof of concept and we'll do our best to include it in a future release!

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ServerList = []string{
	"https://{environment}.bolt.com/v3",
}

ServerList contains the list of servers available to the SDK

Functions

func Bool

func Bool(b bool) *bool

Bool provides a helper function to return a pointer to a bool

func Float32

func Float32(f float32) *float32

Float32 provides a helper function to return a pointer to a float32

func Float64

func Float64(f float64) *float64

Float64 provides a helper function to return a pointer to a float64

func Int

func Int(i int) *int

Int provides a helper function to return a pointer to an int

func Int64

func Int64(i int64) *int64

Int64 provides a helper function to return a pointer to an int64

func Pointer added in v1.4.1

func Pointer[T any](v T) *T

Pointer provides a helper function to return a pointer to a type

func String

func String(s string) *string

String provides a helper function to return a pointer to a string

Types

type Account

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

Account - Use the Accounts API to access shoppers' accounts to empower your checkout and facilitate shoppers' choices.

func (*Account) AddAddress

func (s *Account) AddAddress(ctx context.Context, xPublishableKey string, addressListing components.AddressListingInput, xMerchantClientID *string, opts ...operations.Option) (*operations.AccountAddressCreateResponse, error)

AddAddress - Add an address Add an address to the shopper's account

func (*Account) AddPaymentMethod

func (s *Account) AddPaymentMethod(ctx context.Context, xPublishableKey string, paymentMethod components.PaymentMethodInput, xMerchantClientID *string, opts ...operations.Option) (*operations.AccountAddPaymentMethodResponse, error)

AddPaymentMethod - Add a payment method Add a payment method to a shopper's Bolt Account Wallet. For security purposes, this request must come from your backend. <br/> **Note**: Before using this API, the credit card details must be tokenized by Bolt's credit card tokenization service. Please review our [Bolt Payment Field Component](https://help.bolt.com/products/ignite/api-implementation/#enhance-payments) or [Install the Bolt Tokenizer](https://help.bolt.com/developers/references/bolt-tokenizer) documentation.

func (*Account) DeleteAddress

func (s *Account) DeleteAddress(ctx context.Context, id string, xPublishableKey string, xMerchantClientID *string, opts ...operations.Option) (*operations.AccountAddressDeleteResponse, error)

DeleteAddress - Delete an existing address Delete an existing address. Deleting an address does not invalidate or remove the address from transactions or shipments that are associated with it.

func (*Account) DeletePaymentMethod

func (s *Account) DeletePaymentMethod(ctx context.Context, id string, xPublishableKey string, xMerchantClientID *string, opts ...operations.Option) (*operations.AccountPaymentMethodDeleteResponse, error)

DeletePaymentMethod - Delete an existing payment method Delete an existing payment method. Deleting a payment method does not invalidate or remove it from transactions or orders that are associated with it.

func (*Account) GetDetails

func (s *Account) GetDetails(ctx context.Context, xPublishableKey string, xMerchantClientID *string, opts ...operations.Option) (*operations.AccountGetResponse, error)

GetDetails - Retrieve account details Retrieve a shopper's account details, such as addresses and payment information. The account's details are filtered to be relevant to your merchant account, and some fields may be missing for some accounts. See the schema for details.

func (*Account) UpdateAddress

func (s *Account) UpdateAddress(ctx context.Context, id string, xPublishableKey string, addressListing components.AddressListingInput, xMerchantClientID *string, opts ...operations.Option) (*operations.AccountAddressEditResponse, error)

UpdateAddress - Edit an existing address Edit an existing address on the shopper's account. This does not edit addresses that are already associated with other resources, such as transactions or shipments.

type BoltSDK added in v1.0.1

type BoltSDK struct {
	// Use the Accounts API to access shoppers' accounts to empower your checkout and facilitate shoppers' choices.
	Account  *Account
	Payments *Payments
	// Use the Orders API to create and manage orders, including orders that have been placed outside the Bolt ecosystem.
	Orders *Orders
	// Use the OAuth API to enable your ecommerce server to make API calls on behalf of a Bolt logged-in shopper.
	//
	// https://help.bolt.com/products/accounts/direct-api/oauth-guide/
	OAuth *OAuth
	// Use the Testing API to generate and retrieve test data to verify a subset of flows in non-production environments.
	Testing *Testing
	// contains filtered or unexported fields
}

BoltSDK - Bolt API Reference: A comprehensive Bolt API reference for interacting with Accounts, Payments, Orders and more.

func New

func New(opts ...SDKOption) *BoltSDK

New creates a new instance of the SDK with the provided options

type Guest

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

func (*Guest) Initialize

func (s *Guest) Initialize(ctx context.Context, security operations.GuestPaymentsInitializeSecurity, xPublishableKey string, guestPaymentInitializeRequest components.GuestPaymentInitializeRequest, xMerchantClientID *string, opts ...operations.Option) (*operations.GuestPaymentsInitializeResponse, error)

Initialize a Bolt payment for guest shoppers Initialize a Bolt guest shopper's intent to pay for a cart, using the specified payment method. Payments must be finalized before indicating the payment result to the shopper. Some payment methods will finalize automatically after initialization. For these payments, they will transition directly to "finalized" and the response from Initialize Payment will contain a finalized payment.

func (*Guest) PerformAction

func (s *Guest) PerformAction(ctx context.Context, security operations.GuestPaymentsActionSecurity, id string, xPublishableKey string, paymentActionRequest components.PaymentActionRequest, xMerchantClientID *string, opts ...operations.Option) (*operations.GuestPaymentsActionResponse, error)

PerformAction - Finalize a pending guest payment Finalize a pending payment being made by a Bolt guest shopper. Upon receipt of a finalized payment result, payment success should be communicated to the shopper.

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient provides an interface for suplying the SDK with a custom HTTP client

type LoggedIn

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

func (*LoggedIn) Initialize

func (s *LoggedIn) Initialize(ctx context.Context, xPublishableKey string, paymentInitializeRequest components.PaymentInitializeRequest, xMerchantClientID *string, opts ...operations.Option) (*operations.PaymentsInitializeResponse, error)

Initialize a Bolt payment for logged in shoppers Initialize a Bolt logged-in shopper's intent to pay for a cart, using the specified payment method. Payments must be finalized before indicating the payment result to the shopper. Some payment methods will finalize automatically after initialization. For these payments, they will transition directly to "finalized" and the response from Initialize Payment will contain a finalized payment.

func (*LoggedIn) PerformAction

func (s *LoggedIn) PerformAction(ctx context.Context, id string, xPublishableKey string, paymentActionRequest components.PaymentActionRequest, xMerchantClientID *string, opts ...operations.Option) (*operations.PaymentsActionResponse, error)

PerformAction - Finalize a pending payment Finalize a pending payment being made by a Bolt logged-in shopper. Upon receipt of a finalized payment result, payment success should be communicated to the shopper.

type OAuth

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

OAuth - Use the OAuth API to enable your ecommerce server to make API calls on behalf of a Bolt logged-in shopper.

https://help.bolt.com/products/accounts/direct-api/oauth-guide/

func (*OAuth) GetToken

func (s *OAuth) GetToken(ctx context.Context, tokenRequest components.TokenRequest, xMerchantClientID *string, opts ...operations.Option) (*operations.OauthGetTokenResponse, error)

GetToken - Get OAuth token Retrieve a new or refresh an existing OAuth token.

type Orders

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

Orders - Use the Orders API to create and manage orders, including orders that have been placed outside the Bolt ecosystem.

func (*Orders) OrdersCreate

func (s *Orders) OrdersCreate(ctx context.Context, security operations.OrdersCreateSecurity, xPublishableKey string, order components.Order, xMerchantClientID *string, opts ...operations.Option) (*operations.OrdersCreateResponse, error)

OrdersCreate - Create an order that was prepared outside the Bolt ecosystem. Create an order that was prepared outside the Bolt ecosystem. Some Bolt-powered flows automatically manage order creation - in those flows the order ID will be provided separately and not through this API.

type Payments

type Payments struct {
	LoggedIn *LoggedIn
	Guest    *Guest
	// contains filtered or unexported fields
}

type SDKOption

type SDKOption func(*BoltSDK)

func WithClient

func WithClient(client HTTPClient) SDKOption

WithClient allows the overriding of the default HTTP client used by the SDK

func WithEnvironment

func WithEnvironment(environment ServerEnvironment) SDKOption

WithEnvironment allows setting the environment variable for url substitution

func WithRetryConfig

func WithRetryConfig(retryConfig retry.Config) SDKOption

func WithSecurity

func WithSecurity(security components.Security) SDKOption

WithSecurity configures the SDK to use the provided security details

func WithSecuritySource

func WithSecuritySource(security func(context.Context) (components.Security, error)) SDKOption

WithSecuritySource configures the SDK to invoke the Security Source function on each method call to determine authentication

func WithServerIndex

func WithServerIndex(serverIndex int) SDKOption

WithServerIndex allows the overriding of the default server by index

func WithServerURL

func WithServerURL(serverURL string) SDKOption

WithServerURL allows the overriding of the default server URL

func WithTemplatedServerURL

func WithTemplatedServerURL(serverURL string, params map[string]string) SDKOption

WithTemplatedServerURL allows the overriding of the default server URL with a templated URL populated with the provided parameters

func WithTimeout added in v1.1.0

func WithTimeout(timeout time.Duration) SDKOption

WithTimeout Optional request timeout applied to each operation

type ServerEnvironment

type ServerEnvironment string
const (
	ServerEnvironmentAPI        ServerEnvironment = "api"
	ServerEnvironmentAPISandbox ServerEnvironment = "api-sandbox"
)

func (ServerEnvironment) ToPointer

func (e ServerEnvironment) ToPointer() *ServerEnvironment

func (*ServerEnvironment) UnmarshalJSON

func (e *ServerEnvironment) UnmarshalJSON(data []byte) error

type Testing

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

Testing - Use the Testing API to generate and retrieve test data to verify a subset of flows in non-production environments.

func (*Testing) CreateAccount

func (s *Testing) CreateAccount(ctx context.Context, security operations.TestingAccountCreateSecurity, xPublishableKey string, accountTestCreationData components.AccountTestCreationData, opts ...operations.Option) (*operations.TestingAccountCreateResponse, error)

CreateAccount - Create a test account Create a Bolt shopper account for testing purposes.

func (*Testing) GetCreditCard

GetCreditCard - Retrieve a tokenized test credit card Retrieve a test credit card that can be used to process payments in your Bolt testing environment. The response includes the card's Bolt credit card token.

func (*Testing) TestingAccountPhoneGet added in v0.4.2

func (s *Testing) TestingAccountPhoneGet(ctx context.Context, security operations.TestingAccountPhoneGetSecurity, xPublishableKey string, opts ...operations.Option) (*operations.TestingAccountPhoneGetResponse, error)

TestingAccountPhoneGet - Get a random phone number Get a random, fictitious phone number that is not assigned to any existing Bolt account.

Directories

Path Synopsis
internal
models

Jump to

Keyboard shortcuts

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