"""Python 3.10+, standard library. One fresh-consent request; no email is sent. First POST /subscriptions/lookup from your server. Save the latest opted-out ID, actual NEW consent evidence, timestamp, unchanged request and idempotency key with your consent event BEFORE running this example. These values must remain unchanged on retry. This program never manufactures consent evidence. Keep API keys server-side. A replay can return opted_out: it does not undo a later withdrawal. Never automatically retry a conflict with a new event/key. """ import json import os import re import sys import urllib.error import urllib.request class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None # Never forward a Bearer key to a redirect destination. def saved_request(environment): api_key = environment.get("MAILCORE_MARKETING_API_KEY", "") subscription_id = environment.get("MAILCORE_SUBSCRIPTION_ID", "") event_key = environment.get("MAILCORE_IDEMPOTENCY_KEY", "") if not api_key or any(char in api_key for char in "\r\n"): raise ValueError("Set MAILCORE_MARKETING_API_KEY on your server") if not re.fullmatch(r"sub_[a-f0-9]{24}", subscription_id): raise ValueError("Set MAILCORE_SUBSCRIPTION_ID to the saved latest opted-out ID") if not re.fullmatch(r"[A-Za-z0-9._:-]{16,128}", event_key): raise ValueError("Set MAILCORE_IDEMPOTENCY_KEY saved with this new consent event") payload = { "recipient": environment.get("MAILCORE_RECIPIENT", ""), "topic": environment.get("MAILCORE_TOPIC", ""), "consentSource": environment.get("MAILCORE_CONSENT_SOURCE", ""), "consentReference": environment.get("MAILCORE_CONSENT_REFERENCE", ""), "consentedAt": environment.get("MAILCORE_CONSENTED_AT", ""), } if not all(payload.values()): raise ValueError("Set all recipient/topic and actual saved consent-event values") if payload["consentSource"] not in {"signup", "checkout", "preferences"}: raise ValueError("Fresh consent source must be signup, checkout or preferences") if not 8 <= len(payload["consentReference"]) <= 256: raise ValueError("Use the saved 8–256 character reference for actual fresh consent") return urllib.request.Request( "https://mailcore.uz/api/email/v1/streams/marketing/subscriptions/" + subscription_id + "/resubscribe", data=json.dumps(payload, ensure_ascii=False).encode("utf-8"), headers={"Authorization": "Bearer " + api_key, "Idempotency-Key": event_key, "Content-Type": "application/json"}, method="POST", ) def main(): try: request = saved_request(os.environ) except ValueError as error: raise SystemExit(str(error)) try: with urllib.request.build_opener(NoRedirect()).open(request, timeout=30) as response: result = json.loads(response.read(1_048_577)) if response.status != 201 or result.get("status") not in {"opted_in", "opted_out"}: raise ValueError("Unexpected response") # Save result.id/status/generation on this event. On replay, CURRENT # opted_out is final: do not automatically make another opt-in. print(json.dumps(result)) except urllib.error.HTTPError as error: try: result = json.loads(error.read(1_048_577)) except (ValueError, OSError): result = {"error": "unexpected_http_response"} print(json.dumps({"httpStatus": error.code, **result}), file=sys.stderr) raise SystemExit(1) except (urllib.error.URLError, TimeoutError, OSError, ValueError): raise SystemExit("No usable result. Retry only the saved original ID, body and event key.") if __name__ == "__main__": main()