Developer notes
Technical reference for developers who customize Square Payments + POS Sync.
Add-on identity
Section titled “Add-on identity”| Item | Value |
|---|---|
| Add-on id | kv_square_payments |
| Function prefix | fn_kv_square_payments_ |
| Language variables | kv_square_payments.* |
| CSS scope | .kv-square-payments |
| PHP namespace | Tygh\Addons\KvSquarePayments |
| Preset | payment (generated by kv new --kind integration), extended with the POS sync |
Sources of the Square API usage
Section titled “Sources of the Square API usage”Every endpoint, field and status below comes from Square’s own documentation. Two sources were read:
- OAS: the OpenAPI file Square publishes,
github.com/square/connect-api-specification(api.json,info.version2.0, theSquare-Versionliteral2026-11-18). Field names, enums, security scopes and the doc examples intests/fixtures/come from it. - DOC: pages of
developer.squareup.com(Web Payments SDK, SCA, OAuth, idempotency, webhooks). - SDK: the source of Square’s PHP SDK (
square/square-php-sdk,WebhooksHelper::verifySignature), used only to confirm the webhook signature formula, which the docs describe in words.
Items the documentation does not state are listed under “Flagged” and are never guessed in code that depends on them.
Hosts and headers
Section titled “Hosts and headers”| Item | Value | Source |
|---|---|---|
| Production API host | https://connect.squareup.com |
OAS servers[0].url |
| Sandbox API host | https://connect.squareupsandbox.com |
DOC OAuth overview (authorize URL on the sandbox host) |
| Authentication | Authorization: Bearer <access token> (personal access token, or an OAuth access token) |
OAS security: oauth2 |
| Version | Square-Version: 2026-11-18, pinned in Client\Api::VERSION |
OAS x-fern-global-headers; confirmed as a published version (the latest entry) in Square’s changelog, developer.squareup.com/docs/changelog/connect, 2026-11-26 |
| Content type | application/json |
DOC |
| Web Payments SDK script (sandbox) | https://sandbox.web.squarecdn.com/v1/square.js |
DOC Web Payments quickstart |
| Web Payments SDK script (production) | https://web.squarecdn.com/v1/square.js |
Flagged: the production URL was not on the page we read; it is the production counterpart of the sandbox URL. Confirm before a live launch. |
Endpoints used
Section titled “Endpoints used”| Call | Endpoint | Fields used | Scope (OAS) | Where |
|---|---|---|---|---|
| ListLocations | GET /v2/locations |
locations[].id, name, status (ACTIVE), currency, country |
MERCHANT_PROFILE_READ | Api::locations, Client::checkLocations |
| CreatePayment | POST /v2/payments |
request: source_id (required), idempotency_key (required, 1-45 chars), amount_money, autocomplete, location_id, reference_id (max 40), note (max 500), verification_token, buyer_email_address, customer_details{customer_initiated, seller_keyed_in}; answer payment{id, status, amount_money, refunded_money, card_details.card{card_brand,last_4}, receipt_url, delayed_until, refund_ids} |
PAYMENTS_WRITE | Api::createPayment, PaymentService::charge |
| GetPayment | GET /v2/payments/{payment_id} |
same object | PAYMENTS_READ | Api::getPayment, PaymentService::sync |
| ListPayments | GET /v2/payments |
query begin_time, end_time, location_id, sort_order, cursor, limit; matched on reference_id |
PAYMENTS_READ | Api::listPayments, PaymentService::settle |
| CompletePayment | POST /v2/payments/{payment_id}/complete |
captures a payment with status APPROVED | PAYMENTS_WRITE | PaymentService::capture |
| CancelPayment | POST /v2/payments/{payment_id}/cancel |
voids a payment with status APPROVED | PAYMENTS_WRITE | PaymentService::voidPayment |
| RefundPayment | POST /v2/refunds |
idempotency_key (max 45), amount_money (required), payment_id, reason (max 192; ours starts with the marker [kvrf<row id>], the only way to tie a refund found after a lost answer to our row: RefundPayment has no reference field; a Dashboard refund of the same amount is never adopted); answer refund{id, status, amount_money, payment_id} |
PAYMENTS_WRITE | Api::refund, PaymentService::sendRefund |
| GetPaymentRefund | GET /v2/refunds/{refund_id} |
refund.status |
PAYMENTS_READ | PaymentService::refundSync |
| SearchCatalogObjects | POST /v2/catalog/search |
object_types: ["ITEM_VARIATION"], begin_time, cursor, limit (advisory, max 1,000); objects item_variation_data{item_id, sku, price_money, pricing_type, track_inventory}, version, is_deleted |
ITEMS_READ | Api::searchVariations, Sync::link |
| BatchRetrieveCatalogObjects | POST /v2/catalog/batch-retrieve |
object_ids |
ITEMS_READ | Api::retrieveObjects (price push) |
| BatchUpsertCatalogObjects | POST /v2/catalog/batch-upsert |
idempotency_key, batches[].objects[] (the whole object with its version) |
ITEMS_WRITE | Api::batchUpsert, Sync::prices |
| BatchRetrieveInventoryCounts | POST /v2/inventory/counts/batch-retrieve |
catalog_object_ids, location_ids, states: ["IN_STOCK"], cursor; answer counts[]{catalog_object_id, state, location_id, quantity (string), calculated_at} |
INVENTORY_READ | Api::inventoryCounts, Sync::stockChunk |
| BatchChangeInventory | POST /v2/inventory/changes/batch-create |
idempotency_key, changes[]{type: PHYSICAL_COUNT, physical_count{catalog_object_id, state: IN_STOCK, location_id, quantity (string), occurred_at}}, ignore_unchanged_counts |
INVENTORY_WRITE | Api::inventoryChange |
| SearchOrders | POST /v2/orders/search |
location_ids, query.filter.state_filter.states ["COMPLETED"], query.filter.date_time_filter.updated_at.start_at, query.sort, cursor, limit (max 1,000); answer orders[] |
ORDERS_READ | Api::searchOrders, OrderImport |
| ObtainToken | POST /oauth2/token |
client_id, client_secret, grant_type (authorization_code | refresh_token), code, redirect_uri, refresh_token; answer access_token, refresh_token, expires_at, merchant_id |
none (no bearer) | Api::obtainToken, Oauth |
OAuth scopes requested (Oauth::SCOPES): MERCHANT_PROFILE_READ, PAYMENTS_READ, PAYMENTS_WRITE, ORDERS_READ, ITEMS_READ, ITEMS_WRITE, INVENTORY_READ, INVENTORY_WRITE (names from the OAS security entries of the endpoints above).
Statuses
Section titled “Statuses”| Object | Values | Source | Mapping (Transition) |
|---|---|---|---|
Payment.status |
APPROVED, PENDING, COMPLETED, CANCELED, FAILED | OAS Payment.status description |
APPROVED = authorized, PENDING = pending, COMPLETED = paid, CANCELED = canceled, FAILED = failed. An unknown word stays pending, never failed. |
Payment.card_details.status |
AUTHORIZED, CAPTURED, VOIDED, FAILED | OAS | shown by the read-back only |
PaymentRefund.status |
PENDING, COMPLETED, REJECTED, FAILED | OAS PaymentRefund.status |
pending stays pending (webhook or queue finishes it); REJECTED / FAILED give the reserved amount back |
CatalogObjectType |
ITEM, ITEM_VARIATION, … | OAS | only ITEM_VARIATION (and ITEM, to reach its nested variations) |
InventoryState |
IN_STOCK, SOLD, … | OAS | only IN_STOCK counts are read and written |
Order.state |
OPEN, COMPLETED, CANCELED, DRAFT | OAS | only COMPLETED orders are imported |
Location.status |
ACTIVE, INACTIVE | OAS | only ACTIVE locations are offered |
Errors
Section titled “Errors”Error body: {"errors": [{"category", "code", "detail", "field"}]} (OAS Error; the docs example is ADDRESS_VERIFICATION_FAILURE / PAYMENT_METHOD_ERROR). Categories: API_ERROR, AUTHENTICATION_ERROR, INVALID_REQUEST_ERROR, RATE_LIMIT_ERROR, PAYMENT_METHOD_ERROR, REFUND_ERROR, MERCHANT_SUBSCRIPTION_ERROR, EXTERNAL_VENDOR_ERROR (OAS ErrorCategory). Codes the add-on acts on: RATE_LIMITED and HTTP 429 (pause once, then the queue waits), TEMPORARY_ERROR (503, retried), ACCESS_TOKEN_EXPIRED (OAuth refresh once), UNAUTHORIZED / ACCESS_TOKEN_REVOKED (card payments paused until a good connection test), IDEMPOTENCY_KEY_REUSED. Card refusal codes of CreatePayment (DOC CreatePayment error list): GENERIC_DECLINE, INSUFFICIENT_FUNDS, CVV_FAILURE, ADDRESS_VERIFICATION_FAILURE, INVALID_POSTAL_CODE, CARD_EXPIRED, EXPIRATION_FAILURE, CARD_TOKEN_EXPIRED, CARD_TOKEN_USED, CARD_NOT_SUPPORTED and others (PaymentService::isDeclineCode). The customer never sees Square’s raw text: PaymentService::friendly() maps codes to the language variables kv_square_payments.err_* / declined.
Webhooks
Section titled “Webhooks”- Header:
x-square-hmacsha256-signature(DOC “Validate webhook notifications”). - Signature: base64 of HMAC-SHA256 with the subscription’s signature key over the notification URL concatenated with the raw request body (SDK
WebhooksHelper::verifySignature:$payload = $notificationUrl . $requestBody; base64_encode(hash_hmac('sha256', $payload, $signatureKey, true))). The DOC page says the three inputs (key, URL, raw body) and asks for a constant-time comparison; it does not spell out the concatenation or the encoding, the SDK does.Webhook::verifyuseshash_equals. The URL is the one saved on the Connection page (Accounts::notificationUrl), which must equal the subscription URL character for character. - Event shapes (OAS event schemas):
{merchant_id, type, event_id, created_at, data{type, id, object{payment | refund | inventory_counts}}}. Event types handled:payment.created,payment.updated,refund.created,refund.updated,inventory.count.updated,catalog.version.updated,order.created,order.updated. The state is always read back (GetPayment / GetPaymentRefund); the body is a hint. Only type and ids are stored in the queue (no buyer data). - Idempotency:
event_idbecomes the job’s unique key, so a repeated delivery is one job.
Web Payments SDK on the payment page (PaymentPage)
Section titled “Web Payments SDK on the payment page (PaymentPage)”| Step | Call | Source |
|---|---|---|
| Initialise | Square.payments(applicationId, locationId) |
DOC quickstart |
| Card | payments.card(), card.attach('#container'), card.tokenize(verificationDetails) -> {status: 'OK', token} or {status, errors} |
DOC take-card-payment |
| Apple Pay | payments.paymentRequest({countryCode, currencyCode, total: {amount, label}}), payments.applePay(request) (no attach), tokenize() called synchronously from the click |
DOC apple-pay (Safari only, HTTPS, domain verification file) |
| Google Pay | payments.googlePay(request), googlePay.attach('#google-pay-button'), tokenize() |
DOC google-pay |
| SCA / 3-D Secure | tokenize(verificationDetails) with {amount, billingContact{givenName, familyName, email, phone, addressLines, city, state, countryCode}, currencyCode, intent: 'CHARGE', customerInitiated: true, sellerKeyedIn: false}; the challenge runs inside the SDK and one token comes back |
DOC sca-overview and take-card-payment |
The browser posts only the one-time token (and the attempt’s secret key) to kv_square_payments.charge; the amount, the currency and the location come from the stored attempt.
Legacy verifyBuyer: the SCA page points to a “migrate from verifyBuyer” section and documents tokenize() with verification details as the current method. The add-on uses that method. payments.verifyBuyer is not called.
Code flow with the merchant’s own Square application: authorize URL <host>/oauth2/authorize?client_id=...&scope=...&state=... (session=false is not supported in the sandbox and is only added in live mode), the code is valid 5 minutes and once, ObtainToken with grant_type authorization_code and the application secret, access token valid 30 days, code-flow refresh tokens do not expire (DOC OAuth overview). Oauth::refresh runs under a database lock, a job refreshes tokens that expire within 7 days, and ACCESS_TOKEN_EXPIRED triggers one refresh and one repeat of the call.
Flagged (not stated in the Square documentation we read, so not relied on)
Section titled “Flagged (not stated in the Square documentation we read, so not relied on)”- How long Square remembers an idempotency key (the docs say only that a key must be unique, that the same key with the same body returns the first response and that a different body is an error). The add-on only repeats a request with the same key while the attempt is unconfirmed, and looks the object up first (ListPayments by
reference_id,GetPayment.refund_ids). - The documented rate-limit numbers and whether a
Retry-Afterheader is sent. The add-on honours the header when it is present and otherwise waits 1 second inside a web request and 2 minutes in the queue. - Whether wallets (Apple Pay / Google Pay) accept
tokenize(verificationDetails); the SCA page says “call tokenize() with verification details” for payments in general, and the Google Pay page says digital wallet payments “may be declined” without SCA. - The production script URL of the SDK (see above).
- A required User-Agent: none is documented; the client sends
Square Payments + POS Sync (https://cs-cart.kaviolabs.com). - Behaviour of
delay_durationdefaults forautocomplete: false: the add-on showsdelayed_untilfrom the answer and sends nodelay_duration.
Structure
Section titled “Structure”| Class | Role |
|---|---|
Client\BaseClient |
HTTP (cURL, TLS verification, timeouts), JSON, error mapping, masked logging (scaffold, unchanged) |
Client\Api |
All Square calls (above), the one-time 429 pause, the one-time OAuth refresh |
Client |
Client per company, the connection test and the location rule |
Accounts, Secret, Oauth |
Credentials (application id, access token, signature key, location, OAuth secret and refresh token) sealed with AES-256-GCM; one account per store owner or per vendor |
Config, Access |
Settings, owner mode, who may see and manage what |
PaymentService |
initialize, charge (idempotency key saved first, per-order lock, new attempt row for a new card), adopt (the only place that applies a payment state), settle (lost answer), capture / voidPayment, refund / sendRefund / refundSync |
PaymentPage |
The payment page (card, Apple Pay, Google Pay) and its config |
Transition |
Pure status logic: Square status to local status to order status, never backwards |
Sync, Stock |
Catalog link by SKU, the stock merge rule, price push |
OrderImport |
Square POS orders to CS-Cart orders |
Queue, Jobs, JobException |
Job queue: back-off 5 min / 15 min / 1 h / 3 h / 12 h, per-job isolation, overlap lock; types webhook, sync, refund, refund_sync, oauth_refresh, sync_catalog, import_orders, probe |
Log |
Event log with masking (tokens, card tokens, buyer data), filters, CSV, retention |
Webhook |
Signature check and event ids |
Retention |
Keep-data policy: payment records and the connection survive an uninstall unless the purge setting is on |
Database tables
Section titled “Database tables”| Table | Purpose |
|---|---|
?:kv_square_payments_accounts |
Credentials per company (secrets sealed), location in extra, last connection check |
?:kv_square_payments_oauth |
OAuth application secret and refresh token (sealed), expiry, pending state |
?:kv_square_payments_transactions |
One row per payment attempt: idempotency key, Square payment id, status, amounts, card text, receipt, delayed_until |
?:kv_square_payments_refunds |
One row per refund: idempotency key, Square refund id, status |
?:kv_square_payments_map |
Catalog link: SKU, product, Square variation, last agreed quantity and price |
?:kv_square_payments_state |
Cursors and last run times of the sync |
?:kv_square_payments_orders |
Imported Square orders (one row per Square order id) |
?:kv_square_payments_jobs, ?:kv_square_payments_log |
Queue and log |
Hooks used
Section titled “Hooks used”| Hook | Handler | Purpose |
|---|---|---|
change_order_status_post |
fn_kv_square_payments_change_order_status_post |
Queue a full refund when the order reaches the “refund status” setting |
prepare_checkout_payment_methods |
fn_kv_square_payments_prepare_checkout_payment_methods |
Hide the method while the add-on cannot take payments (disabled, unlicensed, not connected, no location) |
init_templater_post |
fn_kv_square_payments_init_templater_post |
Only while an upgrade synchronization is pending |
Template hook orders:tabs_extra (post) |
hooks/orders/tabs_extra.post.tpl |
The “Square payment” tab on the order page |
Payment processor: payments/kv_square_payments.php (start = payment page, payment_notification.return|cancel). Public endpoints: kv_square_payments.charge, .webhook, .cron.
Test the HTTP layer without Square
Section titled “Test the HTTP layer without Square”The base URL can be overridden for tests in config.local.php (development only):
$config['kv_square_payments_base_url'] = 'http://127.0.0.1:11830';node tests/mock-server/server.js 11830 starts a local stand-in built from the documentation (and serves a fake Web Payments SDK at /v1/square.js); node tests/e2e/e2e.mjs --root <store dir> refuses to run unless the store points at a local mock; php tests/unit.php runs the unit tests with the doc examples in tests/fixtures/. This proves the add-on against the documentation, not against a live Square account.
Template overrides
Section titled “Template overrides”Admin templates live in design/backend/templates/addons/kv_square_payments/. Do not edit them in a store; they are replaced on update.
Square is a trademark of Block, Inc. This add-on is not affiliated with or endorsed by Square.