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

Laravel Square Laravel Package

treesapuk/laravel-square

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require nikolag/laravel-square

Publish the config file:

php artisan vendor:publish --provider="Nikolag\Square\SquareServiceProvider"

Configure .env with your Square credentials:

SQUARE_ENVIRONMENT=sandbox  # or 'production'
SQUARE_ACCESS_TOKEN=your_access_token_here
SQUARE_LOCATION_ID=your_location_id
  1. First Use Case: Create a customer and charge them in a single flow:

    use Nikolag\Square\Traits\CustomerTrait;
    use Nikolag\Square\Traits\PaymentTrait;
    
    class CheckoutController extends Controller
    {
        use CustomerTrait, PaymentTrait;
    
        public function checkout(Request $request)
        {
            // Create a customer
            $customer = $this->createCustomer([
                'given_name' => 'John',
                'family_name' => 'Doe',
                'email_address' => 'john@example.com',
                'phone_number' => '+1234567890',
            ]);
    
            // Charge the customer
            $payment = $this->createPayment([
                'idempotency_key' => 'unique_key',
                'source_id' => $customer->id,
                'amount_money' => [
                    'amount' => 1000, // $10.00
                    'currency' => 'USD',
                ],
                'note' => 'Order #12345',
            ]);
    
            return response()->json($payment);
        }
    }
    
  2. Key Files:

    • config/square.php: Central configuration for API endpoints, timeouts, and defaults.
    • app/Providers/SquareServiceProvider.php: Service binding and boot logic.
    • vendor/nikolag/laravel-square/src/Traits/: Traits for common operations (e.g., CustomerTrait, PaymentTrait).

Implementation Patterns

Core Workflows

  1. Customer Management:

    • Create/Update: Use createCustomer() or updateCustomer() with an array of attributes.
      $customer = $this->createCustomer([
          'given_name' => 'Jane',
          'family_name' => 'Smith',
          'email_address' => 'jane@example.com',
          'address' => [
              'address_line_1' => '123 Main St',
              'locality' => 'San Francisco',
              'administrative_district_level_1' => 'CA',
              'postal_code' => '94105',
              'country' => 'US',
          ],
      ]);
      
    • Retrieve: Fetch by ID or email.
      $customer = $this->getCustomerById($customerId);
      // or
      $customer = $this->getCustomerByEmail('jane@example.com');
      
    • List: Paginate customers with optional filters.
      $customers = $this->listCustomers(['limit' => 10]);
      
  2. Payments and Orders:

    • Charge a Customer:
      $payment = $this->createPayment([
          'idempotency_key' => Str::uuid()->toString(),
          'source_id' => $customer->id,
          'amount_money' => ['amount' => 5000, 'currency' => 'USD'],
          'note' => 'Subscription fee',
      ]);
      
    • Create an Order:
      $order = $this->createOrder([
          'idempotency_key' => Str::uuid()->toString(),
          'line_items' => [
              [
                  'quantity' => '1',
                  'base_price_money' => ['amount' => 2000, 'currency' => 'USD'],
                  'catalog_object_id' => 'item_123',
              ],
          ],
          'customer_id' => $customer->id,
      ]);
      
    • Capture/Refund:
      $this->capturePayment($payment->id, ['amount_money' => ['amount' => 5000, 'currency' => 'USD']]);
      // or
      $this->refundPayment($payment->id, ['reason' => 'Customer request']);
      
  3. Webhooks:

    • Register a webhook endpoint in routes/web.php:
      Route::post('/square/webhook', 'SquareWebhookController@handleWebhook');
      
    • Handle events in SquareWebhookController:
      public function handleWebhook(Request $request)
      {
          $event = $request->json()->all();
          $this->processWebhook($event); // Use the provided trait method
      }
      

Integration Tips

  • Service Container Binding: Bind the Square client to the container in AppServiceProvider for dependency injection:

    public function register()
    {
        $this->app->bind(\Nikolag\Square\Square::class, function ($app) {
            return new \Nikolag\Square\Square(
                config('square.access_token'),
                config('square.environment'),
                config('square.location_id')
            );
        });
    }
    

    Then inject Square into controllers/services:

    public function __construct(\Nikolag\Square\Square $square)
    {
        $this->square = $square;
    }
    
  • Error Handling: Wrap Square API calls in try-catch blocks to handle exceptions:

    try {
        $payment = $this->square->createPayment($paymentData);
    } catch (\Nikolag\Square\Exceptions\SquareException $e) {
        Log::error('Square payment failed: ' . $e->getMessage());
        return response()->json(['error' => 'Payment processing failed'], 500);
    }
    
  • Testing: Use the sandbox environment for testing. Mock the Square client in unit tests:

    $mock = Mockery::mock(\Nikolag\Square\Square::class);
    $mock->shouldReceive('createCustomer')->once()->andReturn($customer);
    $this->app->instance(\Nikolag\Square\Square::class, $mock);
    

Gotchas and Tips

Pitfalls

  1. Idempotency Keys:

    • Always use unique idempotency_key for payments/orders to avoid duplicate charges.
    • Generate keys using Str::uuid()->toString() or a similar method.
    • Gotcha: Reusing the same key will result in a 409 Conflict error.
  2. Currency and Amount:

    • Square expects amounts in smallest currency unit (e.g., cents for USD).
    • Gotcha: Passing $10.00 as 10 instead of 1000 will fail silently or return incorrect results.
  3. Webhook Verification:

    • Square sends webhook events with a Square-Signature header. Verify it using the verifyWebhookSignature method:
      $isValid = $this->verifyWebhookSignature(
          $request->header('Square-Signature'),
          $request->getContent(),
          config('square.webhook_secret')
      );
      
    • Gotcha: Skipping verification exposes your endpoint to spoofing attacks.
  4. Rate Limits:

    • Square enforces rate limits (e.g., 10 requests/second for sandbox).
    • Tip: Implement exponential backoff in your retry logic for transient failures.
  5. Customer Email Uniqueness:

    • Square enforces unique email addresses per customer. Attempting to create a duplicate will fail.
    • Tip: Use getCustomerByEmail() before creating a new customer to avoid conflicts.

Debugging

  1. Enable Debug Mode: Set debug to true in config/square.php to log raw API responses:

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

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

  2. Common Errors:

    • 401 Unauthorized: Invalid or expired access token. Regenerate the token in the Square Developer Dashboard.
    • 400 Bad Request: Invalid payload. Validate data against Square’s API reference.
    • 429 Too Many Requests: Hit rate limits. Implement retries with delays.
  3. Testing in Sandbox:

    • Use Square’s sandbox tester to simulate card declines or successful payments.
    • Tip: Test with 4111 1111 1111 1111 (success) and 4000 0000 0000 0002 (decline).

Extension Points

  1. Custom Traits: Extend the package by creating custom traits for domain-specific logic:
    namespace App\Traits;
    
    use Nikolag\Square\Square
    
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php