This commit is contained in:
Mark Gregory
2026-09-30 13:24:33 +01:00
parent bf5357cbcf
commit 5bb4e43665
32 changed files with 2185 additions and 236 deletions
@@ -0,0 +1,415 @@
# SonarDesk Commercial Launch & Selling Guide
## 1. Recommended commercial model
Launch SonarDesk as a **direct-download macOS product with recurring licensing**. Use **Paddle as the production Merchant of Record (MoR)** for the initial launch because this codebase already has Paddle checkout, subscription lifecycle handling, customer lookup, upgrades/cancellation, webhook verification and product mapping implemented.
Do **not** operate Paddle and Lemon Squeezy as two public checkout systems at launch. Pick one system of record. Running two providers doubles reconciliation, refund, subscription-state and support complexity.
### Launch pricing
| Plan | Monthly | Annual | Activations | Positioning |
|---|---:|---:|---:|---|
| Personal | £2.99/month | £24.99/year | 1 Mac | Individual developer |
| Professional | £4.99/month | £44.99/year | 3 Macs | Multi-Mac / professional workflow |
Both plans should include the complete feature set and a **7-day free trial**. Do not artificially cripple Personal. The upgrade is based on activation allowance, which is simple to understand and easy to support.
Annual should be the visual default. At these prices it produces better unit economics than very low monthly pricing because both Paddle and Lemon Squeezy publish a fixed transaction component in addition to their percentage fee.
### Launch offer
For the first 30 days, use a single promotion rather than permanently reducing the list price:
- 20% off the first annual term using a launch coupon such as `LAUNCH20`.
- Do not discount monthly plans.
- Do not promise “lifetime” access while the licensing model is subscription-based.
- Keep the public list price stable so the product does not look disposable or permanently on sale.
## 2. Why Paddle is the recommended launch provider
Paddle's public pay-as-you-go pricing is 5% + $0.50 per checkout transaction and includes payments/billing, tax compliance and related Merchant of Record services. Paddle supports a sandbox, checkout, subscription lifecycle events and signed webhooks.
This project is already designed around Paddle:
- `CheckoutController` supplies Paddle price IDs to Paddle.js.
- `/api/v1/webhooks/paddle` accepts Paddle events.
- `PaddleWebhookVerifier` verifies signed webhook requests.
- `PurchaseProvisioner` provisions from `subscription.*` and `transaction.completed` events.
- `PaddleCatalogSeeder` maps Paddle products/prices to SonarDesk licence products.
- The portal can upgrade Personal to Professional and cancel Paddle subscriptions.
That makes Paddle the lowest-risk route to a release.
Official references:
- Paddle pricing: https://www.paddle.com/pricing
- Paddle quickstart: https://developer.paddle.com/get-started/quickstart/
- Paddle webhooks: https://developer.paddle.com/webhooks/
- Paddle webhook simulator: https://developer.paddle.com/webhooks/simulator/
## 3. Paddle setup — complete production checklist
### A. Create/complete the Paddle account
1. Create the Paddle account and complete business verification.
2. Add the legal/business details that Paddle requests.
3. Configure payout details.
4. Add the production website/domain.
5. Complete Paddle's domain/default payment link approval before launch.
6. Keep the account in sandbox while integrating. Switch the application to production only after the full purchase flow has passed end-to-end testing.
### B. Create the catalog
Create two Paddle products:
**SonarDesk Personal**
- Monthly recurring price: **£3.99 GBP / month**
- Annual recurring price: **£29.99 GBP / year**
- Trial: **7 days**
**SonarDesk Professional**
- Monthly recurring price: **£6.99 GBP / month**
- Annual recurring price: **£59.99 GBP / year**
- Trial: **7 days**
Use tax-inclusive/exclusive behaviour consistently with the checkout experience you want Paddle to present. Paddle, as MoR, calculates the applicable transaction taxes in checkout.
Copy the resulting two product IDs and four price IDs.
### C. Create application credentials
In Paddle Developer Tools:
1. Create a server API key for the licensing application.
2. Create a client-side token for Paddle.js.
3. Never put the server API key into browser JavaScript or source control.
4. Keep sandbox and production credentials separate.
### D. Configure the webhook
Create a Paddle notification destination:
`https://YOUR-DOMAIN/api/v1/webhooks/paddle`
Subscribe at minimum to:
- `transaction.completed`
- `subscription.created`
- `subscription.updated`
- `subscription.activated`
- `subscription.canceled`
- `subscription.paused`
- `subscription.resumed`
- `subscription.past_due`
The current code uses subscription events as the authoritative state for recurring licences. Paddle documents `transaction.completed` as the point at which transaction processing is complete. Paddle also documents at-least-once webhook delivery, so webhook handlers must remain idempotent; this project stores webhook event IDs for that purpose.
Copy the webhook endpoint secret.
### E. Production `.env`
Set the following values on the production server. Do not commit them.
```dotenv
APP_ENV=production
APP_DEBUG=false
APP_URL=https://YOUR-DOMAIN
PADDLE_ENVIRONMENT=production
PADDLE_API_URL=https://api.paddle.com
PADDLE_API_KEY=YOUR_PRODUCTION_API_KEY
PADDLE_CLIENT_SIDE_TOKEN=YOUR_PRODUCTION_CLIENT_TOKEN
PADDLE_WEBHOOK_SECRET=YOUR_PRODUCTION_WEBHOOK_SECRET
PADDLE_WEBHOOK_TOLERANCE=300
PADDLE_PERSONAL_PRODUCT_ID=pro_...
PADDLE_PERSONAL_MONTHLY_PRICE_ID=pri_...
PADDLE_PERSONAL_ANNUAL_PRICE_ID=pri_...
PADDLE_PROFESSIONAL_PRODUCT_ID=pro_...
PADDLE_PROFESSIONAL_MONTHLY_PRICE_ID=pri_...
PADDLE_PROFESSIONAL_ANNUAL_PRICE_ID=pri_...
```
Also configure the existing SonarDesk licence signing keys, mailer, support email and application database.
### F. Seed the price mapping
After the production IDs are in `.env`:
```bash
php artisan config:clear
php artisan db:seed --class=PaddleCatalogSeeder
php artisan config:cache
```
Check the `license_products` table and confirm there are four active Paddle rows with the correct product/price IDs and activation limits.
### G. Test in sandbox before production
Test every one of these scenarios:
1. Personal monthly trial signup.
2. Personal annual trial signup.
3. Professional monthly trial signup.
4. Professional annual trial signup.
5. Licence email is delivered.
6. Licence activates in SonarDesk.
7. Second activation is rejected for Personal.
8. Up to three activations work for Professional.
9. Portal displays the licence.
10. Deactivate a Mac and activate a replacement Mac.
11. Upgrade Personal to Professional.
12. Cancel a subscription.
13. Simulate a failed payment / past-due subscription.
14. Simulate cancellation/expiry and confirm entitlement behaviour.
15. Replay the same webhook and confirm a duplicate licence is not created.
16. Refund test transaction and verify the intended entitlement state.
17. Verify support and transactional email deliverability.
18. Verify checkout on Safari and Chrome, including a private window.
Use Paddle's webhook simulator for lifecycle testing as well as a real sandbox checkout.
### H. Go live
1. Create the production catalog (do not reuse sandbox IDs).
2. Add production API key/client token/webhook secret.
3. Seed the production catalog mapping.
4. Change `PADDLE_ENVIRONMENT=production` and `PADDLE_API_URL=https://api.paddle.com`.
5. Run `php artisan config:cache`.
6. Make one real low-value purchase with a controlled account.
7. Confirm the webhook, licence issuance, email, activation, portal and cancellation path.
8. Refund the test purchase in Paddle after validation if appropriate.
## 4. Lemon Squeezy — alternative setup
Lemon Squeezy is also a Merchant of Record and publishes base ecommerce pricing of 5% + $0.50 per transaction, with additional fees in some cases (for example certain international, PayPal and subscription payments). It also provides software licence keys and a License API.
Official references:
- Pricing: https://www.lemonsqueezy.com/pricing
- Fees: https://docs.lemonsqueezy.com/help/getting-started/fees
- Webhooks: https://docs.lemonsqueezy.com/help/webhooks
- License API: https://docs.lemonsqueezy.com/api/license-api
### Important for this codebase
The application has a Lemon Squeezy webhook verifier and basic purchase provisioning, but the **public checkout and customer portal are currently Paddle-first**. Lemon Squeezy should therefore be treated as an alternative migration path, not a second launch checkout, until its full subscription lifecycle and portal actions are implemented and tested.
If switching to Lemon Squeezy:
1. Create a store and complete activation/verification.
2. Create Personal and Professional products/variants with the same public pricing.
3. Decide whether SonarDesk's own signed licence system remains authoritative (recommended for consistency with the Mac app) or whether you migrate fully to Lemon Squeezy's License API. Do not mix both without a clear source of truth.
4. Create a webhook at:
`https://YOUR-DOMAIN/api/v1/webhooks/lemon-squeezy`
5. Generate a strong signing secret and set:
```dotenv
LEMON_SQUEEZY_WEBHOOK_SECRET=YOUR_SECRET
```
6. Subscribe to the events the application needs, including order creation/refund and all relevant subscription state events.
7. Add `license_products` mappings where `payment_provider=lemon-squeezy`, mapping Lemon Squeezy variant IDs to `external_price_id`.
8. Implement/verify checkout links or overlay checkout on `/buy` before exposing Lemon Squeezy publicly.
9. Extend `PurchaseProvisioner::provisionLemonSqueezy()` so subscription updates, cancellations, pauses, payment failures/recovery and upgrades are handled with the same completeness as Paddle.
10. Add customer-portal actions for cancellation/change-of-plan or route customers to Lemon Squeezy's supported customer management flow.
11. Run the same end-to-end test matrix used for Paddle.
Lemon Squeezy webhooks are signed and should always be verified. Their documentation states that unsuccessful webhook deliveries are retried; keep processing idempotent and persist event identity/state.
## 5. Website conversion strategy
The updated site now has a clearer commercial funnel:
`Home → Features → Pricing → Paddle checkout → licence email → app activation → customer portal`
### Home page
The home page should answer these questions in order:
1. What is it? A native macOS companion for SonarQube.
2. Why should I care? Faster access to project health and issues without browser-tab friction.
3. What does it do? Projects, quality gates, measures, issues, multiple servers and secure token storage.
4. Is it safe? SonarQube tokens are stored in macOS Keychain and server permissions remain authoritative.
5. What does it cost? Clear Personal and Professional pricing.
6. What should I do next? Start the 7-day free trial.
### Product language to keep consistent
**Primary one-line pitch**
> SonarDesk is a native macOS companion for SonarQube that puts project health, quality gates and issues in one focused desktop workspace.
**Short description**
> Monitor SonarQube projects, quality gates, bugs, vulnerabilities, code smells and measures without living in a browser.
**Positioning rule**
Never imply SonarDesk replaces SonarQube. The stronger and more credible position is: **SonarQube remains the source of truth; SonarDesk makes everyday monitoring faster on macOS.**
## 6. Launch channels
### Phase 1 — pre-launch (7–14 days)
- Finish notarised/signable release build and direct-download hosting.
- Finish Paddle production approval.
- Record a 30–60 second clean screen capture showing: connect server → project dashboard → issues → issue details.
- Produce 4–6 high-resolution screenshots.
- Create the launch coupon.
- Test website analytics and conversion events.
- Prepare support macros for activation, lost key, machine replacement, refund and SonarQube connection problems.
- Recruit 5–10 testers from existing developer contacts for final feedback and testimonials you have permission to publish.
### Phase 2 — launch day
Publish in this order:
1. SonarDesk release page on your own site.
2. LinkedIn launch post.
3. Medium article.
4. Relevant developer communities where self-promotion is allowed and useful.
5. Existing customer/user mailing list only if recipients have consented to product marketing.
Do not spam generic communities. Show the product solving a concrete SonarQube workflow problem.
### Phase 3 — first 30 days
Publish practical content rather than repeating sales copy:
- “A faster way to review SonarQube issues on macOS”
- “How I use SonarQube quality gates in a desktop workflow”
- “What SonarDesk stores locally and how tokens are protected”
- “Personal vs Professional: which SonarDesk licence do I need?”
- Short release notes for every update
Track: website → pricing clicks, checkout starts, trial starts, trial-to-paid conversion, cancellations, refunds, activation failures and support topics.
## 7. LinkedIn release post
**SonarDesk 1.0 is now available for macOS.**
If SonarQube is part of your development workflow, you probably know the routine: open the browser, find the project, check the quality gate, scan the latest issues, then switch back to your editor.
I built SonarDesk to make that recurring workflow faster on the Mac.
SonarDesk is a native macOS companion for SonarQube. It brings project health, quality gates, bugs, vulnerabilities, code smells and measures into one focused desktop workspace.
Version 1.0 includes:
- Project dashboards and quality gate status
- Bugs, vulnerabilities and code smells
- Detailed issue views and filtering
- Server-side pagination for larger issue sets
- Multiple SonarQube server configurations
- SonarQube token storage in macOS Keychain
- Direct licensing and a self-service customer portal
SonarQube remains the source of truth. SonarDesk is designed to make the information you check throughout the day quicker to reach and easier to keep visible.
Personal is £24.99/year for one active Mac. Professional is £44.99/year for up to three active Macs. Monthly options are also available, and every plan starts with a 7-day free trial.
Learn more and try SonarDesk: **YOUR_RELEASE_URL**
#macOS #SonarQube #SoftwareDevelopment #CodeQuality #DeveloperTools
## 8. Medium launch article
# Introducing SonarDesk: a native SonarQube companion for macOS
SonarQube is a valuable part of the software-development toolchain. It gives teams a central place to understand code quality, security findings and the state of quality gates. But the information developers need throughout the day often lives one browser context-switch away from the work itself.
That is the problem I wanted SonarDesk to solve.
## A focused Mac workspace for SonarQube
SonarDesk is a native macOS companion for SonarQube. It is not a replacement for SonarQube, and it does not try to become another analysis engine. Your SonarQube server remains the source of truth.
Instead, SonarDesk focuses on the recurring desktop workflow: open a project, see its health, check the quality gate, browse bugs, vulnerabilities and code smells, inspect an issue, and get back to the code.
## What SonarDesk 1.0 includes
The first release includes project dashboards, quality gate status, important measures, issue browsing and detailed issue views. Issue lists support practical filtering and server-side pagination, which helps keep the workflow manageable as result sets grow.
SonarDesk can also keep multiple SonarQube server configurations available from the same Mac application. SonarQube access tokens are stored using macOS Keychain, and access remains governed by the permissions of the credentials you provide.
## Why a native app?
The browser is excellent for deep investigation and administration, and SonarDesk is not intended to remove it from the workflow. The benefit of a dedicated desktop app is focus. The project-health information you check repeatedly can have a consistent place on the Mac, separate from documentation, tickets, dashboards and all the other tabs competing for attention.
## Direct distribution and licensing
SonarDesk is distributed directly for macOS. Customers receive a licence and can manage activations through the SonarDesk customer portal.
There are two plans. Personal supports one active Mac and costs £24.99 per year or £2.99 per month. Professional supports up to three active Macs and costs £44.99 per year or £4.99 per month. Both include the complete feature set and start with a seven-day free trial.
## What comes next
Version 1.0 establishes the core SonarQube monitoring workflow on macOS. Future releases will continue to focus on making project and issue review faster, clearer and more useful without turning SonarDesk into a replacement for the platform it connects to.
If SonarQube is part of your day-to-day development workflow and you work on a Mac, you can learn more and start a free trial here:
**YOUR_RELEASE_URL**
## 9. Short announcement copy
**SonarDesk 1.0 for macOS is available now.** Monitor SonarQube project health, quality gates, bugs, vulnerabilities and code smells from a focused native Mac app. Personal and Professional plans include a 7-day free trial. **YOUR_RELEASE_URL**
## 10. Product listing copy
### Name
SonarDesk
### Tagline
Native SonarQube monitoring for macOS.
### 80-character style description
Monitor SonarQube projects, quality gates and issues from your Mac.
### Full product description
SonarDesk is a native macOS companion for developers and engineering teams using SonarQube. It provides a focused desktop view of project health, quality gates, measures, bugs, vulnerabilities and code smells, with detailed issue views, filtering, server-side pagination and support for multiple SonarQube server configurations. SonarQube tokens are stored in macOS Keychain, and your existing SonarQube permissions remain authoritative.
## 11. Release readiness checklist
Do not announce the public release until all items below are true:
- Production app is signed with Developer ID and notarised.
- DMG/ZIP download is served over HTTPS.
- Version and build number are final.
- Sparkle/update mechanism, if used, is production-configured and signed.
- Privacy policy, terms and cookie information match actual behaviour.
- Support address is monitored.
- Paddle production checkout is approved and working.
- Webhook signature verification is enabled.
- Production webhook endpoint returns successful responses.
- Production product and price IDs are mapped in the database.
- Licence signing private key is backed up securely and is not in source control.
- Licence activation/validation/deactivation work from a clean Mac.
- Purchase email and support email pass SPF/DKIM/DMARC checks.
- Trial, paid renewal, cancellation, failed payment and refund paths are tested.
- Website has working Home, Features, Pricing, Release, Support, Privacy and Terms pages.
- Open Graph image and favicon render correctly.
- A real production purchase has been tested end-to-end.
- Download analytics and checkout conversion events are visible.
- Launch screenshots/video are ready.
- LinkedIn and Medium copy has been proofread and final URLs inserted.
## 12. First commercial targets
For the first 90 days, optimize for learning rather than vanity traffic. Review weekly:
- Unique visitors to the product page
- Pricing-page visits
- Checkout starts
- Trial starts
- Trial-to-paid conversion
- Annual vs monthly mix
- Personal vs Professional mix
- Cancellation/refund reasons
- Activation failure rate
- Top support issues
Do not change pricing every week. Collect enough data to understand whether the problem is traffic, positioning, checkout friction, onboarding or product value before changing the commercial model.
@@ -0,0 +1,59 @@
<?php
namespace App\Console\Commands;
use App\Models\License;
use App\Models\User;
use App\Services\Accounts\PurchasedAccountProvisioner;
use Illuminate\Console\Command;
final class SonarDeskAccountsBackfill extends Command
{
protected $signature = 'sonardesk:accounts:backfill {--dry-run : Report missing customer accounts without creating them} {--no-email : Create accounts without sending password setup links}';
protected $description = 'Create portal accounts for existing licence holders that do not already have one.';
public function handle(PurchasedAccountProvisioner $accounts): int
{
$customers = License::query()
->whereNotNull('customer_email')
->where('customer_email', '<>', '')
->select(['customer_email', 'customer_name'])
->orderBy('customer_email')
->get()
->unique(fn (License $license) => strtolower(trim((string) $license->customer_email)));
$missing = 0;
$created = 0;
foreach ($customers as $license) {
$email = strtolower(trim((string) $license->customer_email));
if ($email === '') {
continue;
}
if (User::query()->whereRaw('lower(email) = ?', [$email])->exists()) {
continue;
}
$missing++;
if ($this->option('dry-run')) {
$this->line("MISSING {$email}");
continue;
}
if ($accounts->ensure($email, $license->customer_name, ! $this->option('no-email'))) {
$created++;
$this->info("CREATED {$email}");
}
}
if ($this->option('dry-run')) {
$this->info("{$missing} account(s) would be created.");
} else {
$this->info("{$created} account(s) created.");
}
return self::SUCCESS;
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Console\Commands;
use App\Services\Licensing\LicenseDeliveryService;
use Illuminate\Console\Command;
final class SonarDeskLicenseDeliver extends Command
{
protected $signature = 'sonardesk:license-deliver {--limit=50 : Maximum pending licence emails to send}';
protected $description = 'Deliver pending SonarDesk licence-key emails';
public function handle(LicenseDeliveryService $delivery): int
{
$limit = max(1, min((int) $this->option('limit'), 100));
$count = $delivery->deliverPending($limit);
$this->info("Delivered {$count} licence email(s).");
return self::SUCCESS;
}
}
@@ -11,68 +11,181 @@ use App\Services\Payments\PurchaseProvisioner;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use RuntimeException;
use Throwable;
final class PaymentWebhookController extends Controller
{
public function __invoke(string $provider, Request $request, PurchaseProvisioner $provisioner, LicenseDeliveryService $delivery): JsonResponse
{
public function __invoke(
string $provider,
Request $request,
PurchaseProvisioner $provisioner,
LicenseDeliveryService $delivery
): JsonResponse {
$raw = (string) $request->getContent();
$verifier = match ($provider) {
'paddle' => app(PaddleWebhookVerifier::class),'lemon-squeezy' => app(LemonSqueezyWebhookVerifier::class),default => null
'paddle' => app(PaddleWebhookVerifier::class),
'lemon-squeezy' => app(LemonSqueezyWebhookVerifier::class),
default => null,
};
if (! $verifier) {
return response()->json(['message' => 'Unknown webhook provider.'], 404);
return response()->json([
'message' => 'Unknown webhook provider.',
], 404);
}
try {
$verifier->verify($request, $raw);
} catch (\Throwable $e) {
} catch (Throwable $e) {
report($e);
return response()->json(['message' => 'Invalid webhook signature.'], 400);
return response()->json([
'message' => 'Invalid webhook signature.',
], 400);
}
try {
$payload = json_decode($raw, true, flags: JSON_THROW_ON_ERROR);
} catch (\Throwable) {
return response()->json(['message' => 'Invalid JSON.'], 400);
$payload = json_decode(
$raw,
true,
flags: JSON_THROW_ON_ERROR
);
} catch (Throwable) {
return response()->json([
'message' => 'Invalid JSON.',
], 400);
}
$externalID = (string) ($provider === 'paddle' ? ($payload['event_id'] ?? '') : ($payload['meta']['event_name'] ?? '').':'.($payload['data']['id'] ?? ''));
$eventType = (string) ($provider === 'paddle' ? ($payload['event_type'] ?? 'unknown') : ($payload['meta']['event_name'] ?? 'unknown'));
$externalID = (string) (
$provider === 'paddle'
? ($payload['event_id'] ?? '')
: ($payload['meta']['event_name'] ?? '')
.':'
.($payload['data']['id'] ?? '')
);
$eventType = (string) (
$provider === 'paddle'
? ($payload['event_type'] ?? 'unknown')
: ($payload['meta']['event_name'] ?? 'unknown')
);
if ($externalID === '') {
return response()->json(['message' => 'Webhook event has no stable identifier.'], 400);
return response()->json([
'message' => 'Webhook event has no stable identifier.',
], 400);
}
$payloadHash = hash('sha256', $raw);
try {
DB::transaction(function () use ($provider, $externalID, $eventType, $payload, $raw, $provisioner) {
$event = LicenseWebhookEvent::firstOrCreate(['provider' => $provider, 'external_event_id' => $externalID], ['event_type' => $eventType, 'payload_sha256' => hash('sha256', $raw), 'payload' => $payload]);
if ($event->processed_at) {
return;
}
if (! hash_equals($event->payload_sha256, hash('sha256', $raw))) {
throw new \RuntimeException('Webhook ID was reused with a different payload.');
}
try {
$provisioner->provision($provider, $payload);
$event->update(['processed_at' => now(), 'processing_error' => null]);
} catch (\Throwable $e) {
$event->update(['processing_error' => mb_substr($e->getMessage(), 0, 4000)]);
throw $e;
}
});
} catch (\Throwable $e) {
report($e);
/*
* Paddle can deliver several related events concurrently.
*
* Laravel retries this complete transaction when MySQL reports
* a deadlock. Five attempts gives short-lived lock contention
* enough opportunity to resolve without acknowledging an event
* that was not actually processed.
*/
DB::transaction(
function () use (
$provider,
$externalID,
$eventType,
$payload,
$payloadHash,
$provisioner
): void {
/*
* Insert the event if this is its first delivery.
*
* Once present, lock the row so duplicate deliveries of
* the same event cannot provision concurrently.
*/
LicenseWebhookEvent::firstOrCreate(
[
'provider' => $provider,
'external_event_id' => $externalID,
],
[
'event_type' => $eventType,
'payload_sha256' => $payloadHash,
'payload' => $payload,
]
);
return response()->json(['message' => 'Webhook could not be processed.'], 500);
$event = LicenseWebhookEvent::query()
->where('provider', $provider)
->where('external_event_id', $externalID)
->lockForUpdate()
->firstOrFail();
if ($event->processed_at) {
return;
}
if (! hash_equals(
(string) $event->payload_sha256,
$payloadHash
)) {
throw new RuntimeException(
'Webhook ID was reused with a different payload.'
);
}
try {
$provisioner->provision(
$provider,
$payload
);
$event->processed_at = now();
$event->processing_error = null;
$event->save();
} catch (Throwable $e) {
/*
* This assignment is useful when the surrounding
* transaction eventually succeeds. If processing
* throws, the transaction itself is rolled back and
* Paddle will retry the event.
*/
$event->processing_error = mb_substr(
$e->getMessage(),
0,
4000
);
$event->save();
throw $e;
}
},
5
);
} catch (Throwable $e) {
report($e);
return response()->json([
'message' => 'Webhook could not be processed.',
], 500);
}
// Delivery is intentionally outside the webhook transaction. A temporary mail
// outage must not roll back an otherwise valid Paddle event. Pending outbox
// rows remain available for portal resend or a later webhook delivery attempt.
/*
* Delivery deliberately happens outside the webhook transaction.
*
* A temporary SMTP failure must not undo a successfully processed
* payment event. The outbox retains anything that still needs
* delivery.
*/
try {
$delivery->deliverPending(10);
} catch (\Throwable $e) {
} catch (Throwable $e) {
report($e);
}
return response()->json(['ok' => true]);
return response()->json([
'ok' => true,
]);
}
}
@@ -17,10 +17,10 @@ final class CheckoutController extends Controller
}
$plans = [
'personal-monthly' => ['name' => 'Personal', 'billing' => 'Monthly', 'display_price' => '£1.99 / month', 'price_id' => $paddle['personal_monthly_price_id'], 'activation_limit' => 1],
'personal-annual' => ['name' => 'Personal', 'billing' => 'Annual', 'display_price' => '£14.99 / year', 'price_id' => $paddle['personal_annual_price_id'], 'activation_limit' => 1],
'professional-monthly' => ['name' => 'Professional', 'billing' => 'Monthly', 'display_price' => '£3.99 / month', 'price_id' => $paddle['professional_monthly_price_id'], 'activation_limit' => 3],
'professional-annual' => ['name' => 'Professional', 'billing' => 'Annual', 'display_price' => '£29.99 / year', 'price_id' => $paddle['professional_annual_price_id'], 'activation_limit' => 3],
'personal-monthly' => ['name' => 'Personal', 'billing' => 'Monthly', 'display_price' => '£2.99 / month', 'price_id' => $paddle['personal_monthly_price_id'], 'activation_limit' => 1],
'personal-annual' => ['name' => 'Personal', 'billing' => 'Annual', 'display_price' => '£24.99 / year', 'price_id' => $paddle['personal_annual_price_id'], 'activation_limit' => 1],
'professional-monthly' => ['name' => 'Professional', 'billing' => 'Monthly', 'display_price' => '£4.99 / month', 'price_id' => $paddle['professional_monthly_price_id'], 'activation_limit' => 3],
'professional-annual' => ['name' => 'Professional', 'billing' => 'Annual', 'display_price' => '£44.99 / year', 'price_id' => $paddle['professional_annual_price_id'], 'activation_limit' => 3],
];
foreach ($plans as $plan) {
@@ -7,15 +7,14 @@ use App\Models\License;
use App\Models\LicenseDeliveryOutbox;
use App\Models\LicenseProduct;
use App\Services\Payments\PaddleClient;
use App\Services\Licensing\LicenseDeliveryService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Mail;
use RuntimeException;
final class PortalController extends Controller
{
public function __construct(private PaddleClient $paddle) {}
public function __construct(private PaddleClient $paddle, private LicenseDeliveryService $delivery) {}
private function owned(Request $request)
{
@@ -116,9 +115,11 @@ final class PortalController extends Controller
return back()->withErrors(['licence' => 'This licence was issued manually and its full key is not recoverable. Contact support.']);
}
$plain = Crypt::decryptString($out->encrypted_license_key);
Mail::raw("Your SonarDesk licence key is:\n\n{$plain}\n\nKeep this key private.", fn ($m) => $m->to($request->user()->email)->subject('Your SonarDesk licence key'));
$out->update(['delivered_at' => now()]);
$out->update([
'recipient_email' => strtolower($request->user()->email),
'delivered_at' => null,
]);
$this->delivery->deliverPending(1);
return back()->with('status', 'Licence key sent to your verified email address.');
}
@@ -3,6 +3,7 @@
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class LicenseDeliveryOutbox extends Model
{
@@ -11,4 +12,9 @@ class LicenseDeliveryOutbox extends Model
protected $fillable = ['license_id', 'encrypted_license_key', 'recipient_email', 'delivered_at'];
protected $casts = ['delivered_at' => 'datetime'];
public function license(): BelongsTo
{
return $this->belongsTo(License::class);
}
}
@@ -0,0 +1,109 @@
<?php
namespace App\Services\Accounts;
use App\Models\User;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use RuntimeException;
final class PurchasedAccountProvisioner
{
public function ensure(
?string $email,
?string $name = null,
bool $sendSetupLink = true
): ?User {
$email = strtolower(trim((string) $email));
if ($email === '' || ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
return null;
}
/*
* Fast path for the normal case.
*
* Paddle can deliver several related webhook events concurrently, so
* this lookup alone cannot guarantee that another request will not
* create the user between this SELECT and our INSERT.
* enure this is pushed
*/
$user = $this->findByEmail($email);
if ($user) {
return $user;
}
$created = false;
try {
$user = User::create([
'name' => $this->displayName($name, $email),
'email' => $email,
'email_verified_at' => now(),
'password' => Str::random(64),
'is_admin' => false,
]);
$created = true;
} catch (UniqueConstraintViolationException $exception) {
/*
* Another webhook may have created this account after our SELECT
* but before our INSERT. In that case the unique email constraint
* correctly rejects our INSERT; simply reuse the account that won
* the race.
*/
$user = $this->findByEmail($email);
if (! $user) {
/*
* The unique violation was not caused by the email account
* appearing concurrently, so preserve the original failure.
*/
throw $exception;
}
}
/*
* Only the request that actually created the account should send the
* account setup/reset link. Concurrent Paddle events must not result
* in several setup emails being sent to the customer.
*/
if ($created && $sendSetupLink) {
DB::afterCommit(static function () use ($email): void {
Password::sendResetLink(['email' => $email]);
});
}
return $user;
}
private function findByEmail(string $email): ?User
{
return User::query()
->whereRaw('LOWER(email) = ?', [$email])
->first();
}
private function displayName(?string $name, string $email): string
{
$name = trim((string) $name);
if ($name !== '') {
return mb_substr($name, 0, 120);
}
$localPart = strstr($email, '@', true) ?: 'SonarDesk Customer';
$localPart = trim(str_replace(['.', '_', '-'], ' ', $localPart));
return mb_substr(
$localPart !== ''
? ucwords($localPart)
: 'SonarDesk Customer',
0,
120
);
}
}
@@ -12,6 +12,7 @@ final class LicenseDeliveryService
{
$delivered = 0;
$pending = LicenseDeliveryOutbox::query()
->with('license')
->whereNull('delivered_at')
->whereNotNull('recipient_email')
->where('recipient_email', '!=', '')
@@ -20,16 +21,28 @@ final class LicenseDeliveryService
->get();
foreach ($pending as $outbox) {
$license = $outbox->license;
if (! $license) {
continue;
}
$plain = Crypt::decryptString($outbox->encrypted_license_key);
$recipient = strtolower(trim((string) $outbox->recipient_email));
if ($recipient === '') {
continue;
}
Mail::raw(
"Thank you for choosing SonarDesk.\n\nYour licence key is:\n\n{$plain}\n\nOpen SonarDesk → Settings → Licence and enter this key to activate your Mac.\n\nKeep this key private. You can manage activations from the SonarDesk licence portal.",
fn ($message) => $message->to($recipient)->subject('Your SonarDesk licence key')
);
$data = [
'customerName' => $license->customer_name,
'edition' => $license->edition,
'licenseKey' => $plain,
'expiresAt' => $license->expires_at,
'portalUrl' => config('sonardesk.portal_url') ?: url('/portal'),
];
Mail::send(['html' => 'emails.license-key', 'text' => 'emails.license-key-text'], $data, function ($message) use ($recipient): void {
$message->to($recipient)->subject('Your SonarDesk licence key');
});
$outbox->update(['delivered_at' => now()]);
$delivered++;
@@ -0,0 +1,63 @@
<?php
namespace App\Services\Payments;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
final class CustomerAccountProvisioner
{
public function ensure(?string $email, ?string $name = null): ?User
{
$email = strtolower(trim((string) $email));
if ($email === '' || ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
return null;
}
$user = User::whereRaw('lower(email) = ?', [$email])->first();
if ($user) {
return $user;
}
$displayName = trim((string) $name);
if ($displayName === '') {
$displayName = Str::headline(Str::before($email, '@')) ?: 'SonarDesk Customer';
}
$user = User::firstOrCreate(
['email' => $email],
[
'name' => $displayName,
// The customer never receives or knows this password. They choose their
// own password through Laravel's signed, single-use reset flow.
'password' => Str::random(64),
// Access still requires possession of the mailbox because account setup
// is completed using the reset link sent to this address.
'email_verified_at' => now(),
],
);
if ($user->wasRecentlyCreated) {
DB::afterCommit(function () use ($email): void {
try {
$status = Password::sendResetLink(['email' => $email]);
if ($status !== Password::RESET_LINK_SENT) {
Log::warning('SonarDesk customer account created but setup email was not sent.', [
'email' => $email,
'status' => $status,
]);
}
} catch (\Throwable $exception) {
// A mail outage must never undo a paid licence. The customer can
// also use Forgot Password once mail is restored.
report($exception);
}
});
}
return $user;
}
}
@@ -2,6 +2,7 @@
namespace App\Services\Payments;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use RuntimeException;
@@ -19,60 +20,147 @@ final class PaddleClient
if (! $response->successful()) {
return null;
}
$data = $response->json('data');
return is_array($data) ? $data : null;
}
public function updateSubscriptionPrice(string $subscriptionID, string $priceID): array
public function subscription(string $subscriptionID): array
{
$this->requireWritableConfiguration();
$response = $this->request()->patch('/subscriptions/'.$subscriptionID, [
'proration_billing_mode' => 'prorated_immediately',
'items' => [[
'price_id' => $priceID,
'quantity' => 1,
]],
]);
$response = $this->request()
->get('/subscriptions/'.$subscriptionID);
return $this->subscriptionData($response, 'Paddle could not update the subscription.');
return $this->subscriptionData(
$response,
'Paddle could not retrieve the subscription.'
);
}
public function cancelSubscriptionImmediately(string $subscriptionID): array
{
public function updateSubscriptionPrice(
string $subscriptionID,
string $priceID
): array {
$this->requireWritableConfiguration();
$response = $this->request()->post('/subscriptions/'.$subscriptionID.'/cancel', [
'effective_from' => 'immediately',
]);
/*
* Paddle restricts subscription item changes while a subscription
* is trialing. Existing item quantities may only be updated using
* do_not_bill during the trial.
*
* Once the subscription is outside its trial we can use normal
* immediate proration.
*/
$subscription = $this->subscription($subscriptionID);
return $this->subscriptionData($response, 'Paddle could not cancel the subscription.');
$status = (string) ($subscription['status'] ?? '');
$prorationBillingMode = $status === 'trialing'
? 'do_not_bill'
: 'prorated_immediately';
/*
* Preserve the existing subscription item and replace its price.
*
* Paddle treats the submitted items array as the desired
* subscription items, so quantity is retained where possible.
*/
$existingItems = is_array($subscription['items'] ?? null)
? $subscription['items']
: [];
$existingItem = $existingItems[0] ?? [];
$quantity = max(
1,
(int) ($existingItem['quantity'] ?? 1)
);
$response = $this->request()->patch(
'/subscriptions/'.$subscriptionID,
[
'proration_billing_mode' => $prorationBillingMode,
'items' => [
[
'price_id' => $priceID,
'quantity' => $quantity,
],
],
]
);
return $this->subscriptionData(
$response,
'Paddle could not update the subscription.'
);
}
private function request()
public function cancelSubscriptionImmediately(
string $subscriptionID
): array {
$this->requireWritableConfiguration();
$response = $this->request()->post(
'/subscriptions/'.$subscriptionID.'/cancel',
[
'effective_from' => 'immediately',
]
);
return $this->subscriptionData(
$response,
'Paddle could not cancel the subscription.'
);
}
private function request(): PendingRequest
{
return Http::baseUrl((string) config('sonardesk.paddle.api_url'))
->withToken((string) config('sonardesk.paddle.api_key'))
return Http::baseUrl(
(string) config('sonardesk.paddle.api_url')
)
->withToken(
(string) config('sonardesk.paddle.api_key')
)
->acceptJson()
->timeout(15);
}
private function requireWritableConfiguration(): void
{
if (trim((string) config('sonardesk.paddle.api_key')) === '') {
throw new RuntimeException('Paddle subscription management is not configured.');
if (
trim(
(string) config('sonardesk.paddle.api_key')
) === ''
) {
throw new RuntimeException(
'Paddle subscription management is not configured.'
);
}
}
private function subscriptionData(Response $response, string $fallback): array
{
private function subscriptionData(
Response $response,
string $fallback
): array {
if (! $response->successful()) {
$detail = trim((string) ($response->json('error.detail') ?? ''));
throw new RuntimeException($detail !== '' ? $detail : $fallback);
$detail = trim(
(string) (
$response->json('error.detail')
?? ''
)
);
throw new RuntimeException(
$detail !== ''
? $detail
: $fallback
);
}
$data = $response->json('data');
if (! is_array($data)) {
throw new RuntimeException($fallback);
}
@@ -3,36 +3,104 @@
namespace App\Services\Payments;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use RuntimeException;
final class PaddleWebhookVerifier implements WebhookVerifier
{
public function verify(Request $request, string $rawBody): void
{
$secret = (string) config('sonardesk.paddle.webhook_secret');
$header = (string) $request->header('Paddle-Signature');
if ($secret === '' || $header === '') {
throw new RuntimeException('Paddle webhook verification is not configured.');
$secret = trim((string) config('sonardesk.paddle.webhook_secret'));
$header = trim((string) $request->header('Paddle-Signature'));
if ($secret === '') {
throw new RuntimeException('Paddle webhook secret is not configured.');
}
if ($header === '') {
throw new RuntimeException('Paddle-Signature header is missing.');
}
$parts = [];
foreach (explode(';', $header) as $part) {
[$k,$v] = array_pad(explode('=', trim($part), 2), 2, null);
if ($k && $v) {
$parts[$k][] = $v;
[$key, $value] = array_pad(
explode('=', trim($part), 2),
2,
null
);
if ($key !== null && $value !== null) {
$parts[$key][] = $value;
}
}
$ts = isset($parts['ts'][0]) ? (int) $parts['ts'][0] : 0;
$timestamp = isset($parts['ts'][0])
? (int) $parts['ts'][0]
: 0;
$signatures = $parts['h1'] ?? [];
$tolerance = max(1, (int) config('sonardesk.paddle.timestamp_tolerance', 300));
if (! $ts || abs(time() - $ts) > $tolerance) {
throw new RuntimeException('Paddle webhook timestamp is outside the allowed tolerance.');
if ($timestamp === 0) {
throw new RuntimeException(
'Paddle webhook signature has no timestamp.'
);
}
$expected = hash_hmac('sha256', $ts.':'.$rawBody, $secret);
if ($signatures === []) {
throw new RuntimeException(
'Paddle webhook signature has no h1 signature.'
);
}
$tolerance = max(
1,
(int) config('sonardesk.paddle.timestamp_tolerance', 300)
);
$age = abs(time() - $timestamp);
if ($age > $tolerance) {
throw new RuntimeException(
"Paddle webhook timestamp is outside the allowed tolerance ({$age}s)."
);
}
$signedPayload = $timestamp . ':' . $rawBody;
$expected = hash_hmac(
'sha256',
$signedPayload,
$secret
);
Log::debug('Paddle webhook signature diagnostics', [
'timestamp' => $timestamp,
'age_seconds' => $age,
'body_length' => strlen($rawBody),
'body_sha256' => hash('sha256', $rawBody),
// Safe diagnostics — do NOT log the secret itself.
'secret_prefix' => substr($secret, 0, 11),
'secret_length' => strlen($secret),
'received_signature_prefixes' => array_map(
static fn (string $signature): string =>
substr($signature, 0, 12),
$signatures
),
'expected_signature_prefix' => substr($expected, 0, 12),
]);
foreach ($signatures as $signature) {
if (hash_equals($expected, $signature)) {
return;
}
}
throw new RuntimeException('Paddle webhook signature is invalid.');
throw new RuntimeException(
'Paddle webhook signature is invalid.'
);
}
}
@@ -3,14 +3,22 @@
namespace App\Services\Payments;
use App\Models\License;
use App\Models\LicenseDeliveryOutbox;
use App\Models\LicenseProduct;
use App\Services\Accounts\PurchasedAccountProvisioner;
use App\Services\Licensing\LicenseIssuer;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use RuntimeException;
use Throwable;
final class PurchaseProvisioner
{
public function __construct(private LicenseIssuer $issuer, private PaddleClient $paddle) {}
public function __construct(
private LicenseIssuer $issuer,
private PaddleClient $paddle,
private PurchasedAccountProvisioner $accounts,
) {}
public function provision(string $provider, array $event): void
{
@@ -26,16 +34,24 @@ final class PurchaseProvisioner
return;
}
throw new RuntimeException('Unsupported payment provider.');
throw new RuntimeException(
'Unsupported payment provider.'
);
}
private function provisionPaddle(array $event): void
{
$type = (string) ($event['event_type'] ?? '');
$data = $event['data'] ?? [];
$data = is_array($event['data'] ?? null)
? $event['data']
: [];
if (str_starts_with($type, 'subscription.')) {
$this->syncPaddleSubscription($type, $data);
$this->syncPaddleSubscription(
$type,
$data
);
return;
}
@@ -47,200 +63,724 @@ final class PurchaseProvisioner
}
if ($type === 'transaction.refunded') {
$transactionID = (string) ($data['id'] ?? '');
if ($transactionID !== '') {
License::where('payment_provider', 'paddle')
->where('external_order_id', $transactionID)
$transactionID = $this->nullableString(
$data['id'] ?? null
);
if ($transactionID !== null) {
License::query()
->where('payment_provider', 'paddle')
->where(
'external_order_id',
$transactionID
)
->whereNull('external_subscription_id')
->whereNull('revoked_at')
->update(['revoked_at' => now(), 'revoke_reason' => 'Payment refunded']);
->update([
'revoked_at' => now(),
'revoke_reason' => 'Payment refunded',
]);
}
}
}
private function syncPaddleSubscription(string $type, array $data): void
{
$subscriptionID = (string) ($data['id'] ?? '');
if ($subscriptionID === '') {
throw new RuntimeException('Paddle subscription webhook has no subscription ID.');
private function syncPaddleSubscription(
string $type,
array $data
): void {
$subscriptionID = $this->nullableString(
$data['id'] ?? null
);
if ($subscriptionID === null) {
throw new RuntimeException(
'Paddle subscription webhook has no subscription ID.'
);
}
$status = (string) ($data['status'] ?? '');
$item = $this->firstRecurringItem($data['items'] ?? []);
$price = $item['price'] ?? [];
$priceID = (string) ($price['id'] ?? $item['price_id'] ?? '');
$productID = (string) ($price['product_id'] ?? $item['product_id'] ?? '');
/*
* Multiple Paddle events for the same subscription can arrive
* simultaneously.
*
* The unique index protects database integrity, but by itself it
* cannot stop two workers from both observing "no licence" before
* either worker inserts the subscription ID.
*
* A MySQL advisory lock serialises provisioning for one Paddle
* subscription while still allowing unrelated subscriptions to be
* processed concurrently.
*/
$lockName = 'sonardesk:paddle:subscription:'
.$subscriptionID;
$license = License::where('payment_provider', 'paddle')
->where('external_subscription_id', $subscriptionID)
$this->withMysqlLock(
$lockName,
function () use (
$type,
$data,
$subscriptionID
): void {
$this->syncLockedPaddleSubscription(
$type,
$data,
$subscriptionID
);
}
);
}
private function syncLockedPaddleSubscription(
string $type,
array $data,
string $subscriptionID
): void {
$transactionID = $this->nullableString(
$data['transaction_id'] ?? null
);
$status = (string) ($data['status'] ?? '');
$items = is_array($data['items'] ?? null)
? $data['items']
: [];
$item = $this->firstRecurringItem($items);
$price = is_array($item['price'] ?? null)
? $item['price']
: [];
$priceID = (string) (
$price['id']
?? $item['price_id']
?? ''
);
$productID = (string) (
$price['product_id']
?? $item['product_id']
?? ''
);
/*
* The Paddle subscription ID is the authoritative identity for a
* recurring licence.
*
* lockForUpdate protects an existing licence while we mutate it.
* Creation of a missing licence is serialised by the advisory lock
* acquired by syncPaddleSubscription().
*/
$license = License::query()
->where('payment_provider', 'paddle')
->where(
'external_subscription_id',
$subscriptionID
)
->lockForUpdate()
->first();
if (! $license) {
$product = $this->mappedProduct('paddle', $priceID, $productID);
$custom = is_array($data['custom_data'] ?? null) ? $data['custom_data'] : [];
$customer = $this->paddle->customer($this->nullableString($data['customer_id'] ?? null));
$product = $this->mappedProduct(
'paddle',
$priceID,
$productID
);
$custom = is_array($data['custom_data'] ?? null)
? $data['custom_data']
: [];
$customerID = $this->nullableString(
$data['customer_id'] ?? null
);
$customer = $this->paddle->customer(
$customerID
) ?? [];
[$license] = $this->issuer->issue(
$product,
$this->nullableString($custom['customer_name'] ?? $custom['name'] ?? $customer['name'] ?? null),
$this->nullableString($custom['customer_email'] ?? $custom['email'] ?? $customer['email'] ?? null),
$this->nullableString(
$custom['customer_name']
?? $custom['name']
?? $customer['name']
?? null
),
$this->nullableString(
$custom['customer_email']
?? $custom['email']
?? $customer['email']
?? null
),
'paddle',
$this->nullableString($data['transaction_id'] ?? null),
$this->nullableString($data['customer_id'] ?? null),
$transactionID,
$customerID,
true,
);
$license->external_subscription_id = $subscriptionID;
} elseif ($priceID !== '' && $priceID !== $license->external_price_id) {
// Upgrades/downgrades change the entitlement attached to the existing key.
$product = $this->mappedProduct('paddle', $priceID, $productID);
/*
* LicenseIssuer may return an existing licence if the
* transaction ID has already been seen.
*
* Re-read it with a row lock before attaching the Paddle
* subscription.
*/
$license = License::query()
->whereKey($license->getKey())
->lockForUpdate()
->firstOrFail();
/*
* Do not attach this subscription to a licence already owned
* by a different subscription.
*/
if (
$license->external_subscription_id !== null
&& $license->external_subscription_id
!== $subscriptionID
) {
throw new RuntimeException(
'Paddle transaction resolved to a licence '
.'belonging to another subscription.'
);
}
$license->external_subscription_id =
$subscriptionID;
} elseif (
$priceID !== ''
&& $priceID !== $license->external_price_id
) {
/*
* Upgrades and downgrades modify the entitlement attached to
* the existing licence key rather than issuing another key.
*/
$product = $this->mappedProduct(
'paddle',
$priceID,
$productID
);
$license->license_product_id = $product->id;
$license->edition = $product->edition;
$license->activation_limit = $product->activation_limit;
$license->max_major_version = $product->max_major_version;
$license->activation_limit =
$product->activation_limit;
$license->max_major_version =
$product->max_major_version;
}
$periodEnd = $data['current_billing_period']['ends_at'] ?? null;
$periodEnd =
$data['current_billing_period']['ends_at']
?? null;
$scheduled = $data['scheduled_change'] ?? null;
$cancelAt = is_array($scheduled) && ($scheduled['action'] ?? null) === 'cancel'
$cancelAt = is_array($scheduled)
&& ($scheduled['action'] ?? null) === 'cancel'
? ($scheduled['effective_at'] ?? null)
: null;
$license->external_customer_id = $this->nullableString($data['customer_id'] ?? null) ?? $license->external_customer_id;
$license->external_price_id = $priceID !== '' ? $priceID : $license->external_price_id;
$license->subscription_status = $status !== '' ? $status : $license->subscription_status;
$license->current_period_ends_at = $periodEnd ? Carbon::parse($periodEnd) : $license->current_period_ends_at;
$license->cancel_scheduled_at = $cancelAt ? Carbon::parse($cancelAt) : null;
$license->external_customer_id =
$this->nullableString(
$data['customer_id'] ?? null
)
?? $license->external_customer_id;
if (in_array($status, ['active', 'trialing'], true)) {
$this->backfillPaddleCustomer(
$license,
$data
);
/*
* Account provisioning is expected to be idempotent.
*/
$this->accounts->ensure(
$license->customer_email,
$license->customer_name
);
if ($priceID !== '') {
$license->external_price_id = $priceID;
}
if (
$transactionID !== null
&& ! $license->external_order_id
) {
$license->external_order_id =
$transactionID;
}
if ($status !== '') {
$license->subscription_status = $status;
}
if ($periodEnd) {
$license->current_period_ends_at =
Carbon::parse($periodEnd);
}
$license->cancel_scheduled_at = $cancelAt
? Carbon::parse($cancelAt)
: null;
/*
* Subscription entitlement.
*/
if (in_array(
$status,
['active', 'trialing'],
true
)) {
$license->revoked_at = null;
$license->revoke_reason = null;
// Trialing/active subscriptions remain valid through the current period.
$license->expires_at = $periodEnd ? Carbon::parse($periodEnd) : null;
$license->expires_at = $periodEnd
? Carbon::parse($periodEnd)
: null;
} elseif ($status === 'past_due') {
// Do not instantly kill a licence on the first failed renewal. Preserve the
// period Paddle says is current; a later canceled event ends entitlement.
$license->expires_at = $periodEnd ? Carbon::parse($periodEnd) : ($license->expires_at ?? now()->addDays(7));
} elseif (in_array($status, ['canceled', 'paused'], true)) {
/*
* A failed renewal does not immediately destroy the
* entitlement. Preserve Paddle's current billing period when
* available and otherwise provide the existing grace period.
*/
$license->expires_at = $periodEnd
? Carbon::parse($periodEnd)
: (
$license->expires_at
?? now()->addDays(7)
);
} elseif (in_array(
$status,
['canceled', 'paused'],
true
)) {
$license->expires_at = now();
$license->revoked_at = now();
$license->revoke_reason = $status === 'paused' ? 'Subscription paused' : 'Subscription canceled';
$license->revoke_reason =
$status === 'paused'
? 'Subscription paused'
: 'Subscription canceled';
}
$license->save();
}
private function syncPaddleTransaction(array $data): void
{
$subscriptionID = $this->nullableString($data['subscription_id'] ?? null);
$transactionID = (string) ($data['id'] ?? '');
private function syncPaddleTransaction(
array $data
): void {
$subscriptionID = $this->nullableString(
$data['subscription_id'] ?? null
);
// Recurring purchases are provisioned from subscription events because those
// events contain the authoritative trial/status/current-period state.
if ($subscriptionID) {
License::where('payment_provider', 'paddle')
->where('external_subscription_id', $subscriptionID)
->whereNull('external_order_id')
->update(['external_order_id' => $transactionID ?: null]);
$transactionID = $this->nullableString(
$data['id'] ?? null
);
/*
* A recurring transaction belongs to its subscription.
*
* Serialise this operation using the same lock as subscription
* provisioning. This prevents transaction.completed from updating
* the licence while a subscription event is still creating or
* modifying it.
*/
if ($subscriptionID !== null) {
$lockName = 'sonardesk:paddle:subscription:'
.$subscriptionID;
$this->withMysqlLock(
$lockName,
function () use (
$subscriptionID,
$transactionID
): void {
if ($transactionID === null) {
return;
}
$license = License::query()
->where(
'payment_provider',
'paddle'
)
->where(
'external_subscription_id',
$subscriptionID
)
->lockForUpdate()
->first();
/*
* transaction.completed may legitimately arrive before
* subscription.created. In that case there is nothing
* to update yet. The subscription event will create the
* licence and Paddle's transaction_id can populate the
* order ID.
*/
if (! $license) {
return;
}
if (! $license->external_order_id) {
$license->external_order_id =
$transactionID;
$license->save();
}
}
);
return;
}
// Keep support for any future one-time Paddle licence product.
$item = $data['items'][0] ?? [];
$price = $item['price'] ?? [];
$priceID = (string) ($price['id'] ?? $item['price_id'] ?? '');
$productID = (string) ($price['product_id'] ?? $item['product_id'] ?? '');
$product = $this->mappedProduct('paddle', $priceID, $productID);
$custom = is_array($data['custom_data'] ?? null) ? $data['custom_data'] : [];
$customer = $this->paddle->customer($this->nullableString($data['customer_id'] ?? null));
/*
* No subscription ID means this may be a one-time purchase.
*/
$items = is_array($data['items'] ?? null)
? $data['items']
: [];
$this->issuer->issue(
$item = $items[0] ?? [];
$price = is_array($item['price'] ?? null)
? $item['price']
: [];
$priceID = (string) (
$price['id']
?? $item['price_id']
?? ''
);
$productID = (string) (
$price['product_id']
?? $item['product_id']
?? ''
);
$product = $this->mappedProduct(
'paddle',
$priceID,
$productID
);
$custom = is_array($data['custom_data'] ?? null)
? $data['custom_data']
: [];
$customerID = $this->nullableString(
$data['customer_id'] ?? null
);
$customer = $this->paddle->customer(
$customerID
) ?? [];
[$license] = $this->issuer->issue(
$product,
$this->nullableString($custom['customer_name'] ?? $custom['name'] ?? $customer['name'] ?? null),
$this->nullableString($custom['customer_email'] ?? $custom['email'] ?? $customer['email'] ?? null),
$this->nullableString(
$custom['customer_name']
?? $custom['name']
?? $customer['name']
?? null
),
$this->nullableString(
$custom['customer_email']
?? $custom['email']
?? $customer['email']
?? null
),
'paddle',
$transactionID,
$this->nullableString($data['customer_id'] ?? null),
$customerID,
true,
);
$this->accounts->ensure(
$license->customer_email,
$license->customer_name
);
}
private function provisionLemonSqueezy(array $event): void
{
$type = (string) ($event['meta']['event_name'] ?? '');
$attributes = $event['data']['attributes'] ?? [];
$order = (string) ($event['data']['id'] ?? $attributes['order_id'] ?? '');
private function provisionLemonSqueezy(
array $event
): void {
$type = (string) (
$event['meta']['event_name']
?? ''
);
if (in_array($type, ['order_refunded', 'subscription_expired'], true)) {
License::where('payment_provider', 'lemon-squeezy')
$attributes = is_array(
$event['data']['attributes'] ?? null
)
? $event['data']['attributes']
: [];
$order = (string) (
$event['data']['id']
?? $attributes['order_id']
?? ''
);
if (in_array(
$type,
[
'order_refunded',
'subscription_expired',
],
true
)) {
License::query()
->where(
'payment_provider',
'lemon-squeezy'
)
->where('external_order_id', $order)
->whereNull('revoked_at')
->update(['revoked_at' => now(), 'revoke_reason' => 'Payment refunded or subscription expired']);
->update([
'revoked_at' => now(),
'revoke_reason' =>
'Payment refunded or subscription expired',
]);
return;
}
if (! in_array($type, ['order_created', 'subscription_created'], true)) {
if (! in_array(
$type,
[
'order_created',
'subscription_created',
],
true
)) {
return;
}
$product = $this->mappedProduct(
'lemon-squeezy',
(string) ($attributes['variant_id'] ?? ''),
(string) ($attributes['product_id'] ?? ''),
(string) (
$attributes['variant_id']
?? ''
),
(string) (
$attributes['product_id']
?? ''
),
);
$this->issuer->issue(
[$license] = $this->issuer->issue(
$product,
$this->nullableString($attributes['user_name'] ?? null),
$this->nullableString($attributes['user_email'] ?? null),
$this->nullableString(
$attributes['user_name'] ?? null
),
$this->nullableString(
$attributes['user_email'] ?? null
),
'lemon-squeezy',
$order,
$this->nullableString($attributes['customer_id'] ?? null),
$this->nullableString(
$attributes['customer_id'] ?? null
),
true,
);
$this->accounts->ensure(
$license->customer_email,
$license->customer_name
);
}
private function mappedProduct(string $provider, string $priceID, string $productID): LicenseProduct
{
// Price IDs are the authoritative mapping because monthly and annual prices
// intentionally share the same Paddle product ID.
private function backfillPaddleCustomer(
License $license,
array $data
): void {
$custom = is_array(
$data['custom_data'] ?? null
)
? $data['custom_data']
: [];
$customerID = $this->nullableString(
$data['customer_id']
?? $license->external_customer_id
);
$customer = $this->paddle->customer(
$customerID
) ?? [];
$name = $this->nullableString(
$custom['customer_name']
?? $custom['name']
?? $customer['name']
?? null
);
$email = $this->nullableString(
$custom['customer_email']
?? $custom['email']
?? $customer['email']
?? null
);
if (! $license->customer_name && $name) {
$license->customer_name = $name;
}
if (! $license->customer_email && $email) {
$email = strtolower($email);
$license->customer_email = $email;
LicenseDeliveryOutbox::query()
->where(
'license_id',
$license->id
)
->whereNull('delivered_at')
->update([
'recipient_email' => $email,
]);
}
}
private function mappedProduct(
string $provider,
string $priceID,
string $productID
): LicenseProduct {
/*
* Price IDs are authoritative because multiple billing intervals
* can belong to the same Paddle product.
*/
if ($priceID !== '') {
$product = LicenseProduct::where('payment_provider', $provider)
->where('external_price_id', $priceID)
$product = LicenseProduct::query()
->where(
'payment_provider',
$provider
)
->where(
'external_price_id',
$priceID
)
->where('active', true)
->first();
} else {
$product = LicenseProduct::where('payment_provider', $provider)
->where('external_product_id', $productID)
$product = LicenseProduct::query()
->where(
'payment_provider',
$provider
)
->where(
'external_product_id',
$productID
)
->where('active', true)
->first();
}
if (! $product) {
throw new RuntimeException("No active licence product maps to {$provider} price {$priceID} / product {$productID}.");
throw new RuntimeException(
"No active licence product maps to {$provider} "
."price {$priceID} / product {$productID}."
);
}
return $product;
}
private function firstRecurringItem(array $items): array
{
private function firstRecurringItem(
array $items
): array {
foreach ($items as $item) {
if (! is_array($item)) {
continue;
}
if (($item['recurring'] ?? true) === true) {
return $item;
}
}
return $items[0] ?? [];
$first = $items[0] ?? [];
return is_array($first)
? $first
: [];
}
private function nullableString(mixed $value): ?string
{
private function nullableString(
mixed $value
): ?string {
if (! is_scalar($value)) {
return null;
}
$value = trim((string) $value);
return $value === '' ? null : $value;
return $value === ''
? null
: $value;
}
/**
* Execute a callback while holding a MySQL advisory lock.
*
* The lock is connection-scoped, so it must always be explicitly
* released in finally. A short timeout is sufficient because Paddle
* will retry failed webhook deliveries and the controller also retries
* database deadlocks.
*/
private function withMysqlLock(
string $name,
callable $callback
): mixed {
/*
* MySQL advisory lock names have a finite length. Hashing also
* prevents provider supplied identifiers from creating unusual
* lock names.
*/
$lockName = 'sd:'.substr(hash('sha256', $name), 0, 61);
$row = DB::selectOne(
'SELECT GET_LOCK(?, ?) AS acquired',
[
$lockName,
10,
]
);
$acquired = (int) (
$row->acquired
?? 0
);
if ($acquired !== 1) {
throw new RuntimeException(
'Could not acquire Paddle subscription lock.'
);
}
try {
return $callback();
} finally {
try {
DB::selectOne(
'SELECT RELEASE_LOCK(?) AS released',
[$lockName]
);
} catch (Throwable $e) {
/*
* Do not hide the original processing exception merely
* because releasing an advisory lock failed. MySQL also
* releases connection-owned locks when the connection
* closes.
*/
report($e);
}
}
}
}
+6 -2
View File
@@ -1,6 +1,7 @@
<?php
return [
'environment' => env('SONARDESK_ENVIRONMENT', 'develop'),
'product_code' => env('SONARDESK_PRODUCT_CODE', 'sonardesk'),
'private_key_path' => env('SONARDESK_LICENSE_PRIVATE_KEY_PATH'),
'public_key' => env('SONARDESK_LICENSE_PUBLIC_KEY'),
@@ -26,6 +27,7 @@ return [
'alert_emails' => array_values(array_filter(array_map('trim', explode(',', (string) env('SONARDESK_SUPPORT_ALERT_EMAILS', ''))))),
'notify_admin_users' => filter_var(env('SONARDESK_SUPPORT_NOTIFY_ADMINS', true), FILTER_VALIDATE_BOOL),
],
'paddle' => [
'api_key' => env('PADDLE_API_KEY'),
'client_side_token' => env('PADDLE_CLIENT_SIDE_TOKEN'),
@@ -33,13 +35,15 @@ return [
'api_url' => env('PADDLE_API_URL', env('APP_ENV') === 'production' ? 'https://api.paddle.com' : 'https://sandbox-api.paddle.com'),
'webhook_secret' => env('PADDLE_WEBHOOK_SECRET'),
'timestamp_tolerance' => (int) env('PADDLE_WEBHOOK_TOLERANCE', 300),
'personal_product_id' => env('PADDLE_PERSONAL_PRODUCT_ID'),
// SonarDesk is one Paddle product with four recurring prices.
'product_id' => env('PADDLE_PRODUCT_ID'),
'personal_monthly_price_id' => env('PADDLE_PERSONAL_MONTHLY_PRICE_ID'),
'personal_annual_price_id' => env('PADDLE_PERSONAL_ANNUAL_PRICE_ID'),
'professional_product_id' => env('PADDLE_PROFESSIONAL_PRODUCT_ID'),
'professional_monthly_price_id' => env('PADDLE_PROFESSIONAL_MONTHLY_PRICE_ID'),
'professional_annual_price_id' => env('PADDLE_PROFESSIONAL_ANNUAL_PRICE_ID'),
],
'lemon_squeezy' => [
'webhook_secret' => env('LEMON_SQUEEZY_WEBHOOK_SECRET'),
],
Binary file not shown.
@@ -10,10 +10,10 @@ class PaddleCatalogSeeder extends Seeder
public function run(): void
{
$products = [
['code' => 'personal-monthly', 'name' => 'SonarDesk Personal Monthly', 'edition' => 'Personal', 'activation_limit' => 1, 'external_product_id' => config('sonardesk.paddle.personal_product_id'), 'external_price_id' => config('sonardesk.paddle.personal_monthly_price_id')],
['code' => 'personal-annual', 'name' => 'SonarDesk Personal Annual', 'edition' => 'Personal', 'activation_limit' => 1, 'external_product_id' => config('sonardesk.paddle.personal_product_id'), 'external_price_id' => config('sonardesk.paddle.personal_annual_price_id')],
['code' => 'professional-monthly', 'name' => 'SonarDesk Professional Monthly', 'edition' => 'Professional', 'activation_limit' => 3, 'external_product_id' => config('sonardesk.paddle.professional_product_id'), 'external_price_id' => config('sonardesk.paddle.professional_monthly_price_id')],
['code' => 'professional-annual', 'name' => 'SonarDesk Professional Annual', 'edition' => 'Professional', 'activation_limit' => 3, 'external_product_id' => config('sonardesk.paddle.professional_product_id'), 'external_price_id' => config('sonardesk.paddle.professional_annual_price_id')],
['code' => 'personal-monthly', 'name' => 'SonarDesk Personal Monthly', 'edition' => 'Personal', 'activation_limit' => 1, 'external_product_id' => config('sonardesk.paddle.product_id'), 'external_price_id' => config('sonardesk.paddle.personal_monthly_price_id')],
['code' => 'personal-annual', 'name' => 'SonarDesk Personal Annual', 'edition' => 'Personal', 'activation_limit' => 1, 'external_product_id' => config('sonardesk.paddle.product_id'), 'external_price_id' => config('sonardesk.paddle.personal_annual_price_id')],
['code' => 'professional-monthly', 'name' => 'SonarDesk Professional Monthly', 'edition' => 'Professional', 'activation_limit' => 3, 'external_product_id' => config('sonardesk.paddle.product_id'), 'external_price_id' => config('sonardesk.paddle.professional_monthly_price_id')],
['code' => 'professional-annual', 'name' => 'SonarDesk Professional Annual', 'edition' => 'Professional', 'activation_limit' => 3, 'external_product_id' => config('sonardesk.paddle.product_id'), 'external_price_id' => config('sonardesk.paddle.professional_annual_price_id')],
];
foreach ($products as $data) {
+3 -3
View File
@@ -18,14 +18,14 @@ add('shared_dirs', ['storage']);
add('writable_dirs', ['storage', 'bootstrap/cache']);
// Host Definitions
host('main')
->set('hostname', 'sonardesk.absdev.net')
host('production')
->set('hostname', 'sonardsk.absdev.net')
->set('remote_user', 'mag')
->set('branch', 'main')
->set('deploy_path', '/var/www/sonardesk/main');
host('stage')
->set('hostname', 'sonardesk.absdev.net')
->set('hostname', 'sonardesk.stage.absdev.net')
->set('remote_user', 'mag')
->set('branch', 'stage')
->set('deploy_path', '/var/www/sonardesk/stage');
@@ -0,0 +1,11 @@
## Licensing/email release checks
- Production app endpoint: `https://sonardsk.absdev.net`.
- Stage app endpoint: `https://sonardesk.stage.absdev.net`.
- Production must use Paddle production credentials and the production webhook destination.
- `MAIL_MAILER` must be a real delivery transport in production; never `log`.
- Run the Laravel scheduler continuously so pending licence-key emails retry automatically.
- Verify `php artisan sonardesk:license-deliver` reports no unexpected pending delivery failures.
- Verify a real Paddle purchase creates one licence, sends one key email, activates a clean Mac, validates after relaunch, and deactivates from the portal.
- Never deploy `.env`, signing seeds, Paddle secrets, or webhook secrets from source control.
@@ -33,8 +33,8 @@
<div class="card checkout-status" id="checkout-status" hidden>
<h2>Purchase received</h2>
<p>Paddle is confirming your subscription. Your SonarDesk licence key will be sent to the email used at checkout. You can then activate it in <strong>SonarDesk → Settings → Licence</strong>.</p>
<p class="muted">If the email takes a moment, wait for the Paddle confirmation and check your junk folder. You can also create a portal account with the same email address.</p>
<p>Paddle is confirming your subscription. Your SonarDesk licence key is generated by our licensing server and emailed to the address used at checkout. You can then activate it in <strong>SonarDesk → Settings → Licence</strong>.</p>
<p class="muted">Delivery normally follows the subscription webhook within moments. Check your junk folder if needed. You can also create a portal account with the same email address and resend the key from My licences.</p>
<a class="btn" href="{{ route('register') }}">Create portal account</a>
</div>
@@ -0,0 +1,20 @@
SonarDesk — Your licence is ready
{{ $customerName ? 'Hello '.$customerName.',' : 'Hello,' }}
Thank you for choosing SonarDesk. Your {{ $edition }} licence key is:
{{ $licenseKey }}
To activate:
1. Open SonarDesk.
2. Open Settings → Licence.
3. Paste the key above and select Activate.
@if($expiresAt)Current entitlement period: {{ $expiresAt->format('j M Y') }}.
@endif
@if($portalUrl)Manage your licence: {{ $portalUrl }}
@endif
Keep this key private.
@@ -0,0 +1,19 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Your SonarDesk licence key</title></head>
<body style="margin:0;background:#f4f6f8;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;color:#172033">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background:#f4f6f8;padding:32px 12px"><tr><td align="center">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width:620px;background:#fff;border:1px solid #e4e8ee;border-radius:16px;overflow:hidden">
<tr><td style="padding:30px 34px;background:#111827;color:#fff"><div style="font-size:24px;font-weight:700">SonarDesk</div><div style="margin-top:5px;color:#cbd5e1">Your licence is ready</div></td></tr>
<tr><td style="padding:34px">
<p style="margin:0 0 18px">{{ $customerName ? 'Hello '.$customerName.',' : 'Hello,' }}</p>
<p style="margin:0 0 22px;line-height:1.6">Thank you for choosing SonarDesk. Your {{ $edition }} licence key is:</p>
<div style="padding:18px;border:1px solid #d7dde5;border-radius:10px;background:#f8fafc;text-align:center;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:21px;font-weight:700;letter-spacing:1px">{{ $licenseKey }}</div>
<p style="margin:24px 0 10px;line-height:1.6"><strong>Activate SonarDesk</strong></p>
<ol style="padding-left:22px;line-height:1.8;margin-top:0"><li>Open SonarDesk on your Mac.</li><li>Open <strong>Settings → Licence</strong>.</li><li>Paste the licence key above and select <strong>Activate</strong>.</li></ol>
@if($expiresAt)<p style="line-height:1.6">Current entitlement period: <strong>{{ $expiresAt->format('j M Y') }}</strong>.</p>@endif
@if($portalUrl)<p style="margin:24px 0"><a href="{{ $portalUrl }}" style="display:inline-block;background:#2563eb;color:#fff;text-decoration:none;padding:12px 18px;border-radius:8px;font-weight:600">Manage your licence</a></p>@endif
<p style="margin:22px 0 0;color:#64748b;font-size:13px;line-height:1.6">Keep this key private. If you did not make this purchase, contact SonarDesk support.</p>
</td></tr></table>
</td></tr></table>
</body></html>
@@ -0,0 +1,15 @@
@extends('layouts.app', ['title' => 'Features — SonarDesk', 'description' => 'Explore SonarDesk features for monitoring SonarQube projects, quality gates, issues and measures from macOS.'])
@section('content')
<section class="hero-card marketing-hero compact-hero"><span class="eyebrow">Features</span><h1>A focused desktop companion for SonarQube.</h1><p class="lead">Built around the checks developers make every day: project status, quality gates, issues, security findings and measures.</p><div class="support-actions marketing-actions"><a class="btn btn-primary" href="{{ route('buy') }}">Start free trial</a><a class="btn btn-secondary" href="{{ route('release') }}">Read the release notes</a></div></section>
<div class="feature-detail-grid">
<article class="feature-detail"><span>Projects</span><h2>Project dashboard</h2><p>Keep configured SonarQube projects together and scan project health without opening a collection of browser tabs.</p></article>
<article class="feature-detail"><span>Quality</span><h2>Quality gates and measures</h2><p>Surface the status and metrics that tell you whether a project needs attention, in a layout designed for quick review.</p></article>
<article class="feature-detail"><span>Issues</span><h2>Bugs, vulnerabilities and code smells</h2><p>Browse the major SonarQube issue categories, filter the list and open an issue to inspect its details and context.</p></article>
<article class="feature-detail"><span>Scale</span><h2>Server-side pagination</h2><p>Issue browsing is designed to remain practical on projects with larger result sets by paging data from the server.</p></article>
<article class="feature-detail"><span>Connections</span><h2>Multiple SonarQube servers</h2><p>Configure the environments you work with and keep them available from the same SonarDesk workspace.</p></article>
<article class="feature-detail"><span>Security</span><h2>macOS Keychain</h2><p>SonarQube tokens are stored using macOS Keychain rather than being treated as ordinary application preferences.</p></article>
<article class="feature-detail"><span>Licensing</span><h2>Email delivery and self-service portal</h2><p>After checkout, the licence key is emailed to the customer. The SonarDesk portal can resend the key and manage licence information and Mac activations.</p></article>
<article class="feature-detail"><span>Distribution</span><h2>Built for direct Mac distribution</h2><p>SonarDesk is distributed directly for macOS, giving the product a focused release and support channel outside the Mac App Store.</p></article>
</div>
<section class="cta-panel"><div><span class="eyebrow">7-day free trial</span><h2>Try the complete app.</h2><p>Choose Personal for one active Mac or Professional for up to three.</p></div><a class="btn btn-primary" href="{{ route('buy') }}">View pricing</a></section>
@endsection
@@ -96,6 +96,7 @@
.danger-outline{background:#fff;color:var(--red);border:1px solid #f3b7b2}.danger-outline:hover{background:var(--red-soft)}
.full-width{width:100%}
.marketing-hero{padding:72px 0 46px}.marketing-hero h1{max-width:900px;font-size:64px;line-height:1.01;margin:12px 0 20px}.marketing-hero .lead{font-size:20px;max-width:820px}.compact-hero{padding-bottom:36px}.compact-hero h1{font-size:52px}.marketing-actions{margin-top:28px}.microcopy{font-size:13px;color:var(--muted);margin-top:14px}.trust-strip{display:grid;grid-template-columns:repeat(4,1fr);gap:1px;background:var(--line);border:1px solid var(--line);border-radius:14px;overflow:hidden;margin:0 0 68px}.trust-strip span{background:var(--surface);padding:18px;text-align:center;font-size:13px;font-weight:750;color:#475467}.section-block{padding:24px 0 64px}.section-heading{max-width:760px;margin-bottom:28px}.section-heading h2,.split-panel h2,.cta-panel h2{font-size:38px;line-height:1.12;letter-spacing:-.03em;margin:8px 0 12px}.section-heading p{font-size:17px;color:#667085}.feature-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px}.feature-card{background:var(--surface);border:1px solid var(--line);border-radius:16px;padding:24px;box-shadow:var(--shadow-sm)}.feature-card h3{font-size:19px;margin:18px 0 8px}.feature-card p{color:#667085;margin:0}.feature-icon{display:inline-flex;width:38px;height:38px;align-items:center;justify-content:center;border-radius:10px;background:var(--blue-soft);color:var(--blue-dark);font-size:12px;font-weight:900}.split-panel{display:grid;grid-template-columns:1.2fr .8fr;gap:44px;align-items:center;background:#0f172a;color:#fff;border-radius:22px;padding:42px;margin-bottom:64px}.split-panel .lead{color:#cbd5e1}.check-panel{display:grid;gap:10px}.check-panel div{padding:13px 14px;border:1px solid rgba(255,255,255,.12);background:rgba(255,255,255,.05);border-radius:10px;font-weight:650}.check-panel div:before{content:'✓';margin-right:10px;color:#86efac}.pricing-preview-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.marketing-price{font-size:38px;font-weight:900;letter-spacing:-.035em;margin-top:14px}.marketing-price small{font-size:15px;font-weight:650;color:var(--muted);letter-spacing:0}.center-action{text-align:center;margin-top:24px}.cta-panel{display:flex;align-items:center;justify-content:space-between;gap:30px;background:var(--surface);border:1px solid var(--line);border-radius:20px;padding:34px 38px;box-shadow:var(--shadow-md);margin:12px 0 20px}.cta-panel h2{margin-bottom:6px}.cta-panel p{margin:0;color:#667085}.feature-detail-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px;margin:10px 0 64px}.feature-detail{background:var(--surface);border:1px solid var(--line);border-radius:16px;padding:28px}.feature-detail>span{color:var(--blue);font-size:11px;font-weight:850;text-transform:uppercase;letter-spacing:.12em}.feature-detail h2{font-size:24px;margin:8px 0}.feature-detail p{color:#667085;margin:0}.release-body{display:grid;grid-template-columns:minmax(0,1fr) 310px;gap:42px;margin:10px 0 64px}.release-main{background:var(--surface);border:1px solid var(--line);border-radius:18px;padding:36px}.release-main h2{font-size:28px;margin:32px 0 10px}.release-main p,.release-list{color:#475467;font-size:16px;line-height:1.75}.release-list{padding-left:22px}.release-aside{align-self:start;position:sticky;top:92px}
.pricing-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px;margin:20px 0 28px}
.price-card,.card,.panel{background:var(--surface);border:1px solid var(--line);border-radius:16px;padding:24px;box-shadow:var(--shadow-sm)}
.price-card{display:flex;flex-direction:column;justify-content:space-between;gap:24px}.price-card.featured{border-color:#9dbcf7}
@@ -140,11 +141,15 @@
@media(max-width:980px){
.hero-grid{grid-template-columns:1fr;gap:48px}.app-window{max-width:720px;transform:none}.feature-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.workflow-grid{grid-template-columns:repeat(2,1fr)}.security-panel{grid-template-columns:1fr;gap:28px}.nav-email{display:none}
}
@media(max-width:900px){.feature-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.trust-strip{grid-template-columns:repeat(2,1fr)}.release-body{grid-template-columns:1fr}.release-aside{position:static}.marketing-hero h1{font-size:50px}}
@media(max-width:760px){
.site-header{position:relative}.nav-shell{padding:10px 16px;min-height:64px;gap:12px;flex-wrap:wrap}.brand{margin-right:auto}.nav-links{order:3;width:100%;gap:18px;overflow-x:auto;padding:2px 0 4px}.nav-links::-webkit-scrollbar{display:none}.nav-account{margin-left:0}.nav-account .nav-auth-link{display:none}.wrap{padding:28px 16px 48px}.pricing-grid,.plan-grid{grid-template-columns:1fr}.hero-card h1,.portal-header h1{font-size:32px}.portal-header,.licence-detail-head,.licence-title-row,.upgrade-strip,.subscription-warning{align-items:stretch;flex-direction:column}.portal-header .btn,.licence-title-row .btn{width:100%}.licence-stats{grid-template-columns:1fr}.detail-grid{grid-template-columns:1fr}.history-row{grid-template-columns:1fr auto}.history-row a{grid-column:1/-1}.device-row{grid-template-columns:38px 1fr}.device-row form{grid-column:1/-1}.device-row form button{width:100%}
.launch-hero{padding:58px 18px 88px;background:linear-gradient(180deg,#0b1220 0,#101b31 84%,#f7f9fc 84%)}.launch-hero h1{font-size:48px}.hero-copy{font-size:17px}.app-body{grid-template-columns:120px 1fr;min-height:330px}.app-sidebar{padding:12px 8px}.side-item{padding:7px 8px}.app-content{padding:14px}.launch-section{padding:68px 18px}.feature-grid,.workflow-grid{grid-template-columns:1fr}.security-panel{padding:30px 24px;border-radius:20px}.security-panel h2{font-size:32px}.cta-box{padding:36px 26px;align-items:flex-start;flex-direction:column}.cta-box h2{font-size:32px}.footer-shell{align-items:flex-start;flex-direction:column}.launch-cta{padding:16px 18px 72px}
}
@media(max-width:480px){.launch-hero h1{font-size:42px}.hero-actions{flex-direction:column}.hero-actions .btn{width:100%}.app-body{grid-template-columns:1fr}.app-sidebar{display:none}.window-title{display:none}.launch-kicker{font-size:11px}.feature-card{padding:22px}}
@media(max-width:760px){
.site-header{position:static}.nav-shell{min-height:auto;padding:12px 16px;flex-wrap:wrap;gap:10px}.brand{flex:1}.nav-links{order:3;width:100%;overflow-x:auto;display:flex;gap:6px;padding:4px 0 2px;scrollbar-width:none}.nav-links::-webkit-scrollbar{display:none}.nav-links a{white-space:nowrap;padding:8px 10px;border-radius:8px;background:var(--panel)}.nav-account{margin-left:auto}.nav-email{display:none}.wrap{padding-left:16px;padding-right:16px}.hero-card{padding:30px 22px}.marketing-hero h1{font-size:clamp(38px,11vw,52px);line-height:1.02}.marketing-actions{align-items:stretch}.marketing-actions .btn{width:100%;justify-content:center}.pricing-grid,.pricing-preview-grid,.feature-detail-grid,.feature-grid{grid-template-columns:1fr!important}.price-card{min-width:0}.checkout-button{width:100%}.cta-panel{display:grid;grid-template-columns:1fr;gap:20px}.cta-panel .btn{width:100%;justify-content:center}.footer-shell{grid-template-columns:1fr;gap:20px}.footer-links{justify-content:flex-start}.cookie-banner{left:12px;right:12px;bottom:12px}.cookie-actions{display:grid;grid-template-columns:1fr;width:100%}.cookie-actions .btn{width:100%}}
@media(max-width:420px){.nav-account .nav-auth-link{display:none}.nav-cta{padding:9px 11px}.hero-card{padding:26px 18px}.wrap{padding-left:12px;padding-right:12px}.price{font-size:34px}}
@media(prefers-reduced-motion:reduce){html{scroll-behavior:auto}*{transition:none!important}}
@@ -176,7 +181,9 @@
</a>
<div class="nav-links">
<a href="{{ route('home') }}">Product</a>
<a href="{{ route('features') }}">Features</a>
<a href="{{ route('buy') }}">Pricing</a>
<a href="{{ route('release') }}">Release</a>
<a href="{{ route('support') }}">Support</a>
<a href="{{ route('privacy') }}">Privacy</a>
@auth
@@ -232,7 +239,9 @@
</div>
<div class="footer-links">
<a href="{{ route('home') }}">Product</a>
<a href="{{ route('features') }}">Features</a>
<a href="{{ route('buy') }}">Pricing</a>
<a href="{{ route('release') }}">Release</a>
<a href="{{ route('support') }}">Support</a>
<a href="{{ route('privacy') }}">Privacy</a>
<a href="{{ route('terms') }}">Terms</a>
@@ -1,19 +1,48 @@
@extends('layouts.app', [
'title' => 'SonarDesk — SonarQube monitoring for macOS',
'description' => 'A professional native macOS dashboard for SonarQube projects, quality gates, bugs, vulnerabilities and code smells.'
'title' => 'SonarDesk — Native SonarQube monitoring for macOS',
'description' => 'SonarDesk is a native macOS companion for SonarQube: monitor quality gates, issues, measures and project health from one focused desktop workspace.'
])
@section('content')
<section class="hero-card" style="padding:64px 0 38px">
<span class="eyebrow">Native SonarQube monitor for macOS</span>
<h1 style="max-width:850px;font-size:58px">Your SonarQube projects.<br>One focused Mac workspace.</h1>
<p class="lead">SonarDesk gives development teams a fast native view of project health, quality gates, bugs, vulnerabilities, code smells and measures without living in a browser.</p>
<div class="support-actions" style="margin-top:24px"><a class="btn btn-primary" href="{{ route('buy') }}">Start free trial</a><a class="btn btn-secondary" href="{{ route('support') }}">Contact support</a></div>
<section class="hero-card marketing-hero">
<span class="eyebrow">SonarQube, without the browser tab sprawl</span>
<h1>Your code quality.<br>At home on the Mac.</h1>
<p class="lead">SonarDesk is a focused native macOS companion for developers and teams using SonarQube. See project health, quality gates, bugs, vulnerabilities, code smells and measures in one fast desktop workspace.</p>
<div class="support-actions marketing-actions">
<a class="btn btn-primary" href="{{ route('buy') }}">Start 7-day free trial</a>
<a class="btn btn-secondary" href="{{ route('features') }}">Explore features</a>
</div>
<p class="microcopy">Direct download for macOS · Secure licence activation · Cancel anytime</p>
</section>
<div class="grid" style="grid-template-columns:repeat(3,minmax(0,1fr));margin:22px 0 44px">
<div class="card"><span class="eyebrow">Projects</span><h2>Everything at a glance</h2><p>Review quality gates and core measures across every configured SonarQube project.</p></div>
<div class="card"><span class="eyebrow">Issues</span><h2>Find what needs work</h2><p>Browse bugs, vulnerabilities and code smells with filtering and server-side pagination.</p></div>
<div class="card"><span class="eyebrow">Security</span><h2>Credentials stay protected</h2><p>SonarQube tokens are stored in the macOS Keychain and API access respects your server permissions.</p></div>
</div>
<section class="panel" style="padding:34px"><div class="portal-header"><div><span class="eyebrow">Built for engineering teams</span><h2 style="font-size:34px;margin:7px 0">A professional desktop companion for SonarQube.</h2><p class="lead compact">Multiple servers, project dashboards, quality gates, issue views, secure token storage and a native macOS experience.</p></div></div></section>
<section style="padding:54px 0 10px"><div class="portal-header"><div><span class="eyebrow">Licensing</span><h2 style="font-size:34px;margin:7px 0">Simple licensing for SonarDesk.</h2><p class="lead compact">Start with a free trial, then manage your licence, activations and subscription from the customer portal.</p></div><a class="btn" href="{{ route('buy') }}">View pricing</a></div></section>
<section class="trust-strip" aria-label="SonarDesk highlights">
<span>Native macOS app</span><span>Multiple SonarQube servers</span><span>Keychain token storage</span><span>Issue detail workflow</span>
</section>
<section class="section-block">
<div class="section-heading"><span class="eyebrow">Built for daily engineering work</span><h2>See the signal. Open the issue. Get back to code.</h2><p>SonarDesk keeps the information you check most often close at hand, without replacing SonarQube or changing your existing workflow.</p></div>
<div class="feature-grid">
<article class="feature-card"><div class="feature-icon">01</div><h3>Project health at a glance</h3><p>Review configured projects, quality gate state and important measures from a clean Mac dashboard.</p></article>
<article class="feature-card"><div class="feature-icon">02</div><h3>Issue details that are useful</h3><p>Open bugs, vulnerabilities and code smells to see the context you need before switching back to the codebase.</p></article>
<article class="feature-card"><div class="feature-icon">03</div><h3>Focused filtering</h3><p>Work through issue lists with practical filters and server-side pagination rather than fighting a giant browser view.</p></article>
<article class="feature-card"><div class="feature-icon">04</div><h3>Multiple servers</h3><p>Keep the SonarQube environments you work with available from one desktop application.</p></article>
<article class="feature-card"><div class="feature-icon">05</div><h3>macOS security</h3><p>SonarQube access tokens are stored in the macOS Keychain. SonarDesk respects the permissions of the token you provide.</p></article>
<article class="feature-card"><div class="feature-icon">06</div><h3>Native workflow</h3><p>A purpose-built macOS interface with familiar navigation, desktop behaviour and a focused experience for engineering teams.</p></article>
</div>
</section>
<section class="section-block split-panel">
<div><span class="eyebrow">Designed to complement SonarQube</span><h2>Keep SonarQube as the source of truth.</h2><p class="lead compact">SonarDesk is a desktop companion, not a replacement. It connects to your SonarQube server using your credentials and presents the project and issue information you need for everyday monitoring.</p></div>
<div class="check-panel"><div>Quality gates and measures</div><div>Bugs, vulnerabilities and code smells</div><div>Project and issue navigation</div><div>Secure token storage in Keychain</div><div>Customer portal for licences and activations</div></div>
</section>
<section class="section-block pricing-preview">
<div class="section-heading"><span class="eyebrow">Straightforward pricing</span><h2>Start small. Upgrade when you need more Macs.</h2><p>Every plan includes the full SonarDesk application. Professional increases the activation allowance for people working across multiple Macs.</p></div>
<div class="pricing-preview-grid">
<article class="price-card"><span class="eyebrow">Personal</span><h3>For one Mac</h3><div class="marketing-price">£24.99 <small>/ year</small></div><p>or £2.99 monthly</p><ul class="features"><li>Full SonarDesk feature set</li><li>1 active Mac</li><li>7-day free trial</li><li>Licence key delivered by email</li><li>Customer licence portal</li></ul></article>
<article class="price-card featured"><span class="pill">Most popular</span><span class="eyebrow">Professional</span><h3>For a multi-Mac workflow</h3><div class="marketing-price">£44.99 <small>/ year</small></div><p>or £4.99 monthly</p><ul class="features"><li>Full SonarDesk feature set</li><li>Up to 3 active Macs</li><li>7-day free trial</li><li>Licence key delivered by email</li><li>Customer licence portal</li></ul></article>
</div>
<div class="center-action"><a class="btn btn-primary" href="{{ route('buy') }}">See pricing and start trial</a></div>
</section>
<section class="cta-panel"><div><span class="eyebrow">SonarDesk for macOS</span><h2>Make SonarQube easier to keep an eye on.</h2><p>Try SonarDesk for seven days and connect it to your existing SonarQube environment.</p></div><a class="btn btn-primary" href="{{ route('buy') }}">Start free trial</a></section>
@endsection
@@ -0,0 +1,16 @@
@extends('layouts.app', ['title' => 'SonarDesk 1.0 — Release', 'description' => 'SonarDesk 1.0 for macOS: a native desktop companion for SonarQube project health, quality gates and issues.'])
@section('content')
<section class="hero-card marketing-hero compact-hero"><span class="eyebrow">Introducing SonarDesk 1.0</span><h1>SonarQube monitoring, built for the Mac.</h1><p class="lead">SonarDesk brings project health, quality gates, bugs, vulnerabilities, code smells and measures into a dedicated native macOS workspace.</p><div class="support-actions marketing-actions"><a class="btn btn-primary" href="{{ route('buy') }}">Start free trial</a><a class="btn btn-secondary" href="{{ route('features') }}">Explore features</a></div></section>
<section class="release-body">
<div class="release-main">
<span class="eyebrow">Version 1.0</span><h2>Why SonarDesk</h2>
<p>SonarQube is an essential part of many development workflows, but checking it throughout the day often means returning to another browser tab, navigating back to a project and rebuilding context. SonarDesk is designed to make that recurring check faster and more focused on macOS.</p>
<p>It does not replace SonarQube. Your SonarQube server remains the source of truth. SonarDesk gives you a dedicated desktop view of the information you monitor most often.</p>
<h2>What is included</h2>
<ul class="release-list"><li>Project dashboards and project health views</li><li>Quality gate status and important measures</li><li>Issue browsing for bugs, vulnerabilities and code smells</li><li>Detailed issue views and practical filtering</li><li>Server-side pagination for larger issue sets</li><li>Support for multiple SonarQube server configurations</li><li>SonarQube token storage using macOS Keychain</li><li>Direct licensing with a self-service customer portal</li></ul>
<h2>Who it is for</h2><p>SonarDesk is for developers, technical leads and engineering teams who already use SonarQube and want a faster, dedicated way to keep project quality visible while working on a Mac.</p>
<h2>Launch pricing</h2><p>Personal is £24.99/year or £2.99/month for one active Mac. Professional is £44.99/year or £4.99/month for up to three active Macs. Both include a 7-day free trial and the complete SonarDesk feature set.</p>
</div>
<aside class="release-aside"><div class="card"><span class="eyebrow">At a glance</span><h3>SonarDesk 1.0</h3><p>Native macOS application</p><p>Direct distribution</p><p>7-day free trial</p><p>Personal + Professional plans</p><a class="btn btn-primary full-width" href="{{ route('buy') }}">Try SonarDesk</a></div></aside>
</section>
@endsection
+4
View File
@@ -4,3 +4,7 @@ use Illuminate\Support\Facades\Schedule;
// Removes resolved support requests after the configured retention period.
Schedule::command('model:prune')->dailyAt('03:20')->withoutOverlapping();
Schedule::call(function (): void {
app(\App\Services\Licensing\LicenseDeliveryService::class)->deliverPending(50);
})->name('license-delivery')->everyMinute()->withoutOverlapping();
+2
View File
@@ -16,6 +16,8 @@ use Illuminate\Support\Facades\Route;
Route::get('/', fn () => view('portal.welcome'))->name('home');
Route::get('/buy', CheckoutController::class)->name('buy');
Route::view('/features', 'features')->name('features');
Route::view('/release', 'release')->name('release');
Route::get('/support', [SupportController::class, 'create'])->name('support');
Route::post('/support', [SupportController::class, 'store'])->middleware('throttle:5,10')->name('support.store');
Route::view('/privacy', 'legal.privacy')->name('privacy');
@@ -134,10 +134,10 @@ PERSONAL_MONTHLY=$(create_price \
"Personal Monthly" \
"SonarDesk Personal — monthly subscription with 7-day free trial." \
"month" \
"199" \
"199" \
"199" \
"299")
"299" \
"299" \
"349" \
"499")
PERSONAL_MONTHLY_ID=$(echo "$PERSONAL_MONTHLY" | jq -r '.data.id')
@@ -148,10 +148,10 @@ PERSONAL_ANNUAL=$(create_price \
"Personal Annual" \
"SonarDesk Personal — annual subscription with 7-day free trial." \
"year" \
"1499" \
"1499" \
"1699" \
"2499")
"2499" \
"2499" \
"2899" \
"4199")
PERSONAL_ANNUAL_ID=$(echo "$PERSONAL_ANNUAL" | jq -r '.data.id')
@@ -174,10 +174,10 @@ PRO_MONTHLY=$(create_price \
"Professional Monthly" \
"SonarDesk Professional — monthly subscription with 7-day free trial." \
"month" \
"399" \
"399" \
"449" \
"699")
"499" \
"499" \
"599" \
"849")
PRO_MONTHLY_ID=$(echo "$PRO_MONTHLY" | jq -r '.data.id')
@@ -188,10 +188,10 @@ PRO_ANNUAL=$(create_price \
"Professional Annual" \
"SonarDesk Professional — annual subscription with 7-day free trial." \
"year" \
"2999" \
"2999" \
"3499" \
"4999")
"4499" \
"4499" \
"5199" \
"7499")
PRO_ANNUAL_ID=$(echo "$PRO_ANNUAL" | jq -r '.data.id')
@@ -219,13 +219,13 @@ echo
printf "%-24s %-12s %-12s %-12s %-12s\n" \
"Plan" "USD" "UK" "Ireland" "Australia"
printf "%-24s %-12s %-12s %-12s %-12s\n" \
"Personal Monthly" '$1.99' '£1.99' '€1.99' 'A$2.99'
"Personal Monthly" '$2.99' '£2.99' '€3.49' 'A$4.99'
printf "%-24s %-12s %-12s %-12s %-12s\n" \
"Personal Annual" '$14.99' '£14.99' '€16.99' 'A$24.99'
"Personal Annual" '$24.99' '£24.99' '€28.99' 'A$41.99'
printf "%-24s %-12s %-12s %-12s %-12s\n" \
"Professional Monthly" '$3.99' '£3.99' '€4.49' 'A$6.99'
"Professional Monthly" '$4.99' '£4.99' '€5.99' 'A$8.49'
printf "%-24s %-12s %-12s %-12s %-12s\n" \
"Professional Annual" '$29.99' '£29.99' '€34.99' 'A$49.99'
"Professional Annual" '$44.99' '£44.99' '€51.99' 'A$74.99'
echo
echo "All four prices include a 7-day FREE trial."
echo
+296
View File
@@ -0,0 +1,296 @@
# pdl_sdbx_apikey_01m3pv5nbpjq94nh2hzqwhzbv5_TW7kG6xyGMcbxFAnEAtKqc_ALK
#client side
# pdl_sdbx_apikey_01m3pveweeskjzz1rc8f12a7x3_G9qWxtDBxGZJWa3f7VGKz6_A15
#!/usr/bin/env bash
set -euo pipefail
PADDLE_API="https://sandbox-api.paddle.com"
PRODUCT_ID="pro_01m3ptwmqy8npywsq4h4q27p0w"
OUTPUT_FILE=".env.paddle"
echo "============================================================"
echo " SonarDesk Paddle SANDBOX Price Setup"
echo "============================================================"
echo
echo "Product: $PRODUCT_ID"
echo
command -v curl >/dev/null || {
echo "ERROR: curl is required"
exit 1
}
command -v jq >/dev/null || {
echo "ERROR: jq is required"
echo "Install with: brew install jq"
exit 1
}
read -rsp "Enter Paddle SANDBOX API key: " PADDLE_API_KEY
echo
echo
if [[ -z "$PADDLE_API_KEY" ]]; then
echo "ERROR: No API key supplied."
exit 1
fi
# ------------------------------------------------------------
# API request helper
# ------------------------------------------------------------
api_request() {
local method="$1"
local endpoint="$2"
local data="${3:-}"
local tmp
tmp="$(mktemp)"
if [[ "$method" == "GET" ]]; then
HTTP_CODE=$(curl -sS \
-o "$tmp" \
-w "%{http_code}" \
-H "Authorization: Bearer ${PADDLE_API_KEY}" \
-H "Content-Type: application/json" \
"${PADDLE_API}${endpoint}")
else
HTTP_CODE=$(curl -sS \
-o "$tmp" \
-w "%{http_code}" \
-X "$method" \
-H "Authorization: Bearer ${PADDLE_API_KEY}" \
-H "Content-Type: application/json" \
-d "$data" \
"${PADDLE_API}${endpoint}")
fi
RESPONSE="$(cat "$tmp")"
rm -f "$tmp"
}
# ------------------------------------------------------------
# Verify API key
# ------------------------------------------------------------
echo "1. Testing Paddle API key..."
api_request GET "/event-types"
if [[ "$HTTP_CODE" != "200" ]]; then
echo
echo "ERROR: Paddle rejected the API key."
echo "HTTP: $HTTP_CODE"
echo
echo "$RESPONSE" | jq . 2>/dev/null || echo "$RESPONSE"
exit 1
fi
echo " ✓ API key works"
echo
# ------------------------------------------------------------
# Verify product
# ------------------------------------------------------------
echo "2. Checking SonarDesk product..."
api_request GET "/products/${PRODUCT_ID}"
if [[ "$HTTP_CODE" != "200" ]]; then
echo
echo "ERROR: Cannot access SonarDesk product."
echo "HTTP: $HTTP_CODE"
echo
echo "$RESPONSE" | jq . 2>/dev/null || echo "$RESPONSE"
exit 1
fi
PRODUCT_NAME="$(echo "$RESPONSE" | jq -r '.data.name')"
echo " ✓ Product found: $PRODUCT_NAME"
echo " ✓ $PRODUCT_ID"
echo
# ------------------------------------------------------------
# Create price
# ------------------------------------------------------------
create_price() {
local variable="$1"
local name="$2"
local description="$3"
local amount="$4"
local interval="$5"
local display="$6"
echo "Creating: $name"
echo " $display"
PAYLOAD=$(jq -n \
--arg product "$PRODUCT_ID" \
--arg name "$name" \
--arg description "$description" \
--arg amount "$amount" \
--arg interval "$interval" \
'{
product_id: $product,
name: $name,
description: $description,
unit_price: {
amount: $amount,
currency_code: "GBP"
},
billing_cycle: {
interval: $interval,
frequency: 1
},
trial_period: {
interval: "day",
frequency: 7,
requires_payment_method: true
},
tax_mode: "account_setting",
quantity: {
minimum: 1,
maximum: 1
}
}')
echo
echo "Request:"
echo "$PAYLOAD" | jq .
echo
api_request POST "/prices" "$PAYLOAD"
if [[ "$HTTP_CODE" != "201" ]]; then
echo "============================================================"
echo " ERROR CREATING PRICE"
echo "============================================================"
echo
echo "Price: $name"
echo "HTTP: $HTTP_CODE"
echo
echo "Paddle response:"
echo
echo "$RESPONSE" | jq . 2>/dev/null || echo "$RESPONSE"
echo
exit 1
fi
PRICE_ID="$(echo "$RESPONSE" | jq -r '.data.id')"
if [[ -z "$PRICE_ID" || "$PRICE_ID" == "null" ]]; then
echo "ERROR: Paddle returned no price ID."
echo "$RESPONSE" | jq .
exit 1
fi
printf -v "$variable" '%s' "$PRICE_ID"
echo " ✓ CREATED"
echo " ✓ $PRICE_ID"
echo
}
# ------------------------------------------------------------
# Create SonarDesk prices
# ------------------------------------------------------------
echo "============================================================"
echo " Creating SonarDesk Prices"
echo "============================================================"
echo
create_price \
PERSONAL_MONTHLY \
"Personal Monthly" \
"SonarDesk Personal - Monthly subscription" \
"299" \
"month" \
"£2.99/month"
create_price \
PERSONAL_ANNUAL \
"Personal Annual" \
"SonarDesk Personal - Annual subscription" \
"2499" \
"year" \
"£24.99/year"
create_price \
PROFESSIONAL_MONTHLY \
"Professional Monthly" \
"SonarDesk Professional - Monthly subscription" \
"499" \
"month" \
"£4.99/month"
create_price \
PROFESSIONAL_ANNUAL \
"Professional Annual" \
"SonarDesk Professional - Annual subscription" \
"4499" \
"year" \
"£44.99/year"
# ------------------------------------------------------------
# Generate Laravel configuration
# ------------------------------------------------------------
cat > "$OUTPUT_FILE" <<EOF
# ============================================================
# SonarDesk Paddle SANDBOX
# ============================================================
PADDLE_ENV=sandbox
PADDLE_PRODUCT_ID=${PRODUCT_ID}
PADDLE_PERSONAL_MONTHLY_PRICE_ID=${PERSONAL_MONTHLY}
PADDLE_PERSONAL_YEARLY_PRICE_ID=${PERSONAL_ANNUAL}
PADDLE_PROFESSIONAL_MONTHLY_PRICE_ID=${PROFESSIONAL_MONTHLY}
PADDLE_PROFESSIONAL_YEARLY_PRICE_ID=${PROFESSIONAL_ANNUAL}
EOF
echo
echo "============================================================"
echo " SUCCESS"
echo "============================================================"
echo
echo "SonarDesk Paddle prices:"
echo
echo "Personal Monthly"
echo " £2.99/month"
echo " $PERSONAL_MONTHLY"
echo
echo "Personal Annual"
echo " £24.99/year"
echo " $PERSONAL_ANNUAL"
echo
echo "Professional Monthly"
echo " £4.99/month"
echo " $PROFESSIONAL_MONTHLY"
echo
echo "Professional Annual"
echo " £44.99/year"
echo " $PROFESSIONAL_ANNUAL"
echo
echo "Configuration:"
echo " $OUTPUT_FILE"
echo
echo "Now check:"
echo " Paddle Sandbox -> Catalog -> Products -> SonarDesk"
echo
+4
View File
@@ -0,0 +1,4 @@
cloudflared tunnel \
--url https://sonardesk.vm \
--no-tls-verify \
--http-host-header sonardesk.vm
@@ -1,2 +0,0 @@
*
!.gitignore
@@ -4,6 +4,7 @@ namespace Tests\Feature;
use App\Models\License;
use App\Models\LicenseProduct;
use App\Models\User;
use App\Services\Payments\PurchaseProvisioner;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
@@ -102,4 +103,30 @@ class PaddleSubscriptionProvisioningTest extends TestCase
$this->assertNotNull($license->revoked_at);
$this->assertFalse($license->is_usable);
}
public function test_new_purchase_creates_a_portal_user_for_the_customer(): void
{
$this->product('pri_personal_monthly', 'Personal', 1);
app(PurchaseProvisioner::class)->provision('paddle', $this->subscription(
'subscription.created', 'active', 'pri_personal_monthly', 'pro_personal'
));
$user = User::where('email', 'mark@example.com')->firstOrFail();
$this->assertSame('Mark', $user->name);
$this->assertNotNull($user->email_verified_at);
}
public function test_existing_customer_account_is_reused(): void
{
User::factory()->create(['name' => 'Existing Mark', 'email' => 'mark@example.com']);
$this->product('pri_personal_monthly', 'Personal', 1);
app(PurchaseProvisioner::class)->provision('paddle', $this->subscription(
'subscription.created', 'active', 'pri_personal_monthly', 'pro_personal'
));
$this->assertSame(1, User::where('email', 'mark@example.com')->count());
$this->assertSame('Existing Mark', User::where('email', 'mark@example.com')->firstOrFail()->name);
}
}