Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

.NET client library for the Square API

License

NotificationsYou must be signed in to change notification settings

square/square-dotnet-sdk

Repository files navigation

fern shieldnuget shield

The Square .NET library provides convenient access to the Square API from C#, VB.NET, and F#.

Requirements

The Square .NET SDK is supported with the following target frameworks:

  • .NET 8 and above
  • .NET Framework 4.6.2 and above
  • .NET Standard 2.0 and above

Installation

dotnet add package Square

Usage

Instantiate and use the client with the following:

usingSquare.Payments;usingSquare;varclient=newSquareClient();awaitclient.Payments.CreateAsync(newCreatePaymentRequest{SourceId="ccof:GaJGNaZa8x4OgDJn4GB",IdempotencyKey="7b0f3ec5-086a-4871-8f13-3c81b3875218",AmountMoney=newMoney{Amount=1000,Currency=Currency.Usd},AppFeeMoney=newMoney{Amount=10,Currency=Currency.Usd},Autocomplete=true,CustomerId="W92WH6P11H4Z77CTET0RNTGFW8",LocationId="L88917AVBK2S5",ReferenceId="123456",Note="Brief description",});

Instantiation

To get started with the Square SDK, instantiate theSquareClient class as follows:

usingSquare;varclient=newSquareClient("SQUARE_TOKEN");

Alternatively, you can omit the token when constructing the client.In this case, the SDK will automatically read the token from theSQUARE_TOKEN environment variable:

usingSquare;varclient=newSquareClient();// Token is read from the SQUARE_TOKEN environment variable.

Environment and Custom URLs

This SDK allows you to configure different environments or custom URLs for API requests.You can either use the predefined environments or specify your own custom URL.

Environments

usingSquare;varclient=newSquareClient(clientOptions:newClientOptions{BaseUrl=SquareEnvironment.Production// Used by default});

Custom URL

usingSquare;varclient=newSquareClient(clientOptions:newClientOptions{BaseUrl="https://custom-staging.com"});

Enums

This SDK uses forward-compatible enums that provide type safety while maintaining forward compatibility with API updates.

// Use predefined enum valuesvaraccountType=BankAccountType.Checking;// Use unknown/future enum valuesvarcustomType=BankAccountType.FromCustom("FUTURE_VALUE");// String conversions and equalitystringtypeString=accountType.ToString();// Returns "CHECKING"varisChecking=accountType=="CHECKING";// Returns true// When writing switch statements, always include a default caseswitch(accountType.Value){caseBankAccountType.Values.Checking:// Handle checking accountsbreak;caseBankAccountType.Values.BusinessChecking:// Handle business checking accountsbreak;default:// Handle unknown values for forward compatibilitybreak;}

Pagination

List endpoints are paginated. The SDK provides an async enumerable so that you can simply loop over the items:

usingSquare.BankAccounts;usingSquare;varclient=newSquareClient();varpager=awaitclient.BankAccounts.ListAsync(newListBankAccountsRequest());awaitforeach(variteminpager){// do something with item}

Exception Handling

When the API returns a non-success status code (4xx or 5xx response), aSquareApiException will be thrown.

usingSquare;try{varresponse=awaitclient.Payments.CreateAsync(...);}catch(SquareApiExceptione){Console.WriteLine(e.Body);Console.WriteLine(e.StatusCode);// Access the parsed error objectsforeach(varerrorine.Errors){Console.WriteLine($"Category:{error.Category}");Console.WriteLine($"Code:{error.Code}");Console.WriteLine($"Detail:{error.Detail}");Console.WriteLine($"Field:{error.Field}");}}

Webhook Signature Verification

The SDK provides utility methods that allow you to verify webhook signatures and ensurethat all webhook events originate from Square. TheWebhooksHelper.verifySignature methodcan be used to verify the signature like so:

usingMicrosoft.AspNetCore.Http;usingSquare;publicstaticasyncTaskCheckWebhooksEvent(HttpRequestrequest,stringsignatureKey,stringnotificationUrl){varsignature=request.Headers["x-square-hmacsha256-signature"].ToString();usingvarreader=newStreamReader(request.Body,System.Text.Encoding.UTF8);varrequestBody=awaitreader.ReadToEndAsync();if(!WebhooksHelper.VerifySignature(requestBody,signature,signatureKey,notificationUrl)){thrownewException("A webhook event was received that was not from Square.");}}

In .NET 6 and above, there are also overloads using spans for allocation free webhook verification.

Legacy SDK

While the new SDK has a lot of improvements, we at Square understand that it takes time to upgrade when there are breaking changes.To make the migration easier, the legacy SDK is available as a separate NuGet packageSquare.Legacy with all functionality under theSquare.Legacy namespace. Here's an example of how you can use the legacy SDK alongside the new SDK inside a single file:

usingSquare;usingSquare.Legacy.Authentication;varaccessToken="YOUR_SQUARE_TOKEN";// NEWvarclient=newSquareClient(accessToken);// LEGACYvarlegacyClient=newSquare.Legacy.SquareClient.Builder().BearerAuthCredentials(newBearerAuthModel.Builder(accessToken).Build()).Environment(Square.Legacy.Environment.Production).Build();

We recommend migrating to the new SDK using the following steps:

  1. Install theSquare.Legacy NuGet package alongside your existing Square SDK
  2. Search and replace all using statements fromSquare toSquare.Legacy
  3. Gradually move over to use the new SDK by importing it from theSquare namespace.

Advanced

Retries

The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as longas the request is deemed retryable and the number of retry attempts has not grown larger than the configuredretry limit (default: 2).

A request is deemed retryable when any of the following HTTP status codes is returned:

  • 408 (Timeout)
  • 429 (Too Many Requests)
  • 5XX (Internal Server Errors)

Use theMaxRetries request option to configure this behavior.

varresponse=awaitclient.Payments.CreateAsync(    ...,newRequestOptions{MaxRetries:0// Override MaxRetries at the request level});

Timeouts

The SDK defaults to a 30 second timeout. Use theTimeout option to configure this behavior.

varresponse=awaitclient.Payments.CreateAsync(    ...,newRequestOptions{Timeout: TimeSpan.FromSeconds(3)// Override timeout to 3s});

Receive Additional Properties

Every response type includes theAdditionalProperties property, which returns anIDictionary<string, JsonElement> that contains any properties in the JSON response that were not specified in the returned class. Similar to the use case for sending additional parameters, this can be useful for API features not present in the SDK yet.

You can access the additional properties like so:

varpayments=client.Payments.Create(...);IDictionary<string,JsonElement>additionalProperties=payments.AdditionalProperties;

TheAdditionalProperties dictionary is populated automatically during deserialization using the[JsonExtensionData] attribute. This provides you with access to any fields that may be added to the API response in the future before they're formally added to the SDK models.

Contributing

While we value open-source contributions to this SDK, this library is generated programmatically.Additions made directly to this library would have to be moved over to our generation code,otherwise they would be overwritten upon the next generated release. Feel free to open a PR asa proof of concept, but know that we will not be able to merge it as-is. We suggest openingan issue first to discuss with us!

On the other hand, contributions to the README are always very welcome!


[8]ページ先頭

©2009-2025 Movatter.jp