PHP code example of einenlum / creem-php-sdk

1. Go to this page and download the library: Download einenlum/creem-php-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

einenlum / creem-php-sdk example snippets


use Einenlum\CreemPhpSdk\Creem;

// Create a client (auto-discovers PSR-18/17 implementations)
$creem = Creem::create(
    apiKey: 'creem_xxxxx',
    testMode: true // Use test API environment
);

// Get a product
$product = $creem->products->get('prod_xxxxx');
echo $product->name;

// Create a checkout session
$checkout = $creem->checkouts->create(
    productId: 'prod_xxxxx',
    successUrl: 'https://example.com/success'
);
echo $checkout->checkoutUrl;

use Einenlum\CreemPhpSdk\Creem;

$creem = Creem::create(
    apiKey: 'creem_xxxxx',
    webhookSecret: 'whsec_xxxxx', // Optional, for webhook handling
    testMode: false               // false = production, true = test environment
);

use Einenlum\CreemPhpSdk\Creem;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;

$httpClient = new Client([
    'timeout' => 30,
    'proxy' => 'http://proxy.example.com:8080'
]);
$factory = new HttpFactory();

$creem = Creem::create(
    apiKey: 'creem_xxxxx',
    httpClient: $httpClient,
    requestFactory: $factory,
    streamFactory: $factory
);

// Get a product by ID
$product = $creem->products->get('prod_xxxxx');

// Create a product
$product = $creem->products->create([
    'name' => 'My Product',
    'price' => 1999, // Price in cents
    'currency' => 'USD'
]);

// Search products with pagination
$result = $creem->products->search(limit: 10, page: 1);
foreach ($result->items as $product) {
    echo $product->name;
}

// Create a checkout session
$checkout = $creem->checkouts->create(
    productId: 'prod_xxxxx',
    successUrl: 'https://example.com/success',
    customer: [
        'email' => '[email protected]',
        'name' => 'John Doe'
    ],
    metadata: [
        'order_id' => '12345'
    ]
);

// Redirect user to checkout
header('Location: ' . $checkout->checkoutUrl);

// Get checkout details
$checkout = $creem->checkouts->get('ch_xxxxx');

// Get a customer by ID or email
$customer = $creem->customers->get(customerId: 'cus_xxxxx');
$customer = $creem->customers->get(email: '[email protected]');

// List customers
$result = $creem->customers->list(limit: 20, page: 1);

// Create a billing portal session
$portal = $creem->customers->createBillingPortal('cus_xxxxx');
echo $portal->url;

// Get subscription details
$subscription = $creem->subscriptions->get('sub_xxxxx');
echo $subscription->status->value; // 'active', 'canceled', etc.

// Update subscription units
$subscription = $creem->subscriptions->updateUnits('sub_xxxxx', units: 5);

// Upgrade to a different product
$subscription = $creem->subscriptions->upgrade('sub_xxxxx', newProductId: 'prod_yyyyy');

// Cancel subscription
$subscription = $creem->subscriptions->cancel('sub_xxxxx');

// Create a discount
$discount = $creem->discounts->create([
    'code' => 'SUMMER20',
    'type' => 'percentage',
    'amount' => 20,
    'duration' => 'forever'
]);

// Get discount by ID or code
$discount = $creem->discounts->get(discountId: 'disc_xxxxx');
$discount = $creem->discounts->get(code: 'SUMMER20');

// Delete a discount
$creem->discounts->delete('disc_xxxxx');

// Activate a license
$license = $creem->licenses->activate(
    key: 'XXXX-XXXX-XXXX-XXXX',
    instanceName: 'My Computer'
);
echo $license->instanceId;

// Validate a license
$license = $creem->licenses->validate(
    key: 'XXXX-XXXX-XXXX-XXXX',
    instanceId: 'inst_xxxxx'
);

// Deactivate a license
$license = $creem->licenses->deactivate(
    key: 'XXXX-XXXX-XXXX-XXXX',
    instanceId: 'inst_xxxxx'
);

// Search transactions
$result = $creem->transactions->search(
    customerId: 'cus_xxxxx',
    limit: 50,
    page: 1
);

// Search by subscription
$result = $creem->transactions->search(
    subscriptionId: 'sub_xxxxx'
);

use Einenlum\CreemPhpSdk\Webhook\WebhookHandler;
use Einenlum\CreemPhpSdk\Exception\WebhookException;

$handler = new WebhookHandler('whsec_xxxxx');

// Register event handlers
$handler
    ->onCheckoutCompleted(function ($event) {
        $checkout = $event->object;
        // Grant access to the customer
    })
    ->onSubscriptionActive(function ($event) {
        $subscription = $event->object;
        // Activate subscription
    })
    ->onSubscriptionCanceled(function ($event) {
        $subscription = $event->object;
        // Handle cancellation
    });

// Process webhook in your endpoint
try {
    $payload = file_get_contents('php://input');
    $signature = $_SERVER['HTTP_CREEM_SIGNATURE'] ?? '';

    $event = $handler->handle($payload, $signature);

    http_response_code(200);
    echo json_encode(['received' => true]);
} catch (WebhookException $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}

use Einenlum\CreemPhpSdk\Enum\WebhookEvent;

$handler->on(WebhookEvent::CheckoutCompleted, function ($event) {
    // Handle event
});

use Einenlum\CreemPhpSdk\Exception\AuthenticationException;
use Einenlum\CreemPhpSdk\Exception\ValidationException;
use Einenlum\CreemPhpSdk\Exception\NotFoundException;
use Einenlum\CreemPhpSdk\Exception\RateLimitException;
use Einenlum\CreemPhpSdk\Exception\ApiException;
use Einenlum\CreemPhpSdk\Exception\CreemException;

try {
    $product = $creem->products->get('prod_xxxxx');
} catch (AuthenticationException $e) {
    // Invalid API key (401/403)
} catch (ValidationException $e) {
    // Invalid request data (400)
} catch (NotFoundException $e) {
    // Resource not found (404)
} catch (RateLimitException $e) {
    // Too many requests (429)
} catch (ApiException $e) {
    // Server error (500+)
} catch (CreemException $e) {
    // Other errors
}

try {
    $product = $creem->products->get('invalid_id');
} catch (CreemException $e) {
    echo $e->getMessage();
    print_r($e->getResponseBody());
    print_r($e->getResponseHeaders());
}

use Einenlum\CreemPhpSdk\Enum\SubscriptionStatus;
use Einenlum\CreemPhpSdk\Enum\LicenseStatus;
use Einenlum\CreemPhpSdk\Enum\DiscountType;
use Einenlum\CreemPhpSdk\Enum\DiscountDuration;

// Check subscription status
if ($subscription->status === SubscriptionStatus::Active) {
    // Subscription is active
}

// All enum values
SubscriptionStatus::Active;
SubscriptionStatus::Canceled;
SubscriptionStatus::Expired;
SubscriptionStatus::Trialing;
SubscriptionStatus::Paused;

$creem = Creem::create(
    apiKey: 'creem_test_xxxxx',
    testMode: true
);
bash
composer