You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
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});
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:
We recommend migrating to the new SDK using the following steps:
Install theSquare.Legacy NuGet package alongside your existing Square SDK
Search and replace all using statements fromSquare toSquare.Legacy
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:
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.
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!