Skip to content

gr4vy/gr4vy-go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

94 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Gr4vy Go SDK (Beta)

Developer-friendly & type-safe Go SDK specifically catered to leverage the Gr4vy API.

GitHub Tag



Important

This is a Beta release of our latest SDK. Please refer to the legacy Go SDK for the latest stable build.

Summary

Gr4vy Go SDK

The official Gr4vy SDK for Go provides a convenient way to interact with the Gr4vy API from your server-side application. This SDK allows you to seamlessly integrate Gr4vy's powerful payment orchestration capabilities, including:

  • Creating Transactions: Initiate and process payments with various payment methods and services.
  • Managing Buyers: Store and manage buyer information securely.
  • Storing Payment Methods: Securely store and tokenize payment methods for future use.
  • Handling Webhooks: Easily process and respond to webhook events from Gr4vy.
  • And much more: Access the full suite of Gr4vy API payment features.

This SDK is designed to simplify development, reduce boilerplate code, and help you get up and running with Gr4vy quickly and efficiently. It handles authentication, request signing, and provides easy-to-use methods for most API endpoints.

Table of Contents

SDK Installation

To add the SDK as a dependency to your project:

go get github.com/gr4vy/gr4vy-go

SDK Example Usage

Example

package main

import (
	"context"
	gr4vy "github.com/gr4vy/gr4vy-go"
	"github.com/gr4vy/gr4vy-go/models/operations"
	"log"
	"os"
)

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

	privateKey := "...." // Private key loaded from disk or env var
	withToken := gr4vy.WithToken(privateKey, []JWTScope{ReadAll, WriteAll}, 60)

	s := gr4vy.New(
		gr4vy.WithID("example"),
		gr4vy.WithServer(gr4vy.ServerSandbox),
		gr4vy.WithSecuritySource(withToken),
		gr4vy.WithMerchantAccountID("default"),
	)

	res, err := s.Transactions.List(ctx, operations.ListTransactionsRequest{}, nil, nil)
	if err != nil {
		log.Fatal(err)
	}
	if res != nil {
		// handle response
	}
}



Important

Please use WithToken where the documentation mentions os.Getenv("GR4VY_BEARER_AUTH").

Bearer token generation

Alternatively, you can create a token for use with the SDK or with your own client library.

import (
	gr4vy "github.com/gr4vy/gr4vy-go"
	"log"
	"os"
)

privateKey := "...." // Private key loaded from disk or env var

token, err := GetToken(privateKey, []JWTScope{ReadAll, WriteAll}, 5)
if err != nil {
	log.Fatal(err)
}

Note: This will only create a token once. Use WithToken to dynamically generate a token for every request.

Embed token generation

Alternatively, you can create a token for use with Embed as follows.

import (
	gr4vy "github.com/gr4vy/gr4vy-go"
	"log"
	"os"
)

privateKey := "...." // Private key loaded from disk or env var

token, err := GetEmbedToken(privateKey, nil, "")
if err != nil {
	log.Fatal(err)
}

Note: This will only create a token once. Use withToken to dynamically generate a token for every request.

Merchant account ID selection

Depending on the key used, you might need to explicitly define a merchant account ID to use. In our API, this uses the X-GR4VY-MERCHANT-ACCOUNT-ID header. When using the SDK, you can set the merchantAccountId on every request.

s := gr4vy.New(
	gr4vy.WithID("example"),
	gr4vy.WithServer(gr4vy.ServerSandbox),
	gr4vy.WithSecuritySource(withToken),
	gr4vy.WithMerchantAccountID("my-merchant-id"),
)

Webhooks verification

The SDK provides a VerifyWebhook method to validate incoming webhook requests from Gr4vy. This ensures that the webhook payload is authentic and has not been tampered with.

import (
  "log"
  gr4vy "github.com/gr4vy/gr4vy-go"
)

