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

nikolag/laravel-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 credentials:

    SQUARE_ENVIRONMENT=sandbox
    SQUARE_ACCESS_TOKEN=your_access_token
    SQUARE_LOCATION_ID=your_location_id
    
  2. First Use Case: Create a customer in Square via a Laravel controller:

    use Nikolag\Square\Traits\Customer;
    
    class CustomerController extends Controller
    {
        use Customer;
    
        public function createCustomer(Request $request)
        {
            $customer = $this->createCustomer([
                'given_name' => $request->given_name,
                'family_name' => $request->family_name,
                'email_address' => $request->email,
            ]);
            return response()->json($customer);
        }
    }
    

Key Entry Points

  • Service Provider: Registers the package and binds the Square client.
  • Traits: Modular methods for customers, orders, payments, etc.
  • Config: config/square.php for environment-specific settings.

Implementation Patterns

Core Workflows

  1. Customer Management:

    • Create/Update: Use createCustomer() or updateCustomer() with an array of attributes.
    • Fetch: Retrieve a customer by ID with getCustomer($id).
    • List: Fetch all customers with listCustomers() (supports pagination via limit and offset).

    Example:

    $customer = $this->getCustomer($customerId);
    $this->updateCustomer($customerId, ['email_address' => 'new@example.com']);
    
  2. Order Processing:

    • Create Orders: Use createOrder() with items, customer ID, and payment details.
    • Retrieve Orders: Fetch an order by ID with getOrder($id).
    • Cancel Orders: Use cancelOrder($id) for order cancellations.

    Example:

    $order = $this->createOrder([
        'idempotency_key' => 'unique_key',
        'customer_id' => $customerId,
        'items' => [
            ['name' => 'Product 1', 'quantity' => 1, 'base_price_money' => ['amount' => 1000, 'currency' => 'USD']],
        ],
    ]);
    
  3. Payment Handling:

    • Charge Payments: Use createPayment() with a source_id (e.g., from a card token).
    • Refunds: Issue refunds with createRefund($paymentId, $amount).
    • Webhooks: Listen to Square events via Laravel's Event facade (see Square Webhooks).

    Example:

    $payment = $this->createPayment([
        'idempotency_key' => 'unique_key',
        'source_id' => $cardToken,
        'amount_money' => ['amount' => 1000, 'currency' => 'USD'],
        'order_id' => $orderId,
    ]);
    

Integration Tips

  • Service Layer: Abstract Square logic into a dedicated service class to decouple controllers from API calls.
    class SquareService {
        use Customer, Order, Payment;
    
        public function processOrder(Request $request) {
            // Business logic here
            $order = $this->createOrder($request->all());
            return $order;
        }
    }
    
  • Error Handling: Wrap Square calls in try-catch blocks to handle API errors gracefully.
    try {
        $customer = $this->createCustomer($data);
    } catch (\Nikolag\Square\Exceptions\SquareException $e) {
        return response()->json(['error' => $e->getMessage()], 400);
    }
    
  • Testing: Use the sandbox environment for testing. Mock the Square client in PHPUnit:
    $this->partialMock(SquareClient::class, ['createCustomer']);
    

Gotchas and Tips

Common Pitfalls

  1. Environment Mismatch:

    • Ensure SQUARE_ENVIRONMENT in .env matches your Square account (e.g., sandbox for testing, production for live).
    • Debug Tip: Check the environment field in the response to confirm the active environment.
  2. Idempotency Keys:

    • Always include a unique idempotency_key for createOrder() and createPayment() to avoid duplicate transactions.
    • Gotcha: Reusing the same key may overwrite previous requests.
  3. Rate Limits:

    • Square enforces rate limits. Handle 429 Too Many Requests errors with retries:
      $retryAfter = $e->getRetryAfter();
      sleep($retryAfter);
      retry();
      
  4. Webhook Verification:

    • Square webhooks require verification. Use Laravel's HasApiTokens or a middleware to validate signatures:
      use Nikolag\Square\Traits\Webhook;
      
      class SquareWebhookController extends Controller {
          use Webhook;
      
          public function handleWebhook(Request $request) {
              if (!$this->verifyWebhook($request)) {
                  abort(403);
              }
              // Process webhook
          }
      }
      

Debugging Tips

  • Log Responses: Enable debug mode in config/square.php to log API responses:
    'debug' => env('SQUARE_DEBUG', false),
    
  • Square Dashboard: Use the Square Developer Dashboard to inspect API calls and test webhooks.
  • Error Codes: Refer to Square's API error codes for troubleshooting.

Extension Points

  1. Custom Traits:
    • Extend the package by creating custom traits for niche use cases (e.g., loyalty programs):
      trait CustomSquareTrait {
          public function applyLoyaltyDiscount($customerId, $discount) {
              // Custom logic
          }
      }
      
  2. Event Listeners:
    • Subscribe to Square events (e.g., payment.created) via Laravel's event system:
      Event::listen('Nikolag\Square\Events\PaymentCreated', function ($event) {
          // Send notification
      });
      
  3. Middleware:
    • Add middleware to validate Square tokens or enforce rate limits:
      Route::middleware(['square.auth'])->group(function () {
          // Protected routes
      });
      

Configuration Quirks

  • Location ID: Ensure SQUARE_LOCATION_ID is set to the correct Square location (required for most endpoints).
  • Currency: Always specify currency (e.g., USD) in monetary fields. Square defaults may vary by region.
  • Timeouts: Adjust the HTTP client timeout in config/square.php if Square's API is slow:
    'timeout' => 30, // seconds
    

Pro Tips

  • Batch Operations: Use Square's batch API for bulk order updates (not directly supported by the package; implement via raw API calls).
  • Customer Groups: Leverage Square's customer groups for segmentation (extend the Customer trait).
  • Localization: Use Square's localization features for multi-currency support by passing locale in requests.
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity