Weave 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

Sumup Ecom Php Sdk Laravel Package

sumup/sumup-ecom-php-sdk

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sumup/sumup-ecom-php-sdk
    

    (Note: This SDK is deprecated; consider migrating to sumup-php for new projects.)

  2. First Use Case: Initialize the SDK with credentials and create a checkout:

    $sumup = new \SumUp\SumUp([
        'app_id'     => env('SUMUP_APP_ID'),
        'app_secret' => env('SUMUP_APP_SECRET'),
        'code'       => env('SUMUP_AUTH_CODE'), // From OAuth flow
    ]);
    $checkout = $sumup->getCheckoutService()->create(1000, 'EUR', 'order_123', 'merchant_456');
    return $checkout->getBody()->id; // Return to frontend for processing
    
  3. Where to Look First:

    • Docs: API Reference (e.g., Checkouts.md, Customers.md).
    • Exceptions: Handle SumUpAuthenticationException, SumUpResponseException, and SumUpServerException in controllers.
    • Config: Use .env for credentials (e.g., SUMUP_APP_ID, SUMUP_APP_SECRET).

Implementation Patterns

Core Workflows

  1. OAuth Flow Integration:

    • Use getAuthorizationService() to handle token refresh:
      $auth = $sumup->getAuthorizationService();
      $token = $auth->refreshToken($refreshToken);
      
    • Store tokens in Laravel’s cache/database for persistence.
  2. Checkout Processing:

    • Create Checkout:
      $checkout = $sumup->getCheckoutService()->create(
          $amount, $currency, $reference, $merchantCode
      );
      
    • Capture Payment:
      $transaction = $sumup->getTransactionService()->capture($checkoutId);
      
  3. Customer Management:

    • Create/Update Customers:
      $customer = $sumup->getCustomerService()->create(
          'customer_123',
          ['email' => '[email protected]'],
          ['street' => '123 Main St']
      );
      
    • Link Payment Instruments:
      $instruments = $sumup->getCustomerService()->getPaymentInstruments('customer_123');
      
  4. Custom API Calls:

    • Use Custom service for unsupported endpoints:
      $custom = new \SumUp\Services\Custom($sumup->getHttpClient(), $sumup->getAccessToken());
      $response = $custom->request('GET', '/v0.1/me');
      

Laravel-Specific Patterns

  1. Service Container Binding: Bind the SDK to Laravel’s container for dependency injection:

    $app->singleton(\SumUp\SumUp::class, function ($app) {
        return new \SumUp\SumUp([
            'app_id'     => $app['config']['services.sumup.app_id'],
            'app_secret' => $app['config']['services.sumup.app_secret'],
            'access_token' => $app['cache']->get('sumup_access_token'),
        ]);
    });
    
  2. Middleware for Auth: Create middleware to validate SumUp tokens:

    public function handle($request, Closure $next) {
        try {
            $sumup = app(\SumUp\SumUp::class);
            $sumup->getAccessToken(); // Throws if invalid
            return $next($request);
        } catch (\SumUp\Exceptions\SumUpAuthenticationException $e) {
            return redirect()->route('sumup.auth');
        }
    }
    
  3. Event Listeners: Listen for payment events (e.g., checkout.created) and trigger Laravel events:

    public function handle($event) {
        event(new SumUpCheckoutCreated($event->checkout));
    }
    
  4. Queue Jobs: Offload SumUp API calls to queues (e.g., SumUpCaptureJob):

    class SumUpCaptureJob implements ShouldQueue {
        public function handle() {
            $sumup->getTransactionService()->capture($this->checkoutId);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecation Warning:

    • This SDK is deprecated. Migrate to sumup-php for long-term support.
    • Workaround: Fork the repo and extend it for critical projects, but plan a migration.
  2. Token Management:

    • Short-Lived Tokens: Access tokens expire (~1 hour). Always handle SumUpAuthenticationException and refresh tokens.
    • Refresh Tokens: Store refresh tokens securely (e.g., encrypted in Laravel’s database).
    • Cache Tokens:
      $token = $sumup->getAccessToken();
      Cache::put('sumup_access_token', $token->getToken(), $token->getExpiresIn());
      
  3. HTTP Client Issues:

    • SSL Errors: Use the bundled CA bundle or override with ca_bundle_path:
      $sumup = new \SumUp\SumUp([
          'ca_bundle_path' => storage_path('certs/ca.pem'),
      ]);
      
    • Guzzle vs. cURL: Prefer Guzzle for better debugging. Enable it with:
      $sumup = new \SumUp\SumUp(['use_guzzlehttp_over_curl' => true]);
      
  4. Idempotency:

    • SumUp APIs support idempotency keys for POST requests (e.g., Idempotency-Key: abc123). Use Laravel’s Str::uuid() for unique keys:
      $headers = ['Idempotency-Key' => Str::uuid()];
      $response = $custom->request('POST', '/v0.1/checkouts', $payload, $headers);
      
  5. Rate Limiting:

    • SumUp enforces rate limits (~100 requests/minute). Implement exponential backoff in custom services:
      use Symfony\Component\RateLimiter\RateLimiter;
      $limiter = new RateLimiter(100, 60);
      if (!$limiter->consume()) {
          sleep($limiter->waitTime());
      }
      

Debugging Tips

  1. Enable SDK Logging:

    • Configure Monolog to log SumUp requests:
      $sumup = new \SumUp\SumUp([
          'logger' => new \Monolog\Logger('sumup', [
              new \Monolog\Handler\StreamHandler(storage_path('logs/sumup.log'))
          ]),
      ]);
      
  2. Inspect Raw Responses:

    • Override the HTTP client to log responses:
      $client = new \SumUp\HttpClients\GuzzleHttpClient([
          'debug' => fopen(storage_path('logs/sumup_debug.log'), 'w'),
      ]);
      $sumup = new \SumUp\SumUp(['http_client' => $client]);
      
  3. Common Errors:

    • 401 Unauthorized: Invalid/expired token. Refresh or re-authenticate.
    • 403 Forbidden: Missing scopes. Update scopes in config.
    • 429 Too Many Requests: Implement retries with backoff.
    • 500 Server Error: Check SumUp’s status page.

Extension Points

  1. Custom HTTP Client:

    • Implement SumUpHttpClientInterface for custom logic (e.g., retries, proxies):
      class CustomHttpClient implements SumUpHttpClientInterface {
          public function request($method, $url, $options) {
              // Add custom logic (e.g., proxy, signing)
              return GuzzleHttp::request($method, $url, $options);
          }
      }
      
  2. Response Decorators:

    • Extend \SumUp\HttpClients\Response to add Laravel-specific data:
      class LaravelResponse extends \SumUp\HttpClients\Response {
          public function toLaravelCollection() {
              return collect($this->getBody())->map(fn($item) => new PaymentModel($item));
          }
      }
      
  3. Service Decorators:

    • Decorate services to add middleware (e.g., logging, validation):
      class LoggingCheckoutService implements \SumUp\Services\CheckoutsInterface {
          protected $decorated;
      
          public function __construct(\SumUp\Services\Checkouts $checkout) {
              $this->decorated = $checkout;
          }
      
          public function create($amount, $currency, $reference, $merchantCode) {
              Log::info("Creating checkout for {$reference}");
              return $this->decorated->create($amount, $currency, $reference, $merchantCode);
          }
      }
      
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.
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings