### Install and Run Web Payments SDK Quickstart
Source: https://developer.squareup.com/docs/web-payments/quickstart/set-up-web-client-app
Clone the GitHub repository, install dependencies using npm, and start the development server. Navigate to http://localhost:3000 to verify the setup.
```bash
git clone https://github.com/square/web-payments-sdk-quickstart
cd web-payments-sdk-quickstart
npm install
npm run dev
```
--------------------------------
### Create Subscription with Card on File and Delayed Start
Source: https://developer.squareup.com/docs/subscriptions-api/manage-subscriptions
This example shows how to create a subscription with a specified card for payment and a future start date. This is suitable for plans with static pricing and no immediate activation.
```APIDOC
## POST /v2/subscriptions
### Description
Enrolls a customer in a subscription plan variation, using a card on file for payment and setting a future start date. This is for plans without immediate activation or complex phase requirements.
### Method
POST
### Endpoint
https://connect.squareupsandbox.com/v2/subscriptions
### Parameters
#### Request Body
- **idempotency_key** (string) - Required - A unique key to ensure idempotency of the request.
- **customer_id** (string) - Required - The ID of the customer to enroll in the subscription.
- **location_id** (string) - Required - The ID of the location associated with the subscription.
- **plan_variation_id** (string) - Required - The ID of the subscription plan variation.
- **card_id** (string) - Required - The ID of the card on file to charge for the subscription.
- **start_date** (string) - Required - The future date when the subscription should start (YYYY-MM-DD).
### Request Example
```json
{
"idempotency_key": "{UNIQUE_KEY}",
"customer_id": "VAAYA3B3E1T7T1C2TWCEAF88T0",
"location_id": "LE40N37TVF5FT",
"plan_variation_id": "XOUNEKCE6NSXQW5NTSQ73MMX",
"card_id": "{CARD ID}",
"start_date": "2027-01-01"
}
```
### Response
#### Success Response (200)
- **subscription** (object) - The created subscription object.
- **id** (string) - The unique ID of the subscription.
- **location_id** (string) - The ID of the location.
- **customer_id** (string) - The ID of the customer.
- **start_date** (string) - The date the subscription starts.
- **status** (string) - The current status of the subscription (e.g., ACTIVE, PENDING).
- **version** (integer) - The version of the subscription.
- **created_at** (string) - The timestamp when the subscription was created.
- **timezone** (string) - The timezone of the subscription.
- **source** (object) - Information about the source that created the subscription.
- **name** (string) - The name of the application that created the subscription.
- **plan_variation_id** (string) - The ID of the subscription plan variation.
- **card_id** (string) - The ID of the card on file used for payment.
#### Response Example
```json
{
"subscription": {
"id": "28d66d75-a6f8-4594-bd5e-3a8bacf3818e",
"location_id": "LPJKHYR7WFDKN",
"customer_id": "FN3M4KE6EHP5W74M9FSDZ8VPMC",
"start_date": "2027-01-01",
"status": "PENDING",
"version": 1,
"created_at": "2023-03-06T19:44:05Z",
"timezone": "UTC",
"source": {
"name": "My Application"
},
"plan_variation_id": "XOUNEKCE6NSXQW5NTSQ73MMX",
"card_id": "{CARD ID}"
}
}
```
```
--------------------------------
### Complete Quickstart Example
Source: https://developer.squareup.com/docs/web-payments/quickstart/add-sdk-to-web-client
This HTML and JavaScript code provides a full implementation for the Square Web Payments quickstart. It includes SDK initialization, card element attachment, tokenization, and payment creation. Ensure you replace placeholder values like {APP_ID} and {LOCATION_ID} with your actual credentials.
```html
Square Web Payments Quickstart
```
--------------------------------
### Java Quickstart Example
Source: https://developer.squareup.com/docs/sdks/java/quick-start
This Java code snippet demonstrates how to initialize the Square SDK client, retrieve account locations, and handle potential API errors. It reads credentials from a properties file.
```Java
package com.square.examples;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.squareup.square.AsyncSquareClient;
import com.squareup.square.core.Environment;
import com.squareup.square.types.Location;
import com.squareup.square.types.Error;
import com.squareup.square.core.SquareApiException;
import com.squareup.square.types.Address;
public class Quickstart {
public static void main(String[] args) {
InputStream inputStream =
Quickstart.class.getResourceAsStream("/config.properties");
Properties prop = new Properties();
try {
prop.load(inputStream);
} catch (IOException e) {
System.out.println("Error reading properties file");
e.printStackTrace();
}
AsyncSquareClient client = AsyncSquareClient.builder()
.token(prop.getProperty("SQUARE_ACCESS_TOKEN"))
.environment(Environment.SANDBOX)
.build();
client.locations().list()
.thenAccept(result -> {
System.out.println("Location(s) for this account:");
result.getLocations().ifPresent(locations -> {
for (Location l : locations) {
// Build location details safely
StringBuilder locationInfo = new StringBuilder();
// Add ID if present
l.getId().ifPresent(id -> locationInfo.append("ID: ").append(id));
// Add name if present
l.getName().ifPresent(name ->
locationInfo.append(locationInfo.length() > 0 ? ", " : "")
.append("Name: ").append(name));
// Handle address details if present
l.getAddress().ifPresent(address -> {
// Add address line 1 if present
address.getAddressLine1().ifPresent(line1 ->
locationInfo.append(locationInfo.length() > 0 ? ", " : "")
.append("Address: ").append(line1));
// Add locality (city) if present
address.getLocality().ifPresent(locality ->
locationInfo.append(locationInfo.length() > 0 ? ", " : "")
.append("City: ").append(locality));
});
// Print the complete location information
System.out.println(locationInfo.toString());
}
});
})
.exceptionally(exception -> {
if (exception.getCause() instanceof SquareApiException) {
SquareApiException apiException = (SquareApiException) exception.getCause();
apiException.errors().forEach(error -> {
System.out.println("Category: " + error.getCategory());
System.out.println("Code: " + error.getCode());
System.out.println("Detail: " + error.getDetail());
});
} else {
System.out.println("An unexpected error occurred:");
exception.printStackTrace();
}
return null;
})
.join();
}
}
```
--------------------------------
### Complete Example: Process Customer Gift Card
Source: https://developer.squareup.com/docs/customers-api/quick-start
This Java example demonstrates the complete workflow of finding or creating a customer, then creating or loading a gift card for them. It includes setup for the Square client and a main method for execution.
```java
import com.squareup.square.SquareClient;
import com.squareup.square.Environment;
import com.squareup.square.exceptions.ApiException;
import com.squareup.square.models.*;
import java.util.UUID;
public class GiftCardService {
private final SquareClient client;
public GiftCardService(String accessToken) {
client = new SquareClient.Builder()
.environment(Environment.SANDBOX)
.accessToken(accessToken)
.build();
}
public void processCustomerGiftCard(String firstName, String lastName,
String emailAddress, String streetAddress, Money amount) throws ApiException {
// Find or create customer
Customer customer = findOrCreateCustomer(firstName, lastName, emailAddress, streetAddress);
// Create or load gift card
GiftCard giftCard = createOrGetGiftCard(customer, amount);
System.out.println("Gift card processed successfully for customer: " +
customer.getGivenName() + " " + customer.getFamilyName());
System.out.println("Gift card ID: " + giftCard.getId());
}
// ... (include findOrCreateCustomer and createOrGetGiftCard methods from above)
public static void main(String[] args) {
try {
GiftCardService service = new GiftCardService("YOUR_ACCESS_TOKEN");
Money amount = new Money.Builder()
.amount(10000L) // $100.00
.currency("USD")
.build();
service.processCustomerGiftCard(
"John",
"Doe",
"john.doe@example.com",
"123 Main St",
amount
);
} catch (ApiException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
```
--------------------------------
### Charge Card on File Setup
Source: https://developer.squareup.com/docs/web-payments/charge-and-store-cards
This example demonstrates the complete flow for charging a customer's card on file. It includes tokenizing the card, creating the payment, and displaying the results. Ensure Square.js is loaded and initialized with your application ID and location ID.
```javascript
async function createPaymentWithCardOnFile(
token,
customerId,
) {
const body = JSON.stringify({
locationId,
sourceId: token,
customerId,
idempotencyKey: window.crypto.randomUUID(),
});
const paymentResponse = await fetch('/payment', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body,
});
if (paymentResponse.ok) {
return paymentResponse.json();
}
const errorBody = await paymentResponse.text();
throw new Error(errorBody);
}
// status is either SUCCESS or FAILURE;
function displayPaymentResults(status) {
const statusContainer = document.getElementById(
'payment-status-container',
);
if (status === 'SUCCESS') {
statusContainer.classList.remove('is-failure');
statusContainer.classList.add('is-success');
} else {
statusContainer.classList.remove('is-success');
statusContainer.classList.add('is-failure');
}
statusContainer.style.visibility = 'visible';
}
async function tokenize(paymentMethod, sourceId) {
const verificationDetails = {
amount: '1.00',
billingContact: {
givenName: 'John',
familyName: 'Doe',
email: 'john.doe@square.example',
phone: '3214563987',
addressLines: ['123 Main Street', 'Apartment 1'],
city: 'London',
state: 'LND',
countryCode: 'GB',
},
currencyCode: 'GBP',
intent: 'CHARGE',
customerInitiated: true,
sellerKeyedIn: false,
};
const tokenResult = await paymentMethod.tokenize(verificationDetails, sourceId);
if (tokenResult.status === 'OK') {
return tokenResult.token;
} else {
let errorMessage = `Tokenization failed with status: ${tokenResult.status}`;
if (tokenResult.errors) {
errorMessage += ` and errors: ${JSON.stringify(
tokenResult.errors,
)}`;
}
throw new Error(errorMessage);
}
}
document.addEventListener('DOMContentLoaded', async function () {
if (!window.Square) {
throw new Error('Square.js failed to load properly');
}
let payments;
try {
payments = window.Square.payments(appId, locationId);
} catch {
const statusContainer = document.getElementById(
'payment-status-container',
);
statusContainer.className = 'missing-credentials';
statusContainer.style.visibility = 'visible';
return;
}
let card;
try {
card = await payments.card();
} catch (e) {
console.error('Initializing Card failed', e);
return;
}
async function handleChargeCardOnFileSubmission(
event,
card,
cardId,
customerId,
) {
event.preventDefault();
try {
// disable the submit button as we await tokenization and make a payment request.
cardButton.disabled = true;
const token = await tokenize(card, cardId);
const paymentResults = await createPaymentWithCardOnFile(
token,
customerId
);
displayPaymentResults('SUCCESS');
console.debug('Payment Success', paymentResults);
} catch (e) {
cardButton.disabled = false;
displayPaymentResults('FAILURE');
console.error(e.message);
}
}
const cardButton = document.getElementById('card-button');
cardButton.addEventListener('click', async function (event) {
const customerTextInput = document.getElementById('customer-input');
const cardTextInput = document.getElementById('card-input');
if (
!customerTextInput.reportValidity() ||
!cardTextInput.reportValidity()
) {
return;
}
const cardId = cardTextInput.value;
const customerId = customerTextInput.value;
handleChargeCardOnFileSubmission(event, card, cardId, customerId);
});
});
```
--------------------------------
### Validate Webhook Signature in C#
Source: https://developer.squareup.com/docs/webhooks-api/validate-notifications
This C# example demonstrates how to validate webhook signatures using the Square .NET SDK. It includes setup instructions and a sample server implementation that checks the signature of incoming requests. Ensure you have the SDK installed and your project configured.
```csharp
using Square.Utilities;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
public class Server
{
/// The URL where event notifications are sent.
private const string NOTIFICATION_URL = "https://example.com/webhook";
/// The signature key defined for the subscription.
private const string SIGNATURE_KEY = "asdf1234";
///
/// Generate a signature from the notification url, signature key,
/// and request body and compare it to the Square signature header.
///
private static async Task IsFromSquare(HttpListenerRequest request)
{
using (var reader = new StreamReader(request.InputStream, Encoding.UTF8))
{
var signature = request.Headers.Get("x-square-hmacsha256-signature") ?? "";
var requestBody = await reader.ReadToEndAsync();
return WebhooksHelper.IsValidWebhookEventSignature(requestBody, signature, SIGNATURE_KEY, NOTIFICATION_URL);
}
}
///
/// Start a simple server for local testing. Different frameworks may provide the raw request body in other ways.
///
///
/// INSTRUCTIONS
/// After installing the SDK:
/// 1. Run the server:
/// (You will first need to include your own csharp.csproj file.)
/// dotnet run
/// 2. Send the following request from a separate terminal:
/// curl -vX POST localhost:8000 -d '{"hello":"world"}' -H "X-Square-HmacSha256-Signature: 2kRE5qRU2tR+tBGlDwMEw2avJ7QM4ikPYD/PJ3bd9Og="
///
public static void Main(string[] args)
{
HttpListener server = new HttpListener();
server.Prefixes.Add("http://localhost:8000/");
server.Start();
while (true)
{
HttpListenerContext context = server.GetContext();
var task = IsFromSquare(context.Request);
task.Wait();
bool isFromSquare = task.Result;
using (HttpListenerResponse response = context.Response)
{
if (isFromSquare)
{
// Signature is valid. Return 200 OK.
response.StatusCode = 200;
}
else
{
// Signature is invalid. Return 403 Forbidden.
response.StatusCode = 403;
}
}
}
}
}
}
```
--------------------------------
### Run Quickstart Program with Maven
Source: https://developer.squareup.com/docs/sdks/java/quick-start
Execute your Quickstart program using Maven. This command specifies the main class to run, which is 'com.square.examples.Quickstart'.
```bash
mvn exec:java -Dexec.mainClass="com.square.examples.Quickstart"
```
--------------------------------
### Labor API Employee ID Response for Get Wage
Source: https://developer.squareup.com/docs/labor-api/migrate-to-teams
Example JSON response when getting an employee wage using `employee_id`.
```JSON
{
"employee_wage": {
"id": "employee_wage_id",
"employee_id": "employeeid",
"title": "Chef",
"hourly_rate": {
"amount": 6000,
"currency": "USD"
}
}
}
```
--------------------------------
### Labor API Team Member ID Response for Get Wage
Source: https://developer.squareup.com/docs/labor-api/migrate-to-teams
Example JSON response when getting a team member wage using `team_member_id`.
```JSON
{
"team_member_wage": {
"id": "pXS3qCv7BERPnEGedM4S8mhm",
"team_member_id": "33fJchumvVdJwxV0H6L9",
"title": "Manager",
"hourly_rate": {
"amount": 2000,
"currency": "USD"
}
}
}
```
--------------------------------
### Initialize Project with npm
Source: https://developer.squareup.com/docs/sdks/nodejs/quick-start
Use the npm init command to create a package.json file for your project.
```bash
npm init --yes
```
--------------------------------
### Update Booking Example
Source: https://developer.squareup.com/docs/bookings-api/use-the-api
This example shows how to update an existing booking, specifically changing its start time and date. It uses a PUT request to the booking's endpoint.
```APIDOC
## Update a Booking
### Description
Updates an existing booking. This endpoint supports sparse updates, meaning only the fields to be modified need to be provided. The updatable properties depend on the caller's permissions (buyer-level or seller-level).
### Method
PUT
### Endpoint
/v2/bookings/{booking_id}
### Parameters
#### Path Parameters
- **booking_id** (string) - Required - The ID of the booking to update.
#### Request Body
- **booking** (object) - Required - The booking object containing the fields to update.
- **start_at** (string) - Optional - The new start timestamp of the booking in RFC 3339 format. When updating with buyer-level permissions, it's recommended to call `SearchAvailability` first.
- **address** (object) - Optional - The complete address object for the booking. Sparse updates are not allowed for the address field; the entire object must be provided.
### Request Example
```curl
curl https://connect.square.com/v2/bookings/k1jczlajuhy2xg \
-X PUT \
-H 'Square-Version: 2026-05-20' \
-H 'Authorization: Bearer {ACCESS_TOKEN}' \
-H 'Content-Type: application/json' \
-d '{
"booking": {
"start_at": "2021-12-17T18:00:00Z"
}
}'
```
### Response
#### Success Response (200)
- **booking** (object) - The updated booking object.
#### Response Example
```json
{
"booking": {
"id": "k1jczlajuhy2xg",
"version": 1,
"status": "ACCEPTED",
"start_at": "2021-12-17T18:00:00Z",
"location_id": "SNTR5190QMFGM",
"customer_id": "K48SGF7H116G59WZJRMYJNJKA8",
"appointment_segments": [
{
"duration_minutes": 60,
"service_variation_id": "GUN7HNQBH7ZRARYZN52E7O4B",
"team_member_id": "2_uNFkqPYqV-AZB-7neN"
}
],
"creator_details": {
"creator_type": "TEAM_MEMBER",
"team_member_id": "2_uNFkqPYqV-AZB-7neN"
},
"source": "API",
"location_type": "BUSINESS_LOCATION"
}
}
```
```
--------------------------------
### Create a new .NET console project
Source: https://developer.squareup.com/docs/sdks/dotnet/quick-start
Use this command to create a new .NET console project for the SDK quickstart.
```bash
dotnet new console --name Quickstart
```
--------------------------------
### List Payment Refunds GET Request with Limit
Source: https://developer.squareup.com/docs/build-basics/common-api-patterns/pagination
For GET requests, include the `limit` as a query parameter to specify the number of results per page. This example retrieves refunds with a limit of 2.
```curl
curl https://connect.squareupsandbox.com/v2/refunds?limit=2 \
-H 'Square-Version: 2021-12-15' \
-H 'Authorization: Bearer {ACCESS_TOKEN}' \
-H 'Content-Type: application/json'
```
--------------------------------
### Initialize Go Module
Source: https://developer.squareup.com/docs/sdks/go/quick-start
Create a new directory for your project, navigate to it, and initialize a new Go module.
```go
mkdir quickstart
cd quickstart
go mod init quickstart
```
--------------------------------
### Update Booking Request Example
Source: https://developer.squareup.com/docs/bookings-api/use-the-api
This cURL command demonstrates how to update an existing booking's start time and date using the UpdateBooking endpoint. It requires the booking ID and the new desired start time.
```curl
curl https://connect.squareupsandbox.com/v2/bookings/k1jczlajuhy2xg \
-X PUT \
-H 'Square-Version: 2026-05-20' \
-H 'Authorization: Bearer {ACCESS_TOKEN}' \
-H 'Content-Type: application/json' \
-d '{
"booking": {
"start_at": "2021-12-17T18:00:00Z"
}
}'
```
--------------------------------
### Run Ruby Quickstart Application
Source: https://developer.squareup.com/docs/sdks/ruby/quick-start
Execute the Ruby quickstart script from your project directory to see the location listing in action.
```shell
ruby ./quickstart.rb
```
--------------------------------
### Run Python Quickstart Script
Source: https://developer.squareup.com/docs/sdks/python/quick-start
Execute the Python script from your project directory to run the quickstart application.
```bash
python ./quickstart.py
```
--------------------------------
### Create Project Directory and Navigate
Source: https://developer.squareup.com/docs/sdks/nodejs/quick-start
Create a new directory for your project and navigate into it using the terminal.
```bash
mkdir quickstart
cd ./quickstart
```
--------------------------------
### Sum Measures Example
Source: https://developer.squareup.com/docs/reporting-api/query-construction/measures
Use sum measures to get the total amounts for net sales, tips, and discounts over a specified period.
```json
{
"measures": [
"Orders.net_sales", // Sum of all net sales
"Orders.tips_amount", // Sum of all tips
"Orders.discounts_amount" // Sum of all discounts
],
"timeDimensions": [{
"dimension": "Orders.sale_timestamp",
"dateRange": ["2024-01-01", "2024-01-31"]
}],
"segments": ["Orders.closed_checks"]
}
```
--------------------------------
### PaymentAndRefunds Cube - Example Query
Source: https://developer.squareup.com/docs/reporting-api/cubes/core-cubes
This example query shows how to get payment totals by payment type (e.g., CARD, CASH) for the last 30 days using the PaymentAndRefunds cube. It includes measures for total amount and count, and dimensions for payment type.
```APIDOC
## PaymentAndRefunds Cube - Example Query
### Description
This query returns payment totals by payment type for the last 30 days.
### Query Structure
```json
{
"measures": [
"PaymentAndRefunds.total_amount",
"PaymentAndRefunds.count"
],
"dimensions": ["PaymentAndRefunds.type"],
"timeDimensions": [{
"dimension": "PaymentAndRefunds.reporting_timestamp",
"dateRange": "last 30 days"
}],
"order": {
"PaymentAndRefunds.total_amount": "desc"
}
}
```
```
--------------------------------
### Example Subscription Plan Object
Source: https://developer.squareup.com/docs/subscriptions-api/plans-and-variations
This is an example response showing a `SUBSCRIPTION_PLAN` object. It includes details about the plan and its associated `subscription_plan_variations`.
```json
{
"catalog_object": {
"type": "SUBSCRIPTION_PLAN",
"id": "VVH3YXQSQATSL3XR4LIKD3QM",
"updated_at": "2022-11-09T20:28:12.208Z",
"created_at": "2022-11-09T20:28:12.208Z",
"version": 1668025692208,
"present_at_all_locations": true,
"subscription_plan_data": {
"name": "Coffee Subscription",
"subscription_plan_variations": [{
"type": "SUBSCRIPTION_PLAN_VARIATION",
"id": "CUPS23SKJ7J4FD4F3IMVAEOH",
"updated_at": "2022-11-09T20:52:58.857Z",
"created_at": "2022-11-09T20:52:58.857Z",
"version": 1668027178857,
"present_at_all_locations": true,
"subscription_plan_variation_data": {
"name": "Coffee of the Month Club",
"phases": [{
"uid": "CR7TS35JYEVXC5BSDV5N7Z4Y",
"cadence": "MONTHLY",
"ordinal": 0,
"periods": 1,
"pricing": {
"type": "STATIC",
"price": {
"amount": 1000,
"currency": "USD"
}
}
},
{
"uid": "AW9ES43NVGRFC8AQRK8J5X1S",
"cadence": "MONTHLY",
"ordinal": 1,
"pricing": {
"type": "RELATIVE",
"discount_ids": ["5PFBH6YH5SB2F63FOIHJ7HWR"]
}
}],
"subscription_plan_id": "VVH3YXQSQATSL3XR4LIKD3QM"
}
}],
"eligible_category_ids": ["2CJLFP5C6G74W3U3HD5YAE5W"],
"all_items": false
}
}
}
```
--------------------------------
### Webhook Validation Setup in Python
Source: https://developer.squareup.com/docs/webhooks-api/validate-notifications
This Python example shows the initial setup for validating webhook event signatures using the `is_valid_webhook_event_signature` utility. It defines the notification URL, which is essential for the validation process. Further implementation details for handling the request and signature comparison would follow.
```python
# server.py
from http.server import BaseHTTPRequestHandler, HTTPServer
from square.utilities.webhooks_helper import is_valid_webhook_event_signature
# The URL where event notifications are sent.
NOTIFICATION_URL = 'https://example.com/webhook'
```
--------------------------------
### Run Node.js Application
Source: https://developer.squareup.com/docs/sdks/nodejs/quick-start
Execute the Node.js quickstart script from your terminal.
```bash
node quickstart.js
```
--------------------------------
### PERCENTAGE_PROCESSING_DEACTIVATION Entry Example
Source: https://developer.squareup.com/docs/payouts-api/list-payout-entries
Deducts the outstanding Percentage Processing balance from the seller’s account as the final installment for repaying a dispute-induced negative balance.
```json
{
"payout_entries": [
{
"id": "{id}",
"payout_id": "{payout_id}",
"effective_at": "2023-12-19T02:40:21Z",
"type": "PERCENTAGE_PROCESSING_DEACTIVATION",
"gross_amount_money": {
"amount": -91231,
"currency_code": "GBP"
},
"fee_amount_money": {
"amount": 0,
"currency_code": "GBP"
},
"net_amount_money": {
"amount": -91231,
"currency_code": "GBP"
}
}
]
}
```
--------------------------------
### Query for Sales by Channel
Source: https://developer.squareup.com/docs/reporting-api/cubes/types
Example query to get net sales grouped by sales channel (e.g., online, in-person) for the last 30 days.
```json
{
"measures": ["Orders.net_sales"],
"dimensions": ["Orders.sales_channel_id"],
"timeDimensions": [{
"dimension": "Orders.sale_timestamp",
"dateRange": "last 30 days"
}],
"segments": ["Orders.closed_checks"]
}
```
--------------------------------
### Python Quickstart: List Locations
Source: https://developer.squareup.com/docs/sdks/python/quick-start
This script initializes the Square client, lists all locations associated with your account, and prints their details. Ensure your SQUARE_ACCESS_TOKEN is set in your environment variables.
```python
from square import Square
from square.environment import SquareEnvironment
from square.core.api_error import ApiError
from dotenv import load_dotenv
import os
load_dotenv()
client = Square(
environment=SquareEnvironment.SANDBOX,
token=os.environ['SQUARE_ACCESS_TOKEN']
)
try:
response = client.locations.list()
for location in response.locations:
print(f"{location.id}: ", end="")
print(f"{location.name}, ", end="")
print(f"{location.address}, ", end="")
except ApiError as e:
for error in e.errors:
print(error.category)
print(error.code)
print(error.detail)
```
--------------------------------
### Extract SHA1 from Debug Certificate
Source: https://developer.squareup.com/docs/pos-api/cookbook/find-your-android-fingerprint
This is an example of the SHA1 output you will find when listing debug certificate information. Copy this value to get your debug fingerprint.
```text
SHA1: LOOK_FOR_THIS_VALUE
```
--------------------------------
### Get Order Details
Source: https://developer.squareup.com/docs/graphql/query-examples
This example demonstrates how to retrieve detailed information about a specific order, including line items, location, customer, and payment details.
```APIDOC
## Get Order Details
### Description
Retrieves detailed information about a specific order, including its items, customer, and payment information.
### Query
```graphql
query GetOrderDetails($merchantId: ID!, $orderId: ID!) {
orders(
filter: {
id: { equalToAnyOf: [$orderId]}
merchantId: { equalToAnyOf: [$merchantId]}}
) {
nodes {
id
createdAt
state
lineItems {
quantity
itemVariation {
merchantId
name
item {
name
}
}
modifiers {
name
}
}
location {
id
mcc
}
customer {
id
givenName
familyName
merchantId
}
totalMoney {
amount
currency
}
tenders {
type
location {
id
}
payment {
id
createdAt
totalMoney {
amount
currency
}
status
}
}
}
}
}
```
### Query Variables
```json
{
"merchantId": "MERCHANT_ID",
"orderId": "ORDER_ID"
}
```
### Example Response
```json
{
"data": {
"orders": {
"nodes": [
{
"id": "ORDER_ID",
"createdAt": "2023-10-27T10:00:00Z",
"state": "COMPLETED",
"lineItems": [
{
"quantity": 1,
"itemVariation": {
"merchantId": "MERCHANT_ID",
"name": "Item Name",
"item": {
"name": "Item Name"
}
},
"modifiers": [
{
"name": "Modifier Name"
}
]
}
],
"location": {
"id": "LOCATION_ID",
"mcc": "5411"
},
"customer": {
"id": "CUSTOMER_ID",
"givenName": "John",
"familyName": "Doe",
"merchantId": "MERCHANT_ID"
},
"totalMoney": {
"amount": 1000,
"currency": "USD"
},
"tenders": [
{
"type": "CARD",
"location": {
"id": "LOCATION_ID"
},
"payment": {
"id": "PAYMENT_ID",
"createdAt": "2023-10-27T10:05:00Z",
"totalMoney": {
"amount": 1000,
"currency": "USD"
},
"status": "APPROVED"
}
}
]
}
]
}
}
}
```
```
--------------------------------
### Example Output of Listed Location
Source: https://developer.squareup.com/docs/sdks/php/quick-start
This is an example of the output you should expect when the quickstart.php script successfully lists a location from your Square account.
```text
LHI1YXJ8YSV5Z: Default Test Account, 1600 Pennsylvania Ave NW, Washington
```
--------------------------------
### Test Sample Application
Source: https://developer.squareup.com/docs/orders-api/quick-start/step-2
Run this command in the root directory of the order-ahead sample application to test your configuration and confirm that your application is authorized.
```bash
npm test
```
--------------------------------
### Search for Vendors by Name
Source: https://developer.squareup.com/docs/vendors-api/search-for-vendors
Use the `name` filter to specify part or all of the targeted vendor names. This example searches for vendors whose name starts with 'Vendor'.
```cURL
curl https://connect.squareupsandbox.com/v2/vendors/search \
-X POST \
-H 'Square-Version: 2026-05-20' \
-H 'Authorization: Bearer {ACCESS_TOKEN}' \
-H 'Content-Type: application/json' \
-d '{
"filter": {
"name": [
"Vendor"
]
}
}'
```
--------------------------------
### Navigate to Project Directory
Source: https://developer.squareup.com/docs/sdks/java/quick-start
Change into the newly created project directory to access its files.
```bash
cd quickstart
```
--------------------------------
### Install Square Go SDK
Source: https://developer.squareup.com/docs/sdks/go/quick-start
Add the Square Go SDK library to your Go module.
```go
go get github.com/square/square-go-sdk
```
--------------------------------
### Query for Current Merchant ID
Source: https://developer.squareup.com/docs/devtools/graphqlexplorer
Use this query to retrieve the ID of the merchant associated with the access token. This is a basic query to get started with GraphQL Explorer.
```graphql
{
currentMerchant {
id
}
}
```
--------------------------------
### Response for QUICK_AMOUNTS_SETTINGS creation
Source: https://developer.squareup.com/docs/catalog-api/cookbook/set-quick-amounts
This is an example of a successful response when creating a QUICK_AMOUNTS_SETTINGS object. It includes the created object's details and ID mappings.
```json
{
"catalog_object": {
"type": "QUICK_AMOUNTS_SETTINGS",
"id": "IXEVKMKA6CWG6CH4MFB32YPV",
"updated_at": "2020-04-17T20:50:44.31Z",
"version": 1587156644310,
"is_deleted": false,
"present_at_all_locations": false,
"present_at_location_ids": [
"{{LOCATION_ID}}"
],
"quick_amounts_settings_data": {
"option": "MANUAL",
"eligible_for_auto_amounts": false,
"amounts": [
{
"type": "QUICK_AMOUNT_TYPE_MANUAL",
"amount": {
"amount": 855,
"currency": "USD"
},
"score": 100,
"ordinal": 1
},
{
"type": "QUICK_AMOUNT_TYPE_MANUAL",
"amount": {
"amount": 85,
"currency": "USD"
},
"score": 100,
"ordinal": 1
}
]
}
},
"id_mappings": [
{
"client_object_id": "#quick_amount_1",
"object_id": "IXEVKMKA6CWG6CH4MFB32YPV"
}
]
}
```
--------------------------------
### PERCENTAGE_PROCESSING_REPAYMENT Entry Example
Source: https://developer.squareup.com/docs/payouts-api/list-payout-entries
Represents withheld funds from a payment to cover a negative balance, serving as an installment to repay a dispute amount offset during Percentage Processing enrollment.
```json
{
"payout_entries": [
{
"id": "{id}",
"payout_id": "{payout_id}",
"effective_at": "2023-12-18T07:51:14Z",
"type": "PERCENTAGE_PROCESSING_REPAYMENT",
"gross_amount_money": {
"amount": -200,
"currency_code": "GBP"
},
"fee_amount_money": {
"amount": 0,
"currency_code": "GBP"
},
"net_amount_money": {
"amount": -200,
"currency_code": "GBP"
}
}
]
}
```
--------------------------------
### Search Catalog Objects by Name Prefix (Happy)
Source: https://developer.squareup.com/docs/catalog-api/search-catalog-objects
Another example of using a prefix query to search for catalog objects. This demonstrates searching for names starting with 'happy'.
```cURL
curl https://connect.squareupsandbox.com/v2/catalog/search \
-X POST \
-H 'Square-Version: 2026-05-20' \
-H 'Authorization: Bearer {ACCESS_TOKEN}' \
-H 'Content-Type: application/json' \
-d '{
"query": {
"prefix_query": {
"attribute_name": "name",
"attribute_prefix": "happy"
}
}
}'
```
--------------------------------
### Initialize SquareClient and List Locations (PHP)
Source: https://developer.squareup.com/docs/sdks/php/quick-start
This snippet demonstrates how to initialize the SquareClient with your access token and environment settings, then lists all locations associated with your Square account. Ensure your Square access token is loaded from a .env file.
```php
load();
$square = new SquareClient(
token: $_ENV['SQUARE_ACCESS_TOKEN'],
options: ['baseUrl' => Environments::Sandbox->value // Used by default
]
);
try {
$response = $square->locations->list();
foreach ($response->getLocations() as $location) {
printf(
"%s: %s, %s, %s",
$location->getId(),
$location->getName(),
$location->getAddress()?->getAddressLine1(),
$location->getAddress()?->getLocality()
);
}
} catch (SquareException $e) {
echo 'Square API Exception occurred: ' . $e->getMessage() . "\n";
echo 'Status Code: ' . $e->getCode() . "\n";
}
?>
```