solidworx/klarna-invoice
Laravel package for Klarna Invoice payments. Provides helpers and integration scaffolding to create invoices, handle checkout/payment flows, and manage customer/order details within your Laravel app.
## Getting Started
### Minimal Setup
1. **Installation**:
```bash
composer require solidworx/klarna-invoice
Ensure you also install the companion package for integration with Payum:
composer require payum/klarna-invoice
First Use Case:
use SolidWorx\KlarnaInvoice\Client;
$client = new Client(
config('services.klarna.secret_key'),
config('services.klarna.public_key'),
config('services.klarna.test_mode') // Set to true for sandbox
);
Where to Look First:
src/Client.php for API interactions and src/Invoice.php for invoice creation/modification.config/services.php:
'klarna' => [
'secret_key' => env('KLARNA_SECRET_KEY'),
'public_key' => env('KLARNA_PUBLIC_KEY'),
'test_mode' => env('KLARNA_TEST_MODE', false),
],
Invoice Creation:
Use the Client to create an invoice via Payum’s KlarnaInvoice gateway:
$gateway = $payum->getGateway('klarna_invoice');
$invoice = $gateway->createInvoice([
'amount' => 100.00,
'currency' => 'SEK',
'description' => 'Order #12345',
'purchase_country' => 'SE',
'purchase_city' => 'Stockholm',
'order_amount' => 100.00,
'order_tax_amount' => 25.00,
'order_vat_percent' => 25,
'order_lines' => [
['type' => 'physical', 'reference' => 'book-123', 'name' => 'Book', 'quantity' => 1, 'unit_price' => 100.00, 'tax_rate' => 25, 'total_amount' => 100.00, 'total_tax_amount' => 25.00],
],
'customer' => [
'title' => 'Mr',
'given_name' => 'John',
'family_name' => 'Doe',
'email' => 'john.doe@example.com',
'date_of_birth' => '1980-01-01',
'personal_identity_number' => '198001011234', // Required for SE invoices
],
]);
Client class alone won’t handle this; Payum’s gateway abstracts the process.Fetching Invoice Status:
$invoice = $client->fetchInvoice($invoiceId);
$status = $invoice->getStatus(); // 'created', 'paid', 'cancelled', etc.
Cancelling an Invoice:
$client->cancelInvoice($invoiceId);
Webhook Handling:
HandleIncomingWebhook trait or a middleware to validate and process them:
use SolidWorx\KlarnaInvoice\Webhook\HandleIncomingWebhook;
class KlarnaWebhookController extends Controller
{
use HandleIncomingWebhook;
public function handle(Request $request)
{
$this->validateWebhook($request, config('services.klarna.secret_key'));
// Process the webhook event (e.g., update order status in DB)
}
}
Laravel Service Provider:
Bind the Client to the container for dependency injection:
$this->app->singleton(Client::class, function ($app) {
return new Client(
config('services.klarna.secret_key'),
config('services.klarna.public_key'),
config('services.klarna.test_mode')
);
});
Form Integration:
Use the public_key to initialize Klarna’s hosted checkout in your Blade view:
<klarna-invoice
data-payment-method="invoice"
data-merchant-id="{{ config('services.klarna.merchant_id') }}"
data-payment-id="{{ $invoice->getId() }}"
data-init="true"
data-locale="en-GB">
</klarna-invoice>
<script src="https://cdn.klarna.com/js/klarna.js"></script>
Testing:
Use Klarna’s sandbox environment (set test_mode => true) and mock the Client in tests:
$mockClient = Mockery::mock(Client::class);
$mockClient->shouldReceive('createInvoice')->andReturn($mockInvoice);
$this->app->instance(Client::class, $mockClient);
Missing Dependencies:
payum/klarna-invoice for full functionality. Install both:
composer require solidworx/klarna-invoice payum/klarna-invoice
PHP 8 Compatibility:
#[ReturnTypeWillChange]). Ensure your project uses PHP 8.x.Webhook Validation:
validateWebhook method from HandleIncomingWebhook:
$this->validateWebhook($request, config('services.klarna.secret_key'));
401 Unauthorized.Country-Specific Requirements:
personal_identity_number) for invoices. Omit this field for unsupported countries, but expect Klarna to reject the invoice.Rate Limiting:
$invoice = Cache::remember("klarna_invoice_{$invoiceId}", now()->addHours(1), function () use ($client, $invoiceId) {
return $client->fetchInvoice($invoiceId);
});
Deprecated Methods:
ArrayAccess methods in Invoice are marked with #[ReturnTypeWillChange]. Avoid relying on return types in older PHP versions.Enable API Logging:
Configure the Client to log requests/responses:
$client = new Client($secretKey, $publicKey, $testMode, [
'logger' => new \Monolog\Logger('klarna', [$handler]),
'debug' => true,
]);
Test Mode Quirks:
https://webhook-test.klarna.com).Common Errors:
InvalidParameter: Validate all required fields (e.g., purchase_country, order_lines).AuthenticationFailed: Double-check secret_key and public_key in your config.InvoiceNotFound: Ensure the invoice_id matches Klarna’s format (e.g., inv_123abc).Custom Invoice Data:
Extend the Invoice class to add project-specific fields:
class CustomInvoice extends \SolidWorx\KlarnaInvoice\Invoice
{
public function setCustomField(string $key, $value): self
{
$this->data['custom'][$key] = $value;
return $this;
}
}
Override Webhook Handling:
Extend HandleIncomingWebhook to add custom logic:
class CustomWebhookHandler
{
use HandleIncomingWebhook;
protected function handlePaidEvent($data)
{
// Custom logic for paid invoices
event(new InvoicePaid($data['invoice']['invoice_number']));
}
}
Add Middleware: Use Laravel middleware to pre-process requests/responses:
$client->setMiddleware(function ($request, callable $next) {
$request->
How can I help you explore Laravel packages today?