Files
ladill-woo-manager/app/Http/Controllers/Api/StoreActivationController.php
T
isaaccladandCursor e3ef23218f
Deploy Ladill Woo Manager / deploy (push) Successful in 39s
Fix Woo sync: exempt webhooks from CSRF and backfill on connect.
Auto-import catalog and orders after store activation, add manual order sync, and allow WooCommerce webhooks without CSRF tokens.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-07 00:15:37 +00:00

84 lines
2.6 KiB
PHP

<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Jobs\StoreBootstrapSync;
use App\Models\WooStore;
use App\Services\Woo\InstallTokenService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use RuntimeException;
class StoreActivationController extends Controller
{
public function __construct(private InstallTokenService $tokens) {}
public function activate(Request $request): JsonResponse
{
$validated = $request->validate([
'install_token' => ['required', 'string'],
'site_url' => ['required', 'url', 'max:500'],
]);
try {
$store = $this->tokens->consume($validated['install_token']);
} catch (RuntimeException $e) {
return response()->json(['message' => $e->getMessage()], 422);
}
$parsed = parse_url($validated['site_url']);
$scheme = $parsed['scheme'] ?? 'https';
$host = strtolower((string) ($parsed['host'] ?? ''));
$siteUrl = rtrim($scheme.'://'.$host, '/');
if ($store->site_url !== $siteUrl) {
return response()->json(['message' => 'Site URL does not match the connection request.'], 422);
}
$pluginToken = $this->tokens->issuePluginToken($store);
$store = $store->fresh();
StoreBootstrapSync::dispatch($store->id)->afterResponse();
return response()->json([
'store_id' => $store->public_id,
'webhook_url' => $store->webhookUrl(),
'webhook_secret' => $store->webhook_secret,
'plugin_token' => $pluginToken,
'webhook_topics' => config('woo.webhook_topics'),
]);
}
public function show(Request $request): JsonResponse
{
$store = $this->storeFromRequest($request);
if (! $store) {
return response()->json(['message' => 'Unauthorized.'], 401);
}
return response()->json([
'store_id' => $store->public_id,
'site_url' => $store->site_url,
'site_name' => $store->site_name,
'status' => $store->status,
'webhook_url' => $store->webhookUrl(),
]);
}
private function storeFromRequest(Request $request): ?WooStore
{
$storeId = (string) $request->header('X-Ladill-Store', '');
$token = (string) $request->bearerToken();
if ($storeId === '' || $token === '') {
return null;
}
$store = WooStore::query()->where('public_id', $storeId)->first();
if (! $store || ! $this->tokens->verifyPluginToken($store, $token)) {
return null;
}
return $store;
}
}