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

Connect Laravel Package

square/connect

Retired Square Connect PHP SDK (EOL 2020-06-10). No longer receives updates or fixes. Migrate to the new Square PHP SDK: require square/square, update namespaces from SquareConnect\ to Square, and adjust client/response handling per docs.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Migrate to square/square (required):

    composer require square/square
    

    Replace all use SquareConnect\* imports with use Square\*.

  2. Initialize the client (replace deprecated ApiClient):

    use Square\SquareClient;
    use Square\Environment;
    
    $client = new SquareClient([
        'accessToken' => config('services.square.access_token'),
        'environment' => Environment::SANDBOX, // or Environment::PRODUCTION
    ]);
    
  3. First API call (e.g., create a payment):

    $paymentsApi = $client->getPaymentsApi();
    $money = new \Square\Models\Money(['amount' => 100, 'currency' => 'USD']);
    $request = new \Square\Models\CreatePaymentRequest(
        'nonce_from_client',
        uniqid(),
        $money
    );
    $response = $paymentsApi->createPayment($request);
    

Where to Look First


Implementation Patterns

1. Client Initialization

  • Centralize configuration (e.g., in config/services.php):
    'square' => [
        'access_token' => env('SQUARE_ACCESS_TOKEN'),
        'environment' => env('SQUARE_ENVIRONMENT', 'sandbox'),
    ],
    
  • Reuse the client across requests (singleton pattern):
    $client = app(SquareClient::class);
    

2. Method Chaining

  • Avoid instantiating multiple API clients (use the single $client instance):
    $paymentsApi = $client->getPaymentsApi();
    $locationsApi = $client->getLocationsApi();
    

3. Request/Response Handling

  • Use model classes for requests/responses (e.g., CreatePaymentRequest, Payment):
    $request = new CreatePaymentRequest(
        $nonce,
        $idempotencyKey,
        new Money(['amount' => 100, 'currency' => 'USD'])
    );
    $response = $paymentsApi->createPayment($request);
    
  • Check for errors:
    if ($response->isError()) {
        throw new \RuntimeException('Square API Error: ' . $response->getErrors()[0]->getMessage());
    }
    

4. Common Workflows

Payments

$payment = $paymentsApi->createPayment($request);
$paymentId = $payment->getPayment()->getId();

Refunds

$refund = $refundsApi->refundPayment($paymentId, 50);

Customers

$customer = $customersApi->createCustomer($customerRequest);

Locations

$locations = $locationsApi->listLocations();

5. Error Handling

  • Catch ApiException for network/API errors:
    try {
        $response = $paymentsApi->createPayment($request);
    } catch (ApiException $e) {
        \Log::error('Square API Error: ' . $e->getMessage());
        abort(500, 'Payment failed');
    }
    
  • Validate responses:
    if ($response->isError()) {
        $errors = $response->getErrors();
        foreach ($errors as $error) {
            \Log::error($error->getCategory() . ': ' . $error->getCode());
        }
    }
    

6. Webhooks (if applicable)

  • Subscribe to events (e.g., payments):
    $webhooksApi = $client->getWebhooksApi();
    $webhook = $webhooksApi->createWebhook($webhookRequest);
    

Gotchas and Tips

Pitfalls

  1. Deprecated Endpoints:

    • Avoid using square/connect (EOL). Migrate to square/square immediately.
    • Example: renewToken is deprecated; use OAuth token refresh.
  2. Idempotency Keys:

    • Always use unique idempotency_key for payments/refunds to avoid duplicate charges.
    • Example: uniqid() or a UUID.
  3. Currency Formatting:

    • Amounts must be integers (e.g., $100 = 100, not 100.00).
    • Use Money model for consistency:
      $money = new Money(['amount' => 100, 'currency' => 'USD']);
      
  4. Rate Limits:

    • Square enforces rate limits. Cache responses where possible.
  5. Webhook Verification:

    • Always verify Square webhook signatures to prevent spoofing:
      use Square\Webhook\SignatureVerifier;
      $verifier = new SignatureVerifier(config('services.square.webhook_secret'));
      if (!$verifier->verify($rawBody, $signatureHeader)) {
          abort(403, 'Invalid webhook signature');
      }
      

Debugging Tips

  1. Enable Debug Logging:

    use Square\SquareClient;
    $client = new SquareClient([
        'accessToken' => $token,
        'environment' => Environment::SANDBOX,
        'debug' => true, // Enable debug logs
    ]);
    
  2. Inspect Raw Responses:

    • Use getRawResponse() to debug API calls:
      $response = $paymentsApi->createPayment($request);
      \Log::debug($response->getRawResponse());
      
  3. Test in Sandbox First:

    • Use Square’s sandbox for testing:
      $client = new SquareClient([
          'accessToken' => 'sandbox-access-token',
          'environment' => Environment::SANDBOX,
      ]);
      

Extension Points

  1. Custom Request/Response Transformers:

    • Extend SquareClient to add middleware for request/response modification:
      $client = new SquareClient([
          'accessToken' => $token,
          'middleware' => [
              function ($request) {
                  $request->setHeader('X-Custom-Header', 'value');
              },
          ],
      ]);
      
  2. Repository Pattern:

    • Abstract Square API calls into a repository for cleaner code:
      class SquarePaymentRepository {
          public function __construct(private SquareClient $client) {}
      
          public function charge(string $nonce, int $amount): Payment {
              $request = new CreatePaymentRequest($nonce, uniqid(), new Money(['amount' => $amount, 'currency' => 'USD']));
              return $this->client->getPaymentsApi()->createPayment($request)->getPayment();
          }
      }
      
  3. Event Dispatching:

    • Trigger Laravel events after Square API calls:
      $payment = $paymentsApi->createPayment($request);
      event(new PaymentCreated($payment));
      

Configuration Quirks

  1. Environment Variables:

    • Store SQUARE_ACCESS_TOKEN and SQUARE_ENVIRONMENT in .env:
      SQUARE_ACCESS_TOKEN=sandbox-access-token
      SQUARE_ENVIRONMENT=sandbox
      
  2. Webhook Secrets:

    • Generate a secret in your Square app dashboard and store it in config/services.php:
      'square' => [
          'webhook_secret' => env('SQUARE_WEBHOOK_SECRET'),
      ],
      
  3. Timeouts:

    • Adjust Guzzle client timeout if needed (default: 30s):
      $client = new SquareClient([
          'accessToken' => $token,
          'httpClient' => new \GuzzleHttp\Client(['timeout' => 60]),
      ]);
      
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime