Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Square Laravel Package

nikolag/square

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. 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
    
  2. 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,
            ]);
        }
    }
    
  3. Key Files:

    • config/square.php: Configuration for API endpoints and defaults.
    • app/SquareService.php: Base service class (if extending functionality).

Implementation Patterns

Core Workflows

Customer Management

  1. Create/Update Customers:

    $customer = $this->createCustomer([
        'given_name' => 'John',
        'family_name' 'Doe',
        'email_address' => 'john@example.com',
        'phone_number' => '+1234567890',
    ]);
    
    • Use updateCustomer() with the customer ID to modify existing records.
  2. Retrieve Customers:

    $customer = $this->getCustomer($customerId);
    $customers = $this->listCustomers(['limit' => 10]);
    
  3. Delete Customers:

    $this->deleteCustomer($customerId);
    

Order Processing

  1. 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,
    ]);
    
  2. Retrieve Orders:

    $order = $this->getOrder($orderId);
    $orders = $this->listOrders(['limit' => 5]);
    
  3. Capture Payments:

    $payment = $this->capturePayment($orderId, $amountMoney);
    

Payment Handling

  1. 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,
    ]);
    
  2. Refund Payments:

    $refund = $this->createRefund($paymentId, [
        'amount_money' => ['amount' => 500, 'currency' => 'USD'],
        'reason' => 'Customer refund',
    ]);
    

Integration Tips

  1. Use Traits for Modularity: Extend your service classes with traits like Customer, Order, or Payment to isolate concerns:

    class SquareOrderService {
        use Order, Payment;
    }
    
  2. 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,
        ],
    ];
    
  3. 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);
    
  4. Testing: Mock the SquareService in tests:

    $this->mock(SquareService::class)->shouldReceive('createCustomer')->once()->andReturn($mockCustomer);
    

Gotchas and Tips

Pitfalls

  1. Idempotency Keys:

    • Always include a unique idempotency_key for createOrder or createPayment to avoid duplicate charges.
    • Square will reject requests without this key in production.
  2. Rate Limits:

    • Square enforces rate limits. Handle 429 Too Many Requests responses gracefully:
    try {
        $this->createPayment(...);
    } catch (\Nikolag\Square\Exceptions\RateLimitExceeded $e) {
        sleep($e->getRetryAfter());
        retry();
    }
    
  3. Webhook Verification:

    • Square webhooks require verification. Use the SquareWebhook middleware to validate signatures:
    Route::post('/square-webhook', [SquareWebhookHandler::class, 'handle'])
        ->middleware('square.webhook');
    
  4. Sandbox vs. Production:

    • Test thoroughly in sandbox mode before switching to production. Sandbox uses mock data (e.g., 4242424242424242 for test cards).
  5. Location ID:

    • Ensure SQUARE_LOCATION_ID matches the location where transactions are processed. Incorrect IDs will fail silently in some cases.

Debugging

  1. Enable Debug Logging: Add to config/square.php:

    'debug' => env('SQUARE_DEBUG', false),
    

    Logs will appear in storage/logs/square.log.

  2. 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.
  3. API Response Inspection: Use dd($this->lastResponse()) to inspect raw Square API responses for debugging.

Extension Points

  1. 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);
    }
    
  2. Webhook Handlers: Create custom handlers for specific events:

    class CustomPaymentHandler {
        public function handlePaymentSucceeded(PaymentSucceeded $event) {
            // Logic for custom payment processing
        }
    }
    
  3. Catalog Integration: Use Square’s Catalog API to manage items/variations:

    $item = $this->createCatalogItem([
        'name' => 'Product Name',
        'description' => 'Description',
        'type' => 'ITEM',
    ]);
    
  4. Loyalty Programs: Integrate Square’s Loyalty API by extending the base service:

    use Nikolag\Square\Traits\Loyalty;
    
    class LoyaltyService {
        use Loyalty;
    }
    

Configuration Quirks

  1. Environment Variables:

    • SQUARE_ENVIRONMENT: Must be sandbox or production (case-sensitive).
    • SQUARE_ACCESS_TOKEN: Generate via Square Developer Dashboard.
  2. Timeouts:

    • Adjust config/square.php timeout settings for slow networks:
    'timeout' => 30, // seconds
    
  3. Retry Logic: Enable automatic retries for transient failures:

    'retry' => [
        'max_attempts' => 3,
        'delay' => 100, // ms
    ],
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle