PHP code example of caspahouzer / lemonsqueezy-api-client
1. Go to this page and download the library: Download caspahouzer/lemonsqueezy-api-client 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/ */
caspahouzer / lemonsqueezy-api-client example snippets
use LemonSqueezy\ClientFactory;
// Create a client with your API key
$client = ClientFactory::create('YOUR_API_KEY');
// Get all customers
$customers = $client->customers()->list();
foreach ($customers as $customer) {
echo $customer->getEmail() . "\n";
}
// Get a specific customer
$customer = $client->customers()->get('cust-123');
// Create a new discount
$discount = $client->discounts()->create([
'name' => 'Summer Sale',
'code' => 'SUMMER2024',
'percent' => 20,
]);
use LemonSqueezy\Configuration\ConfigBuilder;
use LemonSqueezy\Client;
// Create client without API key (public API)
$config = (new ConfigBuilder())->build();
$client = new Client($config);
// Activate a license
$result = $client->licenseKeys()->activate(
'license-key-here',
'instance-name'
);
// Validate a license
$validation = $client->licenseKeys()->validate(
'license-key-here',
'instance-id-hash',
'instance-name'
);
// Deactivate a license
$result = $client->licenseKeys()->deactivate(
'license-key-here',
'instance-id-hash',
'instance-name'
);
use GuzzleHttp\Client as GuzzleClient;
$guzzleClient = new GuzzleClient(['timeout' => 60]);
$client = ClientFactory::create('YOUR_API_KEY')
->withHttpClient($guzzleClient)
->withTimeout(60)
->withMaxRetries(3)
->build();
use Monolog\Logger;
use Monolog\Handlers\StreamHandler;
$logger = new Logger('lemonsqueezy');
$logger->pushHandler(new StreamHandler('app.log'));
$client = ClientFactory::create('YOUR_API_KEY', $logger);
use LemonSqueezy\Configuration\ConfigBuilder;
use LemonSqueezy\Client;
$config = (new ConfigBuilder())
->withApiKey('YOUR_API_KEY')
->withWebhookSecret('whk_secret_...') // Set your webhook secret from LemonSqueezy dashboard
->build();
$client = new Client($config);
use LemonSqueezy\Exception\WebhookVerificationException;
// In your webhook endpoint
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
try {
// Verify using client method
$client->verifyWebhookSignature($payload, $signature);
// Webhook is valid, process it
$data = json_decode($payload, true);
handleWebhook($data);
} catch (WebhookVerificationException $e) {
http_response_code(401);
exit('Webhook verification failed');
}
use LemonSqueezy\Webhook\WebhookVerifier;
// With a PSR-7 stream (e.g., from a framework like Laravel, Symfony)
$stream = $request->getBody(); // PSR-7 StreamInterface
if (WebhookVerifier::isValid($stream, $signature, $webhookSecret)) {
// Process webhook
}
use LemonSqueezy\Exception\WebhookVerificationException;
try {
WebhookVerifier::verify($payload, $signature, $webhookSecret);
} catch (WebhookVerificationException $e) {
match($e->getCode()) {
WebhookVerificationException::MISSING_SECRET =>
// Webhook secret not configured
echo "Configuration error: webhook secret not set",
WebhookVerificationException::EMPTY_SIGNATURE =>
// Signature header missing or empty
echo "Missing signature header",
WebhookVerificationException::INVALID_FORMAT =>
// Signature not in valid hex format
echo "Invalid signature format",
WebhookVerificationException::VERIFICATION_FAILED =>
// Signature does not match
echo "Webhook signature verification failed",
WebhookVerificationException::UNSUPPORTED_ALGORITHM =>
// Unsupported hash algorithm
echo "Unsupported algorithm",
default => echo "Unknown error"
};
}
use LemonSqueezy\Webhook\Dispatcher\EventDispatcher;
use LemonSqueezy\Webhook\Event\WebhookEvent;
// Register a listener for order creation
EventDispatcher::register('order.created', function($event) {
$data = $event->getData();
// Save order, send confirmation email, etc.
echo "New order: {$data['id']}";
});
// In your webhook endpoint:
$body = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
try {
$event = new WebhookEvent($body);
$result = $client->dispatchWebhookEvent($body, $signature, $event);
if ($result->hasFailures()) {
http_response_code(202); // Accepted with some failures
} else {
http_response_code(200);
}
} catch (WebhookVerificationException $e) {
http_response_code(401);
}
EventDispatcher::register('subscription.updated', function($event) {
$subscription = $event->getData();
// Update subscription in your database
});
use LemonSqueezy\Webhook\Listener\EventListenerInterface;
use LemonSqueezy\Webhook\Event\EventInterface;
class OrderCreatedListener implements EventListenerInterface {
public function handle(EventInterface $event): void {
$data = $event->getData();
// Process order creation
}
}
EventDispatcher::register('order.created', new OrderCreatedListener());
EventDispatcher::register('order.created', new SaveOrderListener());
EventDispatcher::register('order.created', new SendEmailListener());
EventDispatcher::register('order.created', new LogAnalyticsListener());
$customer = $client->customers()->get('cust-123');
echo $customer->getId(); // 'cust-123'
echo $customer->getEmail(); // '[email protected]'
echo $customer->getAttribute('name'); // Access any attribute
$attributes = $customer->getAttributes(); // Get all attributes
$meta = $customer->getMeta(); // Get meta information