Skip to content

gr4vy/gr4vy-csharp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

34 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Gr4vy C# SDK (Beta)

Developer-friendly & type-safe C# SDK specifically catered to leverage Gr4vy API.

NuGet Version

Summary

Gr4vy C# SDK

The official Gr4vy SDK for C# 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

NuGet

To add the NuGet package to a .NET project:

dotnet add package Gr4vy

Locally

To add a reference to a local instance of the SDK in a .NET project:

dotnet add reference src/Gr4vy/Gr4vy.csproj

SDK Example Usage

Example

using Gr4vy;
using Gr4vy.Models.Components;
using System.Collections.Generic;

// Loaded the key from a file, env variable, 
// or anywhere else
var privateKey = "..."; 

var sdk = new Gr4vySDK(
    id: "example",
    server: SDKConfig.Server.Sandbox,
    bearerAuthSource: Auth.WithToken(privateKey),
    merchantAccountId: "default"
);

var res = await sdk.Transactions.ListAsync();

// handle response



Important

Please use bearerAuthSource: Auth.WithToken() where the documentation mentions bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",.

Bearer token generation

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

using Gr4vy;

var token = Auth.GetToken(privateKey),

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

Embed token generation

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

using Gr4vy;

// Loaded the key from a file, env variable, 
// or anywhere else
var privateKey = "..."; 

var sdk = new Gr4vySDK(
    id: "example",
    server: SDKConfig.Server.Sandbox,
    bearerAuthSource: Auth.WithToken(privateKey),
    merchantAccountId: "default"
);

var checkoutSession = await sdk.CheckoutSessions.CreateAsync()

auth.get_embed_token(
    privatekey,
    embedParams=new Dictionary<string, object>
    {
        ["amount"]: 1299,
        ["currency"]: 'USD',
        ["buyer_external_identifier"]: 'user-1234',
    },
    checkoutSessionId=checkoutSession.ID
)

Note: This will only create a token once. Use Auth.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 when initializing the SDK.

var sdk = new Gr4vySDK(
    id: "example",
    server: SDKConfig.Server.Sandbox,
    bearerAuthSource: Auth.WithToken(privateKey),
    merchantAccountId: "my-merchant-id"
);

Webhooks verification

The SDK makes it easy to verify that incoming webhooks were actually sent by Gr4vy. Once you have configured the webhook subscription with its corresponding secret, that can be verified the following way:

using Gr4vy;

// Webhook payload and headers
string payload = "your-webhook-payload";
string secret = "your-webhook-secret";
string signatureHeader = "signatures-from-header";
string timestampHeader = "timestamp-from-header";
int timestampTolerance = 300; // optional, in seconds (default: 0)

try {
    Webhooks.Verify(Payload, Secret, signatureHeader, timestampHeader, timestampTolerance);
    
}
catch(ArgumentException ex) {
    // handle the exception
}

Parameters

  • payload: The raw payload string received in the webhook request.
  • secret: The secret used to sign the webhook. This is provided in your Gr4vy dashboard.
  • signatureHeader: The X-Gr4vy-Signature header from the webhook request.
  • timestampHeader: The X-Gr4vy-Timestamp header from the webhook request.
  • timestampTolerance: (Optional) The maximum allowed difference (in seconds) between the current time and the timestamp in the webhook. Defaults to 0 (no tolerance).

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
  • Summary - Get transaction summary
  • Sync - Sync transaction
  • List - List transaction refunds
  • Create - Create transaction refund
  • Get - Get transaction refund
  • Create - Create batch transaction refund

Global Parameters

A parameter is configured globally. This parameter may be set on the SDK client instance itself during initialization. When configured as an option during SDK initialization, This global value will be used as the default on the operations that use it. When such operations are called, there is a place in each to override the global value, if needed.

For example, you can set merchant_account_id to "default" at SDK initialization and then you do not have to pass the same value on calls to operations like Get. But if you want to do so you may, which will locally override the global setting. See the example code below for a demonstration.

Available Globals

The following global parameter is available.

Name Type Description
merchantAccountId string The ID of the merchant account to use for this request.

Example

using Gr4vy;
using Gr4vy.Models.Components;

var sdk = new Gr4vySDK(
    bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
    merchantAccountId: "default"
);

var res = await sdk.MerchantAccounts.GetAsync(merchantAccountId: "merchant-12345");

// handle response

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 null, then there are no more pages to be fetched.

Here's an example of one such pagination call:

using Gr4vy;
using Gr4vy.Models.Components;
using Gr4vy.Models.Requests;

var sdk = new Gr4vySDK(
    bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
    merchantAccountId: "default"
);

ListBuyersRequest req = new ListBuyersRequest() {
    Cursor = "ZXhhbXBsZTE",
    Search = "John",
    ExternalIdentifier = "buyer-12345",
};

ListBuyersResponse? res = await sdk.Buyers.ListAsync(req);

while(res != null)
{
    // handle items

    res = await res.Next!();
}

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 pass a RetryConfig to the call:

using Gr4vy;
using Gr4vy.Models.Components;
using Gr4vy.Models.Requests;

var sdk = new Gr4vySDK(
    bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
    merchantAccountId: "default"
);

ListBuyersRequest req = new ListBuyersRequest() {
    Cursor = "ZXhhbXBsZTE",
    Search = "John",
    ExternalIdentifier = "buyer-12345",
};

ListBuyersResponse? res = await sdk.Buyers.ListAsync(
    retryConfig: new RetryConfig(
        strategy: RetryConfig.RetryStrategy.BACKOFF,
        backoff: new BackoffStrategy(
            initialIntervalMs: 1L,
            maxIntervalMs: 50L,
            maxElapsedTimeMs: 100L,
            exponent: 1.1
        ),
        retryConnectionErrors: false
    ),
    request: req
);

while(res != null)
{
    // handle items

    res = await res.Next!();
}

If you'd like to override the default retry strategy for all operations that support retries, you can use the RetryConfig optional parameter when intitializing the SDK:

using Gr4vy;
using Gr4vy.Models.Components;
using Gr4vy.Models.Requests;

var sdk = new Gr4vySDK(
    retryConfig: new RetryConfig(
        strategy: RetryConfig.RetryStrategy.BACKOFF,
        backoff: new BackoffStrategy(
            initialIntervalMs: 1L,
            maxIntervalMs: 50L,
            maxElapsedTimeMs: 100L,
            exponent: 1.1
        ),
        retryConnectionErrors: false
    ),
    bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
    merchantAccountId: "default"
);

ListBuyersRequest req = new ListBuyersRequest() {
    Cursor = "ZXhhbXBsZTE",
    Search = "John",
    ExternalIdentifier = "buyer-12345",
};

ListBuyersResponse? res = await sdk.Buyers.ListAsync(req);

while(res != null)
{
    // handle items

    res = await res.Next!();
}

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or throw an exception.

By default, an API error will raise a Gr4vy.Models.Errors.APIException exception, which has the following properties:

Property Type Description
Message string The error message
StatusCode int The HTTP status code
RawResponse HttpResponseMessage The raw HTTP response
Body string The response content

When custom error responses are specified for an operation, the SDK may also throw their associated exceptions. You can refer to respective Errors tables in SDK docs for more details on possible exception types for each operation. For example, the CreateAsync method throws the following exceptions:

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

Example

using Gr4vy;
using Gr4vy.Models.Components;
using Gr4vy.Models.Errors;
using System.Collections.Generic;

var sdk = new Gr4vySDK(
    bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
    merchantAccountId: "default"
);

try
{
    var res = await sdk.AccountUpdater.Jobs.CreateAsync(
        accountUpdaterJobCreate: new AccountUpdaterJobCreate() {
            PaymentMethodIds = new List<string>() {
                "ef9496d8-53a5-4aad-8ca2-00eb68334389",
                "f29e886e-93cc-4714-b4a3-12b7a718e595",
            },
        },
        timeoutInSeconds: 1D,
        merchantAccountId: "default"
    );

    // handle response
}
catch (Exception ex)
{
    if (ex is Error400)
    {
        // Handle exception data
        throw;
    }
    else if (ex is Error401)
    {
        // Handle exception data
        throw;
    }
    else if (ex is Error403)
    {
        // Handle exception data
        throw;
    }
    else if (ex is Error404)
    {
        // Handle exception data
        throw;
    }
    else if (ex is Error405)
    {
        // Handle exception data
        throw;
    }
    else if (ex is Error409)
    {
        // Handle exception data
        throw;
    }
    else if (ex is HTTPValidationError)
    {
        // Handle exception data
        throw;
    }
    else if (ex is Error425)
    {
        // Handle exception data
        throw;
    }
    else if (ex is Error429)
    {
        // Handle exception data
        throw;
    }
    else if (ex is Error500)
    {
        // Handle exception data
        throw;
    }
    else if (ex is Error502)
    {
        // Handle exception data
        throw;
    }
    else if (ex is Error504)
    {
        // Handle exception data
        throw;
    }
    else if (ex is Gr4vy.Models.Errors.APIException)
    {
        // Handle default exception
        throw;
    }
}

Server Selection

Select Server by Name

You can override the default server globally by passing a server name to the server: string optional parameter 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 through the additional parameters made available in the SDK constructor:

Variable Parameter Default Description
id id: string "example" The subdomain for your Gr4vy instance.

Example

using Gr4vy;
using Gr4vy.Models.Components;
using System.Collections.Generic;

var sdk = new Gr4vySDK(
    server: "sandbox",
    id: "<id>",
    bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
    merchantAccountId: "default"
);

var res = await sdk.AccountUpdater.Jobs.CreateAsync(
    accountUpdaterJobCreate: new AccountUpdaterJobCreate() {
        PaymentMethodIds = new List<string>() {
            "ef9496d8-53a5-4aad-8ca2-00eb68334389",
            "f29e886e-93cc-4714-b4a3-12b7a718e595",
        },
    },
    timeoutInSeconds: 1D,
    merchantAccountId: "default"
);

// handle response

Override Server URL Per-Client

The default server can also be overridden globally by passing a URL to the serverUrl: string optional parameter when initializing the SDK client instance. For example:

using Gr4vy;
using Gr4vy.Models.Components;
using System.Collections.Generic;

var sdk = new Gr4vySDK(
    serverUrl: "https://api.example.gr4vy.app",
    bearerAuth: "<YOUR_BEARER_TOKEN_HERE>",
    merchantAccountId: "default"
);

var res = await sdk.AccountUpdater.Jobs.CreateAsync(
    accountUpdaterJobCreate: new AccountUpdaterJobCreate() {
        PaymentMethodIds = new List<string>() {
            "ef9496d8-53a5-4aad-8ca2-00eb68334389",
            "f29e886e-93cc-4714-b4a3-12b7a718e595",
        },
    },
    timeoutInSeconds: 1D,
    merchantAccountId: "default"
);

// handle response

Development

Testing

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

dotnet test src/Gr4vy.Tests

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