getenv('MAILCORE_RECIPIENT') ?: '', 'topic' => getenv('MAILCORE_TOPIC') ?: '', 'consentSource' => getenv('MAILCORE_CONSENT_SOURCE') ?: '', 'consentReference' => getenv('MAILCORE_CONSENT_REFERENCE') ?: '', 'consentedAt' => getenv('MAILCORE_CONSENTED_AT') ?: '', ]; if (in_array('', $payload, true) || !in_array($payload['consentSource'], ['signup','checkout','preferences'], true)) { fwrite(STDERR, "Set all recipient/topic and actual fresh signup/checkout/preferences consent values\n"); exit(1); } $referenceLength = preg_match_all('/./us', $payload['consentReference']); if ($referenceLength === false || $referenceLength < 8 || $referenceLength > 256) { fwrite(STDERR, "Use the saved 8–256 character reference for actual fresh consent\n"); exit(1); } $context = stream_context_create(['http' => [ 'method' => 'POST', 'header' => "Authorization: Bearer {$apiKey}\r\nIdempotency-Key: {$eventKey}\r\nContent-Type: application/json\r\n", 'content' => json_encode($payload, JSON_THROW_ON_ERROR), 'timeout' => 30, 'ignore_errors' => true, 'follow_location' => 0, // Never forward Bearer credentials to a redirect. ], 'ssl' => ['verify_peer' => true, 'verify_peer_name' => true]]); $url = 'https://mailcore.uz/api/email/v1/streams/marketing/subscriptions/' . $subscriptionId . '/resubscribe'; $raw = @file_get_contents($url, false, $context, 0, 1048577); if ($raw === false) { fwrite(STDERR, "No usable result. Retry only the saved original ID, body and event key.\n"); exit(1); } $status = 0; foreach ($http_response_header ?? [] as $header) { if (preg_match('/^HTTP\/\S+ (\d{3})/', $header, $match)) $status = (int) $match[1]; } try { $result = json_decode($raw, true, 512, JSON_THROW_ON_ERROR); if (!is_array($result)) throw new RuntimeException('Unexpected response'); if ($status !== 201) { fwrite(STDERR, json_encode(['httpStatus' => $status] + $result, JSON_THROW_ON_ERROR) . "\n"); exit(1); } // Persist result on the SAME event. A replay can return opted_out: never // automatically restore it or manufacture another consent event/key. echo json_encode($result, JSON_THROW_ON_ERROR) . "\n"; } catch (Throwable $error) { fwrite(STDERR, "No usable JSON result. Retry only the saved original ID, body and event key.\n"); exit(1); }