func main() {
  secret := "your_webhook_secret"
  payload := "webhook_payload"
  signatureHeader := "signature_from_header"
  timestampHeader := "timestamp_from_header"
  timestampTolerance := 300 // Optional: Tolerance in seconds for timestamp validation

  err := gr4vy.VerifyWebhook(secret, payload, &signatureHeader, &timestampHeader, timestampTolerance)
  if err != nil {
    log.Fatal(err)
  }
}

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme Environment Variable
BearerAuth http HTTP Bearer GR4VY_BEARER_AUTH

You can configure it using the WithSecurity option when initializing the SDK client instance. For example:

package main

import (
	"context"
	gr4vygo "github.com/gr4vy/gr4vy-go"
	"github.com/gr4vy/gr4vy-go/models/components"
	"log"
	"os"
)

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

	s := gr4vygo.New(
		gr4vygo.WithSecurity(os.Getenv("GR4VY_BEARER_AUTH")),
	)

	res, err := s.AccountUpdater.Jobs.Create(ctx, components.AccountUpdaterJobCreate{
		PaymentMethodIds: []string{
			"ef9496d8-53a5-4aad-8ca2-00eb68334389",
			"f29e886e-93cc-4714-b4a3-12b7a718e595",
		},
	}, nil)
	if err != nil {
		log.Fatal(err)
	}
	if res != nil {
		// handle response
	}
}

Available Resources and Operations

Available methods
  • Create - Create account updater job
  • List - List audit log entries
  • List - List gift cards for a buyer
  • List - List payment methods for a buyer
  • Create - Add buyer shipping details
  • List - List a buyer's shipping details
  • Get - Get buyer shipping details
  • Update - Update a buyer's shipping details
  • Delete - Delete a buyer's shipping details
  • List - List card scheme definitions
  • Create - Create checkout session
  • Update - Update checkout session
  • Get - Get checkout session
  • Delete - Delete checkout session
  • Create - Register digital wallet
  • List - List digital wallets
  • Get - Get digital wallet
  • Delete - Delete digital wallet
  • Update - Update digital wallet
  • Create - Register a digital wallet domain
  • Delete - Remove a digital wallet domain
  • Get - Get gift card
  • Delete - Delete a gift card
  • Create - Create gift card
  • List - List gift cards
  • List - List gift card balances
  • List - List all merchant accounts
  • Create - Create a merchant account
  • Get - Get a merchant account
  • Update - Update a merchant account
  • List - List all payment methods
  • Create - Create payment method
  • Get - Get payment method
  • Delete - Delete payment method
  • List - List network tokens
  • Create - Provision network token
  • Suspend - Suspend network token
  • Resume - Resume network token
  • Delete - Delete network token
  • Create - Provision network token cryptogram
  • List - List payment service tokens
  • Create - Create payment service token
  • Delete - Delete payment service token
  • List - List payment options
  • List - List payment service definitions
  • Get - Get a payment service definition
  • Session - Create a session for apayment service definition
  • List - List payment services
  • Create - Update a configured payment service
  • Get - Get payment service
  • Update - Configure a payment service
  • Delete - Delete a configured payment service
  • Verify - Verify payment service credentials
  • Session - Create a session for apayment service definition
  • List - List payouts created.
  • Create - Create a payout.
  • Get - Get a payout.
  • Get - Get refund
  • List - List transactions
  • Create - Create transaction
  • Get - Get transaction
  • Capture - Capture transaction
  • Void - Void transaction
  • Sync - Sync transaction
  • List - List transaction events
  • List - List transaction refunds
  • Create - Create transaction refund
  • Get - Get transaction refund
  • Create - Create batch transaction refund

Pagination

Some of the endpoints in this SDK support pagination. To use pagination, you make your SDK calls as usual, but the returned response object will have a Next method that can be called to pull down the next group of results. If the return value of Next is nil, then there are no more pages to be fetched.

Here's an example of one such pagination call:

package main

import (
	"context"
	gr4vygo "github.com/gr4vy/gr4vy-go"
	"github.com/gr4vy/gr4vy-go/models/operations"
	"log"
	"os"
)

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

	s := gr4vygo.New(
		gr4vygo.WithSecurity(os.Getenv("GR4VY_BEARER_AUTH")),
	)

	res, err := s.Buyers.List(ctx, operations.ListBuyersRequest{
		Cursor:             gr4vygo.String("ZXhhbXBsZTE"),
		Search:             gr4vygo.String("John"),
		ExternalIdentifier: gr4vygo.String("buyer-12345"),
	})
	if err != nil {
		log.Fatal(err)
	}
	if res != nil {
		for {
			// handle items

			res, err = res.Next()

			if err != nil {
				// handle error
			}

			if res == nil {
				break
			}
		}
	}
}

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"
	gr4vygo "github.com/gr4vy/gr4vy-go"
	"github.com/gr4vy/gr4vy-go/models/components"
	"github.com/gr4vy/gr4vy-go/retry"
	"log"
	"models/operations"
	"os"
)

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

	s := gr4vygo.New(
		gr4vygo.WithSecurity(os.Getenv("GR4VY_BEARER_AUTH")),
	)

	res, err := s.AccountUpdater.Jobs.Create(ctx, components.AccountUpdaterJobCreate{
		PaymentMethodIds: []string{
			"ef9496d8-53a5-4aad-8ca2-00eb68334389",
			"f29e886e-93cc-4714-b4a3-12b7a718e595",
		},
	}, nil, 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 != 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"
	gr4vygo "github.com/gr4vy/gr4vy-go"
	"github.com/gr4vy/gr4vy-go/models/components"
	"github.com/gr4vy/gr4vy-go/retry"
	"log"
	"os"
)

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

	s := gr4vygo.New(
		gr4vygo.WithRetryConfig(
			retry.Config{
				Strategy: "backoff",
				Backoff: &retry.BackoffStrategy{
					InitialInterval: 1,
					MaxInterval:     50,
					Exponent:        1.1,
					MaxElapsedTime:  100,
				},
				RetryConnectionErrors: false,
			}),
		gr4vygo.WithSecurity(os.Getenv("GR4VY_BEARER_AUTH")),
	)

	res, err := s.AccountUpdater.Jobs.Create(ctx, components.AccountUpdaterJobCreate{
		PaymentMethodIds: []string{
			"ef9496d8-53a5-4aad-8ca2-00eb68334389",
			"f29e886e-93cc-4714-b4a3-12b7a718e595",
		},
	}, nil)
	if err != nil {
		log.Fatal(err)
	}
	if res != nil {
		// handle response
	}
}

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 apierrors.APIError. 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 Create function may return the following errors:

Error Type Status Code Content Type
apierrors.Error400 400 application/json
apierrors.Error401 401 application/json
apierrors.Error403 403 application/json
apierrors.Error404 404 application/json
apierrors.Error405 405 application/json
apierrors.Error409 409 application/json
apierrors.HTTPValidationError 422 application/json
apierrors.Error425 425 application/json
apierrors.Error429 429 application/json
apierrors.Error500 500 application/json
apierrors.Error502 502 application/json
apierrors.Error504 504 application/json
apierrors.APIError 4XX, 5XX */*

Example

package main

import (
	"context"
	"errors"
	gr4vygo "github.com/gr4vy/gr4vy-go"
	"github.com/gr4vy/gr4vy-go/models/apierrors"
	"github.com/gr4vy/gr4vy-go/models/components"
	"log"
	"os"
)

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

	s := gr4vygo.New(
		gr4vygo.WithSecurity(os.Getenv("GR4VY_BEARER_AUTH")),
	)

	res, err := s.AccountUpdater.Jobs.Create(ctx, components.AccountUpdaterJobCreate{
		PaymentMethodIds: []string{
			"ef9496d8-53a5-4aad-8ca2-00eb68334389",
			"f29e886e-93cc-4714-b4a3-12b7a718e595",
		},
	}, nil)
	if err != nil {

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

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

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

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

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

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

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

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

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

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

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

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

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

Server Selection

Select Server by Name

You can override the default server globally using the WithServer(server string) option when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:

Name Server Variables Description
production https://api.{id}.gr4vy.app id
sandbox https://api.sandbox.{id}.gr4vy.app id

If the selected server has variables, you may override its default values using the associated option(s):

Variable Option Default Description
id WithID(id string) "example" The subdomain for your Gr4vy instance.

Example

package main

import (
	"context"
	gr4vygo "github.com/gr4vy/gr4vy-go"
	"github.com/gr4vy/gr4vy-go/models/components"
	"log"
	"os"
)

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

	s := gr4vygo.New(
		gr4vygo.WithServer("sandbox"),
		gr4vygo.WithID("<id>"),
		gr4vygo.WithSecurity(os.Getenv("GR4VY_BEARER_AUTH")),
	)

	res, err := s.AccountUpdater.Jobs.Create(ctx, components.AccountUpdaterJobCreate{
		PaymentMethodIds: []string{
			"ef9496d8-53a5-4aad-8ca2-00eb68334389",
			"f29e886e-93cc-4714-b4a3-12b7a718e595",
		},
	}, nil)
	if err != nil {
		log.Fatal(err)
	}
	if res != nil {
		// handle response
	}
}

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"
	gr4vygo "github.com/gr4vy/gr4vy-go"
	"github.com/gr4vy/gr4vy-go/models/components"
	"log"
	"os"
)

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

	s := gr4vygo.New(
		gr4vygo.WithServerURL("https://api.example.gr4vy.app"),
		gr4vygo.WithSecurity(os.Getenv("GR4VY_BEARER_AUTH")),
	)

	res, err := s.AccountUpdater.Jobs.Create(ctx, components.AccountUpdaterJobCreate{
		PaymentMethodIds: []string{
			"ef9496d8-53a5-4aad-8ca2-00eb68334389",
			"f29e886e-93cc-4714-b4a3-12b7a718e595",
		},
	}, nil)
	if err != nil {
		log.Fatal(err)
	}
	if res != nil {
		// handle response
	}
}

Timeouts

The GO SDK supports custom timeouts for the API requests. This timeout can be set globally or per request. To set it globally, pass the WithTimeout function to the SDK constructor.

s := gr4vy.New(
	gr4vy.WithID("example"),
	gr4vy.WithServer(gr4vy.ServerSandbox),
	gr4vy.WithSecuritySource(withToken),
	gr4vy.WithMerchantAccountID("default"),
	// 5 second timeout
	gr4vy.WithTimeout(time.Duration(5*time.Second))
)

Alternatively, the timeout can be set for every API request.

_, err = merchantClient.PaymentServices.Create(ctx, paymentServiceCreate, &merchantAccountID,
	operations.WithOperationTimeout(time.Duration(5*time.Second)),
)

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.

Special Types

This SDK defines the following custom types to assist with marshalling and unmarshalling data.

Date

types.Date is a wrapper around time.Time that allows for JSON marshaling a date string formatted as "2006-01-02".

Usage

d1 := types.NewDate(time.Now()) // returns *types.Date

d2 := types.DateFromTime(time.Now()) // returns types.Date

d3, err := types.NewDateFromString("2019-01-01") // returns *types.Date, error

d4, err := types.DateFromString("2019-01-01") // returns types.Date, error

d5 := types.MustNewDateFromString("2019-01-01") // returns *types.Date and panics on error

d6 := types.MustDateFromString("2019-01-01") // returns types.Date and panics on error

Development

Testing

To run the tests, install Go and run the following.

go install
go test -v

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. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.

SDK Created by Speakeasy