SubLoop PHP SDK

Official PHP SDK for SubLoop's payment analytics API. Easily integrate payment data tracking and analytics into your PHP applications.

Installation

Install via Composer:

composer require subloop/php-sdk

Quick Start

<?php
require_once 'vendor/autoload.php';

use SubLoop\SubLoop;

// Initialize the client
$subloop = new SubLoop('sk_your_api_key_here');

// Send payment data
$payment = $subloop->payments->createSuccessful(
    customerId: 'cust_001',
    amount: 29.99,
    currency: 'USD',
    subscriptionId: 'sub_001'
);

// Get analytics
$overview = $subloop->analytics->getOverview();
$mrr = $subloop->analytics->getMRR();

Authentication

Get your API key from your SubLoop dashboard and initialize the client:

$subloop = new SubLoop('sk_your_api_key_here');

// For development/testing
$subloop = new SubLoop('sk_your_api_key_here', 'http://localhost:8000');

Payment Events

Create Payment Event

// Manual payment creation
$payment = $subloop->payments->create([
    'customer_id' => 'cust_001',
    'subscription_id' => 'sub_001', // Optional for recurring payments
    'amount' => 29.99,
    'currency' => 'USD',
    'status' => 'succeeded', // succeeded, failed, pending, refunded
    'payment_date' => '2025-07-31T00:00:00Z',
    'payment_method' => 'card',
    'metadata' => [
        'gateway_transaction_id' => 'txn_123',
        'customer_email' => '[email protected]'
    ]
]);

// Helper methods for common scenarios
$successfulPayment = $subloop->payments->createSuccessful(
    customerId: 'cust_001',
    amount: 29.99,
    currency: 'USD',
    subscriptionId: 'sub_001'
);

$failedPayment = $subloop->payments->createFailed(
    customerId: 'cust_002',
    amount: 19.99,
    currency: 'USD'
);

List Payment Events

// Get all payments
$payments = $subloop->payments->list();

// With pagination
$payments = $subloop->payments->list(['page' => 2]);

// Get specific payment
$payment = $subloop->payments->get(123);

Analytics

Dashboard Overview

$overview = $subloop->analytics->getOverview();

echo "MRR: $" . $overview['mrr'];
echo "Total Revenue (30d): $" . $overview['total_revenue_30d'];
echo "Active Subscriptions: " . $overview['active_subscriptions'];
echo "Success Rate: " . $overview['payment_success_rate'] . "%";

Monthly Recurring Revenue

$mrr = $subloop->analytics->getMRR();

echo "Current MRR: $" . $mrr['mrr'];
echo "Previous MRR: $" . $mrr['previous_mrr'];
echo "Growth: " . $mrr['growth_percentage'] . "%";

Revenue Analytics

// Get revenue for different periods
$revenue30d = $subloop->analytics->getRevenue('30days');
$revenue7d = $subloop->analytics->getRevenueLast7Days();
$revenue90d = $subloop->analytics->getRevenue('90days');

// Custom date range
$customRevenue = $subloop->analytics->getRevenue(
    period: null,
    startDate: '2025-06-01',
    endDate: '2025-07-31'
);

Payment Activity

// Get recent payments
$recentPayments = $subloop->analytics->getPayments(limit: 10);

// Get only successful payments
$successfulPayments = $subloop->analytics->getSuccessfulPayments(20);

// Get only recurring payments
$recurringPayments = $subloop->analytics->getRecurringPayments(15);

// Filter by status
$failedPayments = $subloop->analytics->getPayments(
    limit: 10,
    status: 'failed'
);

Integration Examples

Stripe Webhook Integration

<?php
// webhook.php - Handle Stripe webhooks

require_once 'vendor/autoload.php';
use SubLoop\SubLoop;

$subloop = new SubLoop($_ENV['SUBLOOP_API_KEY']);

// Get Stripe webhook data
$input = file_get_contents('php://input');
$event = json_decode($input, true);

if ($event['type'] === 'payment_intent.succeeded') {
    $paymentIntent = $event['data']['object'];

    // Send to SubLoop
    $subloop->payments->createSuccessful(
        customerId: $paymentIntent['customer'],
        amount: $paymentIntent['amount_received'] / 100, // Convert from cents
        currency: strtoupper($paymentIntent['currency']),
        subscriptionId: $paymentIntent['metadata']['subscription_id'] ?? null,
        metadata: [
            'stripe_payment_intent_id' => $paymentIntent['id'],
            'stripe_charge_id' => $paymentIntent['charges']['data'][0]['id'] ?? null
        ]
    );
}

http_response_code(200);
echo json_encode(['status' => 'success']);

Laravel Integration

<?php
// app/Services/SubLoopService.php

namespace App\Services;

use SubLoop\SubLoop;

class SubLoopService
{
    private SubLoop $client;

    public function __construct()
    {
        $this->client = new SubLoop(config('services.subloop.api_key'));
    }

    public function trackPayment($order)
    {
        return $this->client->payments->createSuccessful(
            customerId: $order->customer_id,
            amount: $order->total,
            currency: $order->currency,
            subscriptionId: $order->subscription_id,
            metadata: [
                'order_id' => $order->id,
                'product_ids' => $order->items->pluck('product_id')->toArray()
            ]
        );
    }

    public function getDashboardData()
    {
        return [
            'overview' => $this->client->analytics->getOverview(),
            'mrr' => $this->client->analytics->getMRR(),
            'recent_payments' => $this->client->analytics->getPayments(10)
        ];
    }
}

WordPress Plugin Integration

<?php
// wp-content/plugins/subloop-analytics/subloop-analytics.php

require_once plugin_dir_path(__FILE__) . 'vendor/autoload.php';
use SubLoop\SubLoop;

class SubLoopAnalytics
{
    private $subloop;

    public function __construct()
    {
        $apiKey = get_option('subloop_api_key');
        $this->subloop = new SubLoop($apiKey);

        // Hook into WooCommerce payment completion
        add_action('woocommerce_payment_complete', [$this, 'track_payment']);
    }

    public function track_payment($order_id)
    {
        $order = wc_get_order($order_id);

        $this->subloop->payments->createSuccessful(
            customerId: $order->get_customer_id(),
            amount: floatval($order->get_total()),
            currency: $order->get_currency(),
            subscriptionId: $this->get_subscription_id($order),
            metadata: [
                'woocommerce_order_id' => $order_id,
                'customer_email' => $order->get_billing_email()
            ]
        );
    }
}

new SubLoopAnalytics();

Error Handling

use SubLoop\Exceptions\SubLoopException;

try {
    $payment = $subloop->payments->create([
        'customer_id' => 'cust_001',
        'amount' => 29.99,
        'currency' => 'USD',
        'status' => 'succeeded',
        'payment_date' => '2025-07-31T00:00:00Z'
    ]);
} catch (SubLoopException $e) {
    echo "SubLoop Error: " . $e->getMessage();
    echo "HTTP Code: " . $e->getCode();

    if ($e->getDetails()) {
        print_r($e->getDetails());
    }
} catch (Exception $e) {
    echo "General Error: " . $e->getMessage();
}

Requirements

  • PHP 7.4 or higher
  • cURL extension
  • JSON extension

Support

License

MIT License. See LICENSE for more information.