Installation:
composer require nikolag/laravel-square
Publish the config file:
php artisan vendor:publish --provider="Nikolag\Square\SquareServiceProvider"
Configure .env with your Square API credentials:
SQUARE_ENVIRONMENT=sandbox # or 'production'
SQUARE_ACCESS_TOKEN=your_access_token_here
SQUARE_LOCATION_ID=your_location_id
First Use Case: Create a customer and retrieve their details:
use Nikolag\Square\Traits\Customer;
class CustomerService {
use Customer;
public function createCustomer(string $email, string $firstName, string $lastName) {
return $this->createCustomer([
'given_name' => $firstName,
'family_name' => $lastName,
'email_address' => $email,
]);
}
}
Key Files:
config/square.php: Configuration for API endpoints and defaults.app/SquareService.php: Base service class (if extending functionality).Create/Update Customers:
$customer = $this->createCustomer([
'given_name' => 'John',
'family_name' 'Doe',
'email_address' => 'john@example.com',
'phone_number' => '+1234567890',
]);
updateCustomer() with the customer ID to modify existing records.Retrieve Customers:
$customer = $this->getCustomer($customerId);
$customers = $this->listCustomers(['limit' => 10]);
Delete Customers:
$this->deleteCustomer($customerId);
Create Orders:
$order = $this->createOrder([
'idempotency_key' => 'unique_key_123',
'line_items' => [
['quantity' => 1, 'catalog_object_id' => 'item_123', 'variation_id' => null],
],
'customer_id' => $customerId,
]);
Retrieve Orders:
$order = $this->getOrder($orderId);
$orders = $this->listOrders(['limit' => 5]);
Capture Payments:
$payment = $this->capturePayment($orderId, $amountMoney);
Create Payments:
$payment = $this->createPayment([
'idempotency_key' => 'unique_key_456',
'amount_money' => ['amount' => 1000, 'currency' => 'USD'],
'source_id' => $cardNonce, // From Square Web Payments
'customer_id' => $customerId,
]);
Refund Payments:
$refund = $this->createRefund($paymentId, [
'amount_money' => ['amount' => 500, 'currency' => 'USD'],
'reason' => 'Customer refund',
]);
Use Traits for Modularity:
Extend your service classes with traits like Customer, Order, or Payment to isolate concerns:
class SquareOrderService {
use Order, Payment;
}
Leverage Events:
Subscribe to Square webhooks (e.g., payment.succeeded) via Laravel’s Event system:
// In EventServiceProvider
protected $listen = [
\Nikolag\Square\Events\PaymentSucceeded::class => [
\App\Listeners\HandlePaymentSuccess::class,
],
];
Batch Operations:
Use listCustomers() or listOrders() with pagination for large datasets:
$cursor = null;
do {
$customers = $this->listCustomers(['limit' => 100, 'cursor' => $cursor]);
$cursor = $customers['cursor'] ?? null;
} while ($cursor);
Testing:
Mock the SquareService in tests:
$this->mock(SquareService::class)->shouldReceive('createCustomer')->once()->andReturn($mockCustomer);
Idempotency Keys:
idempotency_key for createOrder or createPayment to avoid duplicate charges.Rate Limits:
429 Too Many Requests responses gracefully:try {
$this->createPayment(...);
} catch (\Nikolag\Square\Exceptions\RateLimitExceeded $e) {
sleep($e->getRetryAfter());
retry();
}
Webhook Verification:
SquareWebhook middleware to validate signatures:Route::post('/square-webhook', [SquareWebhookHandler::class, 'handle'])
->middleware('square.webhook');
Sandbox vs. Production:
4242424242424242 for test cards).Location ID:
SQUARE_LOCATION_ID matches the location where transactions are processed. Incorrect IDs will fail silently in some cases.Enable Debug Logging:
Add to config/square.php:
'debug' => env('SQUARE_DEBUG', false),
Logs will appear in storage/logs/square.log.
Common Errors:
INVALID_REQUEST_ERROR: Validate payload structure (e.g., missing amount_money).NOT_FOUND: Check customer_id, order_id, or location_id existence.AUTHENTICATION_ERROR: Verify SQUARE_ACCESS_TOKEN and permissions.API Response Inspection:
Use dd($this->lastResponse()) to inspect raw Square API responses for debugging.
Custom Fields: Extend customer/order models with additional fields by overriding trait methods:
public function createCustomer(array $data) {
$data['custom_field'] = 'value';
return parent::createCustomer($data);
}
Webhook Handlers: Create custom handlers for specific events:
class CustomPaymentHandler {
public function handlePaymentSucceeded(PaymentSucceeded $event) {
// Logic for custom payment processing
}
}
Catalog Integration: Use Square’s Catalog API to manage items/variations:
$item = $this->createCatalogItem([
'name' => 'Product Name',
'description' => 'Description',
'type' => 'ITEM',
]);
Loyalty Programs: Integrate Square’s Loyalty API by extending the base service:
use Nikolag\Square\Traits\Loyalty;
class LoyaltyService {
use Loyalty;
}
Environment Variables:
SQUARE_ENVIRONMENT: Must be sandbox or production (case-sensitive).SQUARE_ACCESS_TOKEN: Generate via Square Developer Dashboard.Timeouts:
config/square.php timeout settings for slow networks:'timeout' => 30, // seconds
Retry Logic: Enable automatic retries for transient failures:
'retry' => [
'max_attempts' => 3,
'delay' => 100, // ms
],
How can I help you explore Laravel packages today?