Learn how to quickly set up and test the Square .NET SDK.
Before you begin, you need a Square account and account credentials. You use the Square Sandbox for the Quickstart exercise.
- Create a Square account and an application. For more information, see Create an Account and Application.
- Get a Sandbox access token from the Developer Console. For more information, see Get a personal access token.
You can now follow one of the following workflows depending on whether you're using Visual Studio.
Note
If you prefer to skip the following setup steps, download the Square .NET SDK Quickstart sample and follow the instructions in the README.
Use the following steps to create a project if you're using a non-Windows computer and don't use Visual Studio. These steps use the .NET command-line interface. Make sure you have .NET installed on your computer. For example, if you're using a Mac, see Install .NET on macOS.
Open a new terminal window. Find or create an operating system folder under which you can create a .NET project.
In that folder, run the following command to create the .NET project:
dotnet new console --name ExploreLocationsAPIDon't add your credentials to the source file. You add an application settings file to the project to store credentials.
Go to the newly created ExploreLocationsAPI folder and add the following appsettings.json file:
{ "AppSettings": { "AccessToken": "YOUR-SANDBOX-ACCESS-TOKEN" } }See the following example:
{ "AppSettings": { "AccessToken": "EAAAEFeOs3UYyCct-9FcmbUwUp7Hm1cuaqTRwOOnkw1F0TGKjtKO0avgjexample" } }Update the JSON file by providing your Sandbox access token.
Run the following commands to install the NuGet packages from the NuGet package manager:
dotnet add package Square dotnet add package Microsoft.Extensions.Configuration.Json dotnet add package Microsoft.Extensions.ConfigurationThe
Microsoft.Extensions.Configuration
andpackage Microsoft.Extensions.Configuration.Json
packages are used to manage the application settings file (such as read credentials).
In the ExploreLocationsAPI folder, find and open Program.cs in your code editor.
Replace the contents with the following code and save the file:
using System; using Square; using Square.Models; using Square.Exceptions; using Square.Authentication; using Microsoft.Extensions.Configuration; namespace ExploreLocationsAPI { public class Program { private static ISquareClient client; private static IConfigurationRoot config; static void Main(string[] args) { var builder = new ConfigurationBuilder() .AddJsonFile($"appsettings.json", true, true); config = builder.Build(); var accessToken = config["AppSettings:AccessToken"]; client = new SquareClient.Builder() .BearerAuthCredentials( new BearerAuthModel.Builder( accessToken ) .Build()) .Environment(Square.Environment.Sandbox) .Build(); RetrieveLocationsAsync().Wait(); } static async Task RetrieveLocationsAsync() { try { ListLocationsResponse response = await client.LocationsApi.ListLocationsAsync(); foreach (Location location in response.Locations) { Console.WriteLine("location:\n country = {0} name = {1}", location.Country, location.Name); } } catch (ApiException e) { var errors = e.Errors; var statusCode = e.ResponseCode; var httpContext = e.HttpContext; Console.WriteLine("ApiException occurred:"); Console.WriteLine("Headers:"); foreach (var item in httpContext.Request.Headers) { //Display all the headers except Authorization if (item.Key != "Authorization") { Console.WriteLine("\t{0}: \t{1}", item.Key, item.Value); } } Console.WriteLine("Status Code: \t{0}", statusCode); foreach (Error error in errors) { Console.WriteLine("Error Category:{0} Code:{1} Detail:{2}", error.Category, error.Code, error.Detail); } // Your error handling code } catch (Exception e) { Console.WriteLine("Exception occurred"); // Your error handling code } } } }This code does the following:
- Reads your Square access token from the appsettings.json file.
- Creates a SquareClient using the access token.
- Calls the ListLocationsAsync method to retrieve the locations.
If the request is successful, the code prints the location information on the terminal.
Update the code to provide the full path of the appsettings.json file.
var builder = new ConfigurationBuilder() .AddJsonFile($"<file-path>/appsettings.json", true, true);
Run the following command:
dotnet runYou should see at least one location (Square creates one location when you create a Square account).
You perform this Quickstart exercise on a Windows computer using Visual Studio and .NET Core. Make sure you have the following:
- Microsoft Visual Studio.
- Microsoft .NET Standard 2.0 or later. This is typically included by default when installing a recent version of Visual Studio. For more information, see Install .NET on Windows.
Open Visual Studio and create a new project using the C# Console Application template. Name the project ExploreLocationsAPI.
After the project loads, right-click the project, choose Add, and then choose NuGet Packages.
Search the following NuGet packages and install them in the project:
Square Microsoft.Extensions.Configuration.Json Microsoft.Extensions.ConfigurationAdd an appsettings.json file to the project.
Right-click the project, choose Add, choose New File, and then choose Empty text file. Specify the file name as appsettings.json.
Add the following JSON:
{ "AppSettings": { "AccessToken": "{YOUR-SANDBOX-ACCESS-TOKEN}" } }Update the preceding JSON by providing your Sandbox access token.
Update the file properties. Right-click appsettings.json, and then choose Properties. In the Copy to Output Directory drop-down list, choose Copy if newer.
In the ExploreCustomersAPI project, find and open Program.cs.
Replace the contents with the following code:
using System; using Square; using Square.Models; using Square.Exceptions; using Square.Authentication; using Microsoft.Extensions.Configuration; namespace ExploreLocationsAPI { public class Program { private static ISquareClient client; private static IConfigurationRoot config; static void Main(string[] args) { var builder = new ConfigurationBuilder() .AddJsonFile($"appsettings.json", true, true); config = builder.Build(); var accessToken = config["AppSettings:AccessToken"]; client = new SquareClient.Builder() .BearerAuthCredentials( new BearerAuthModel.Builder( accessToken ) .Build()) .Environment(Square.Environment.Sandbox) .Build(); RetrieveLocationsAsync().Wait(); } static async Task RetrieveLocationsAsync() { try { ListLocationsResponse response = await client.LocationsApi.ListLocationsAsync(); foreach (Location location in response.Locations) { Console.WriteLine("location:\n country = {0} name = {1}", location.Country, location.Name); } } catch (ApiException e) { var errors = e.Errors; var statusCode = e.ResponseCode; var httpContext = e.HttpContext; Console.WriteLine("ApiException occurred:"); Console.WriteLine("Headers:"); foreach (var item in httpContext.Request.Headers) { //Display all the headers except Authorization if (item.Key != "Authorization") { Console.WriteLine("\t{0}: \t{1}", item.Key, item.Value); } } Console.WriteLine("Status Code: \t{0}", statusCode); foreach (Error error in errors) { Console.WriteLine("Error Category:{0} Code:{1} Detail:{2}", error.Category, error.Code, error.Detail); } // Your error handling code } catch (Exception e) { Console.WriteLine("Exception occurred"); // Your error handling code } } } }Save the file.
This code does the following:
- Reads your Square access token from the appsettings.json file.
- Creates a SquareClient using the access token.
- Calls the ListLocationsAsync method to retrieve the locations.
- If the request is successful, the code prints the location information on the terminal.
- Build and run the application.
- Verify the result. You should see at least one location (Square creates one location when you create a Square account).
You can explore one of the following paths:
- Explore the .NET SDK and try examples on your own. For more information, see SDK reference library on GitHub.
- Learn more introductory information about using the .NET SDK.