PHP Examples
Complete PHP examples for integrating with the Pixlpay API.
API Client Class
A reusable client for all API operations:
php
<?php
class PixlpayClient
{
private string $baseUrl;
private string $token;
public function __construct(string $storeUrl, string $token)
{
$this->baseUrl = rtrim($storeUrl, '/') . '/api/external/v1';
$this->token = $token;
}
private function request(string $method, string $endpoint, array $data = null): array
{
$ch = curl_init();
$url = $this->baseUrl . $endpoint;
$headers = [
'Authorization: Bearer ' . $this->token,
'Accept: application/json',
'Content-Type: application/json',
];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
} elseif ($method === 'PUT') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
if ($data) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
} elseif ($method === 'DELETE') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
throw new Exception('cURL Error: ' . $error);
}
$result = json_decode($response, true);
if ($httpCode >= 400) {
throw new PixlpayException(
$result['message'] ?? 'Unknown error',
$result['error'] ?? 'UNKNOWN',
$httpCode,
$result['errors'] ?? null
);
}
return $result;
}
// Products
public function getProducts(array $params = []): array
{
$query = http_build_query($params);
return $this->request('GET', '/products' . ($query ? '?' . $query : ''));
}
public function getProduct(int $id): array
{
return $this->request('GET', '/products/' . $id);
}
// Orders
public function getOrders(array $params = []): array
{
$query = http_build_query($params);
return $this->request('GET', '/orders' . ($query ? '?' . $query : ''));
}
public function getOrder(int $id): array
{
return $this->request('GET', '/orders/' . $id);
}
public function fulfillOrder(int $id): array
{
return $this->request('POST', '/orders/' . $id . '/fulfill');
}
// Customers
public function getCustomers(array $params = []): array
{
$query = http_build_query($params);
return $this->request('GET', '/customers' . ($query ? '?' . $query : ''));
}
public function getCustomer(int $id): array
{
return $this->request('GET', '/customers/' . $id);
}
// Analytics
public function getRevenueAnalytics(array $params = []): array
{
$query = http_build_query($params);
return $this->request('GET', '/analytics/revenue' . ($query ? '?' . $query : ''));
}
public function getSalesAnalytics(array $params = []): array
{
$query = http_build_query($params);
return $this->request('GET', '/analytics/sales' . ($query ? '?' . $query : ''));
}
// Webhooks
public function getWebhooks(): array
{
return $this->request('GET', '/webhooks');
}
public function createWebhook(string $url, array $events): array
{
return $this->request('POST', '/webhooks', [
'url' => $url,
'events' => $events,
]);
}
public function deleteWebhook(int $id): array
{
return $this->request('DELETE', '/webhooks/' . $id);
}
}
class PixlpayException extends Exception
{
public string $errorCode;
public ?array $errors;
public function __construct(string $message, string $errorCode, int $httpCode, ?array $errors = null)
{
parent::__construct($message, $httpCode);
$this->errorCode = $errorCode;
$this->errors = $errors;
}
}Usage Examples
List Products
php
<?php
$client = new PixlpayClient(
getenv('PIXLPAY_STORE_URL'),
getenv('PIXLPAY_API_TOKEN')
);
try {
$response = $client->getProducts([
'is_active' => true,
'per_page' => 50,
]);
foreach ($response['data'] as $product) {
echo "{$product['name']} - \${$product['price']}\n";
}
} catch (PixlpayException $e) {
echo "Error: {$e->getMessage()}\n";
}Fulfill an Order
php
<?php
try {
$result = $client->fulfillOrder(123);
echo "Order {$result['data']['order_number']} fulfilled!\n";
} catch (PixlpayException $e) {
if ($e->errorCode === 'ORDER_ALREADY_COMPLETED') {
echo "Order was already completed\n";
} else {
echo "Error: {$e->getMessage()}\n";
}
}Get Revenue Analytics
php
<?php
$analytics = $client->getRevenueAnalytics([
'start_date' => date('Y-m-01'),
'end_date' => date('Y-m-t'),
'group_by' => 'day',
]);
echo "Total Revenue: \${$analytics['data']['summary']['total_revenue']}\n";
echo "Total Orders: {$analytics['data']['summary']['total_orders']}\n";Webhook Handler
Complete webhook handler with signature verification:
php
<?php
class PixlpayWebhookHandler
{
private string $secret;
public function __construct(string $secret)
{
$this->secret = $secret;
}
public function handle(): void
{
// Get raw body before parsing
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '';
// Verify signature
if (!$this->verifySignature($payload, $signature)) {
http_response_code(401);
echo json_encode(['error' => 'Invalid signature']);
return;
}
// Parse event
$event = json_decode($payload, true);
// Log the event
$this->log("Received: {$event['event_type']} ({$event['id']})");
// Process based on event type
try {
switch ($event['event_type']) {
case 'order.paid':
$this->handleOrderPaid($event['data']);
break;
case 'order.refunded':
$this->handleOrderRefunded($event['data']);
break;
case 'subscription.created':
$this->handleSubscriptionCreated($event['data']);
break;
case 'subscription.cancelled':
$this->handleSubscriptionCancelled($event['data']);
break;
default:
$this->log("Unhandled event type: {$event['event_type']}");
}
http_response_code(200);
echo json_encode(['status' => 'success']);
} catch (Exception $e) {
$this->log("Error: {$e->getMessage()}");
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
}
private function verifySignature(string $payload, string $signature): bool
{
$expected = hash_hmac('sha256', $payload, $this->secret);
return hash_equals($expected, $signature);
}
private function handleOrderPaid(array $data): void
{
$orderId = $data['order_id'];
$customerEmail = $data['customer_email'];
$items = $data['items'];
foreach ($items as $item) {
// Deliver item to customer
$this->deliverItem($customerEmail, $item);
}
$this->log("Delivered order {$orderId} to {$customerEmail}");
}
private function handleOrderRefunded(array $data): void
{
$orderId = $data['order_id'];
// Revoke access, update inventory, etc.
$this->log("Refund processed for order {$orderId}");
}
private function handleSubscriptionCreated(array $data): void
{
$customerId = $data['customer_id'];
$planName = $data['plan_name'];
// Grant subscription access
$this->log("Subscription {$planName} created for customer {$customerId}");
}
private function handleSubscriptionCancelled(array $data): void
{
$subscriptionId = $data['subscription_id'];
// Revoke subscription access
$this->log("Subscription {$subscriptionId} cancelled");
}
private function deliverItem(string $email, array $item): void
{
// Implement your delivery logic
}
private function log(string $message): void
{
error_log('[Pixlpay Webhook] ' . $message);
}
}
// Usage
$handler = new PixlpayWebhookHandler(getenv('PIXLPAY_WEBHOOK_SECRET'));
$handler->handle();Laravel Integration
Service Provider
php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Services\PixlpayClient;
class PixlpayServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(PixlpayClient::class, function () {
return new PixlpayClient(
config('services.pixlpay.store_url'),
config('services.pixlpay.api_token')
);
});
}
}Config
php
// config/services.php
return [
'pixlpay' => [
'store_url' => env('PIXLPAY_STORE_URL'),
'api_token' => env('PIXLPAY_API_TOKEN'),
'webhook_secret' => env('PIXLPAY_WEBHOOK_SECRET'),
],
];Webhook Controller
php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Jobs\ProcessPixlpayWebhook;
class PixlpayWebhookController extends Controller
{
public function handle(Request $request)
{
$payload = $request->getContent();
$signature = $request->header('X-Webhook-Signature');
$secret = config('services.pixlpay.webhook_secret');
$expected = hash_hmac('sha256', $payload, $secret);
if (!hash_equals($expected, $signature)) {
return response()->json(['error' => 'Invalid signature'], 401);
}
// Process asynchronously
ProcessPixlpayWebhook::dispatch($request->all());
return response()->json(['status' => 'received']);
}
}