Learn about the Square .NET SDK features.
If you're new to developing Square integrations using the Square .NET SDK, you should try the Quickstart. It provides step-by-step instructions to explore your first project.
This topic explains how to configure a client, how to securely provide credentials (access tokens) to authenticate your request, the API call patterns, how to pass parameters, and how to process responses.
The using
directive allows you to use types defined in a namespace without specifying the fully qualified namespace of that type. You add the following using
directive to import all the types from the Square namespace:
using Square;
To use the Square API, instantiate a SquareClient
object and initialize it with the appropriate environment and corresponding access token. For an introduction to these environments, see Create an Account and Application.
For testing, Square provides a Sandbox environment.
SquareClient client = new SquareClient.Builder() .BearerAuthCredentials( new BearerAuthModel.Builder( accessToken ) .Build()) .Environment(Square.Environment.Sandbox) .Build();The next section (Configure credentials securely) explains how you might avoid hardcoding credentials (access tokens) in your application.
To access production resources, set the environment to
Production
.SquareClient client = new SquareClient.Builder() .BearerAuthCredentials( new BearerAuthModel.Builder( accessToken ) .Build()) .Environment(Square.Environment.Production) .Build();To set a custom environment, provide a
CustomUrl
and set the environment toSquare.Environment.Custom
.SquareClient client = new SquareClient.Builder() .Environment(Square.Environment.Custom) .CustomUrl("https://your.customdomain.com") .BearerAuthCredentials( new BearerAuthModel.Builder( accessToken ) .Build()) .Build();
Each Square API request must be authenticated. Don't hardcode credentials (access tokens) in your code. The Quickstart exercise uses a configuration file in the project to store credentials. The code then uses the .NET API calls to read the credentials as shown in the following C# code fragment:
var builder = new ConfigurationBuilder()
.AddJsonFile($"appsettings.json", true, true);
config = builder.Build();
var accessToken = config["AppSettings:AccessToken"];
Console.WriteLine($"Access Token is: {accessToken}");
client = new SquareClient.Builder()
.BearerAuthCredentials(
new BearerAuthModel.Builder(
accessToken
)
.Build())
.Environment(Square.Environment.Sandbox)
.Build();
In the code, appsettings.json is the configuration file, as shown in the following example:
{
"AppSettings": {
"AccessToken": "{YOUR-SANDBOX-ACCESS-TOKEN}",
}
}
Note
If you plan to upload your project to GitHub, don't upload this file with credentials. You might consider using a .gitignore file to prevent the configuration file from being uploaded to GitHub.
The Square .NET SDK uses the Task-based Asynchronous Pattern (TAP) for its asynchronous implementation. The Square .NET SDK asynchronous methods are based on the Task class or the Task<TResult> class. For more information about TAP, see Task-based Asynchronous Pattern (TAP).
You can call Square async API methods from within functions declared with the async keyword, as shown:
static async Task RetrieveLocationsAsync()
{
try
{
ListLocationsResponse response;
response = await client.LocationsApi.ListLocationsAsync();
...
}
catch (ApiException e)
{
…
}
}
You can set the main function as async to ensure that all Square API calls that your application makes are asynchronous.
In the Square.Models
namespace, every object is a model. For example, complex types Address
, Customer
, and Order
are all models defined in the namespace. You pass these models, with values, as parameters as shown in the following example. The example passes the Address
model as a parameter to create a new customer.
Address address = new Address.Builder()
.AddressLine1("1455 Market St")
.AddressLine2("San Francisco, CA 94103")
.Build();
CreateCustomerRequest request = new CreateCustomerRequest.Builder()
.IdempotencyKey("12345")
.GivenName("JohnNet2")
.FamilyName("DoeNet2")
.Address(address)
.Build();
try
{
CreateCustomerResponse response;
response = await client.CustomersApi.CreateCustomerAsync(request);
Console.WriteLine("customer created:\n Given name = {0} Family name = {1}",
response.Customer.GivenName, response.Customer.FamilyName);
}
catch (ApiException e)
{
}
The Square API endpoints can have path parameters, query parameters, and a request body. When you make corresponding method calls using the Square .NET SDK, you provide the values as follows:
Request body - For example,
CreateCustomer
andUpdateCustomer
require aCustomer
object in the body. In the Square .NET SDK, you use the builder pattern to specify the request body.Address address = new Address.Builder() .AddressLine1("1455 Market St") .AddressLine2("San Francisco, CA 94103") .Build(); CreateCustomerRequest request = new CreateCustomerRequest.Builder() .IdempotencyKey("18djdufd") .GivenName("given-vs1") .FamilyName("family-vs1") .Address(address) .Build(); try { CreateCustomerResponse response; response = await client.CustomersApi.CreateCustomerAsync(request); Console.WriteLine("customer created:\n Customer Id: {0}, Given name: {1}, Family name: {2}", response.Customer.Id, response.Customer.GivenName, response.Customer.FamilyName); } catch (ApiException e) { }Path and query parameters - For example:
- The
RetrieveCustomer
endpoint has acustomer_id
path parameter (GET /v2/customers/{customer_id}
). - The
ListCustomers
endpoint has several query parameters such ascursor
andlimit
.
You provide these as parameters to the method calls. The following example passes the
customer_id
path parameter as a parameter to theUpdateCustomerAsync
method:UpdateCustomerRequest request = new UpdateCustomerRequest.Builder() .GivenName("Drew2") .FamilyName("Grimes2") .Version(0) .Build(); try { UpdateCustomerResponse response; response = await client.CustomersApi.UpdateCustomerAsync(custId, request); Console.WriteLine("customer updated:\n Id: {0}, Version:{1} Given name:{2}, Family name: {3}", response.Customer.Id, response.Customer.Version, response.Customer.GivenName, response.Customer.FamilyName); } catch (ApiException e) { }For an example of query parameters, see Pagination.
- The
You can configure the number of retries and the timeout values for HTTP requests when using the Square .NET SDK:
Retries - By default, the Square SDK doesn't retry a failed request. When your application starts, the Square SDK sets the number of retries to 0. You have the option to configure a different value when you create a client. Retries can help improve application stability by allowing applications to handle momentary failures in connecting to a service by transparently retrying a failed request.
Timeout - Timeout is the time period that a client waits for a server response. The Square SDK sets the default timeout to 60 seconds. On timeout, the SDK throws an exception. You have the option to configure a timeout value at the client level. The maximum timeout can be the InfiniteTimeSpan constant.
The following C# code fragment specifies the HttpClientConfig
parameter in creating a client. The configuration sets the number of retries to 2 and the timeout to 60 seconds.
client = new SquareClient.Builder()
.Environment(Square.Environment.Sandbox)
.BearerAuthCredentials(
new BearerAuthModel.Builder(
accessToken
)
.Build())
.HttpClientConfig(config => config
.NumberOfRetries(2)
.Timeout(TimeSpan.FromSeconds(60)))
.Build();
Configuring a client with long timeout values and a high number of retries can cause some SDK operations to appear unresponsive. There are several considerations that apply when configuring the timeout and retries. These include:
- For network issues (decrease in network connectivity and response speed), how should the application respond? Do you want the call to fail fast, or do you want the application to retry the failed call?
- Buyer-facing applications might need to be responsive compared to a background job that can tolerate increased latency due increased timeout values and retries.
The response object contains the HttpContext
that describes both the request and the response.
- If an API call succeeds, a response object containing
HttpContext
is returned. ThisHttpContext
describes both the request and the response. - If an API call fails, you get an
ApiException
(see ApiException Class).
try {
ListLocationsResponse response = await client.LocationsApi.ListLocationsAsync();
Console.WriteLine("Successfully called ListLocations");
// Your business logic here
}
catch (ApiException e){
var errors = e.Errors;
var statusCode = e.ResponseCode;
var httpContext = e.HttpContext;
Console.WriteLine("ApiException occurred");
// Your error handling code
}
For more information, see Square API errors.