Compare commits

...

3 Commits

Author SHA1 Message Date
dev.daminik00
5bef4efbf1 fix utm unicode 2025-12-24 22:03:08 +03:00
dev.daminik00
7f80767333 utm 2025-12-24 21:42:17 +03:00
dev.daminik00
7469c43b86 remove klav 2025-12-24 03:56:53 +03:00
12 changed files with 253 additions and 35 deletions

View File

@ -3,6 +3,38 @@ import { NextRequest, NextResponse } from "next/server";
import { createPaymentCheckout } from "@/entities/payment/api";
import { ROUTES } from "@/shared/constants/client-routes";
/**
* Convert base64 string to bytes (handles UTF-8 properly)
* MDN recommended approach: https://developer.mozilla.org/en-US/docs/Web/API/Window/btoa#unicode_strings
*/
function base64ToBytes(base64: string): Uint8Array {
const binString = atob(base64);
return Uint8Array.from(binString, (m) => m.codePointAt(0) ?? 0);
}
/**
* Decode URL-safe base64 state parameter to UTM object
* Supports UTF-8 encoded content (e.g., utm_campaign=)
*/
function decodeStateParam(state: string): Record<string, string> | undefined {
if (!state) return undefined;
try {
// Restore URL-safe base64 to standard base64
let base64 = state.replace(/-/g, "+").replace(/_/g, "/");
// Add padding if needed
while (base64.length % 4) {
base64 += "=";
}
// Decode base64 to bytes, then decode UTF-8
const bytes = base64ToBytes(base64);
const json = new TextDecoder().decode(bytes);
return JSON.parse(json);
} catch {
return undefined;
}
}
export async function GET(req: NextRequest) {
const productId = req.nextUrl.searchParams.get("productId");
const placementId = req.nextUrl.searchParams.get("placementId");
@ -10,11 +42,18 @@ export async function GET(req: NextRequest) {
const fbPixels = req.nextUrl.searchParams.get("fb_pixels");
const productPrice = req.nextUrl.searchParams.get("price");
const currency = req.nextUrl.searchParams.get("currency");
const sessionId = req.nextUrl.searchParams.get("sessionId");
const state = req.nextUrl.searchParams.get("state");
// Decode state param to get UTM
const utm = state ? decodeStateParam(state) : undefined;
const data = await createPaymentCheckout({
productId: productId || "",
placementId: placementId || "",
paywallId: paywallId || "",
sessionId: sessionId || undefined,
utm,
});
let redirectUrl: URL = new URL(data?.paymentUrl || "", req.nextUrl.origin);

View File

@ -39,6 +39,8 @@ export async function GET(req: NextRequest) {
const productPrice = searchParams.get("price");
const currency = searchParams.get("currency");
const nextUrl = searchParams.get("nextUrl");
const sessionId = searchParams.get("sessionId");
const state = searchParams.get("state");
const redirectUrl = new URL(
`${nextUrl || ROUTES.payment()}`,
@ -51,6 +53,8 @@ export async function GET(req: NextRequest) {
if (fbPixels) redirectUrl.searchParams.set("fb_pixels", fbPixels);
if (productPrice) redirectUrl.searchParams.set("price", productPrice);
if (currency) redirectUrl.searchParams.set("currency", currency);
if (sessionId) redirectUrl.searchParams.set("sessionId", sessionId);
if (state) redirectUrl.searchParams.set("state", state);
const trackingCookies = extractTrackingCookiesFromUrl(req.nextUrl);

View File

@ -7,6 +7,7 @@ import { Button, Typography } from "@/components/ui";
import { BlurComponent } from "@/components/widgets";
import { ROUTES } from "@/shared/constants/client-routes";
import { translatePathEmailMarketingCompatibilityV1 } from "@/shared/constants/translate";
import { getCurrentUtmParams } from "@/shared/utils/url";
import styles from "./LandingButtonWrapper.module.scss";
@ -17,7 +18,8 @@ export default function LandingButtonWrapper() {
);
const handleContinue = () => {
router.push(ROUTES.emailMarketingCompatibilityV1SpecialOffer());
const utmParams = getCurrentUtmParams();
router.push(ROUTES.emailMarketingCompatibilityV1SpecialOffer(utmParams));
};
return (

View File

@ -7,6 +7,10 @@ import { Button, Typography } from "@/components/ui";
import { BlurComponent } from "@/components/widgets";
import { ROUTES } from "@/shared/constants/client-routes";
import { translatePathEmailMarketingCompatibilityV1 } from "@/shared/constants/translate";
import {
getSessionIdFromUrl,
getStateParamForRedirect,
} from "@/shared/utils/url";
import styles from "./SpecialOfferButtonWrapper.module.scss";
@ -27,13 +31,20 @@ export default function SpecialOfferButtonWrapper({
);
const openPaymentModal = () => {
router.push(
ROUTES.payment({
productId,
placementId,
paywallId,
})
);
const state = getStateParamForRedirect();
const sessionId = getSessionIdFromUrl();
const params: Record<string, string> = {
productId,
placementId,
paywallId,
};
if (state) {
params.state = state;
}
if (sessionId) {
params.sessionId = sessionId;
}
router.push(ROUTES.payment(params));
};
return (

View File

@ -7,6 +7,7 @@ import { Button, Typography } from "@/components/ui";
import { BlurComponent } from "@/components/widgets";
import { ROUTES } from "@/shared/constants/client-routes";
import { translatePathEmailMarketingSoulmateV1 } from "@/shared/constants/translate";
import { getCurrentUtmParams } from "@/shared/utils/url";
import styles from "./LandingButtonWrapper.module.scss";
@ -15,7 +16,8 @@ export default function LandingButtonWrapper() {
const t = useTranslations(translatePathEmailMarketingSoulmateV1("Landing"));
const handleContinue = () => {
router.push(ROUTES.emailMarketingSoulmateV1SpecialOffer());
const utmParams = getCurrentUtmParams();
router.push(ROUTES.emailMarketingSoulmateV1SpecialOffer(utmParams));
};
return (

View File

@ -7,6 +7,10 @@ import { Button, Typography } from "@/components/ui";
import { BlurComponent } from "@/components/widgets";
import { ROUTES } from "@/shared/constants/client-routes";
import { translatePathEmailMarketingSoulmateV1 } from "@/shared/constants/translate";
import {
getSessionIdFromUrl,
getStateParamForRedirect,
} from "@/shared/utils/url";
import styles from "./SpecialOfferButtonWrapper.module.scss";
@ -27,13 +31,20 @@ export default function SpecialOfferButtonWrapper({
);
const openPaymentModal = () => {
router.push(
ROUTES.payment({
productId,
placementId,
paywallId,
})
);
const state = getStateParamForRedirect();
const sessionId = getSessionIdFromUrl();
const params: Record<string, string> = {
productId,
placementId,
paywallId,
};
if (state) {
params.state = state;
}
if (sessionId) {
params.sessionId = sessionId;
}
router.push(ROUTES.payment(params));
};
return (

View File

@ -6,6 +6,7 @@ import { useTranslations } from "next-intl";
import { Button, Typography } from "@/components/ui";
import { usePeriod } from "@/hooks/translations/usePeriod";
import { ROUTES } from "@/shared/constants/client-routes";
import { getCurrentUtmParams } from "@/shared/utils/url";
import { PeriodType } from "@/types/period";
import styles from "./Button.module.scss";
@ -24,7 +25,8 @@ export default function SaveOffButton({
const router = useRouter();
const handleNext = () => {
router.push(ROUTES.secretDiscount());
const utmParams = getCurrentUtmParams();
router.push(ROUTES.secretDiscount(utmParams));
};
return (

View File

@ -6,6 +6,10 @@ import { useTranslations } from "next-intl";
import { Button, Typography } from "@/components/ui";
import { usePeriod } from "@/hooks/translations/usePeriod";
import { ROUTES } from "@/shared/constants/client-routes";
import {
getSessionIdFromUrl,
getStateParamForRedirect,
} from "@/shared/utils/url";
import { PeriodType } from "@/types/period";
import styles from "./Button.module.scss";
@ -30,13 +34,20 @@ export default function SecretDiscountButton({
const router = useRouter();
const handleNext = () => {
router.push(
ROUTES.payment({
productId,
placementId,
paywallId,
})
);
const state = getStateParamForRedirect();
const sessionId = getSessionIdFromUrl();
const params: Record<string, string> = {
productId,
placementId,
paywallId,
};
if (state) {
params.state = state;
}
if (sessionId) {
params.sessionId = sessionId;
}
router.push(ROUTES.payment(params));
};
return (

View File

@ -4,6 +4,8 @@ export const CheckoutRequestSchema = z.object({
productId: z.string(),
placementId: z.string(),
paywallId: z.string(),
sessionId: z.string().optional(),
utm: z.record(z.string()).optional(),
});
export type CheckoutRequest = z.infer<typeof CheckoutRequestSchema>;

View File

@ -52,7 +52,7 @@ export const UserSchema = z.object({
signDate: z.string().nullable().optional(),
password: z.string(),
externalId: z.string().optional(),
klaviyoId: z.string().nullable(),
klaviyoId: z.string().nullable().optional(),
assistants: z.array(z.string()),
createdAt: z.string().optional(),
updatedAt: z.string(),

View File

@ -74,8 +74,10 @@ export const ROUTES = {
paymentFailed: () => createRoute(["payment", "failed"]),
// Secret Discount
saveOff: () => createRoute(["save-off"]),
secretDiscount: () => createRoute(["secret-discount"]),
saveOff: (queryParams?: Record<string, string>) =>
createRoute(["save-off"], queryParams),
secretDiscount: (queryParams?: Record<string, string>) =>
createRoute(["secret-discount"], queryParams),
// Chat
chat: (id?: string) => createRoute(["chat", id]),
@ -86,16 +88,16 @@ export const ROUTES = {
additionalPurchases: (type?: string) => createRoute(["ap", type]),
// Email Marketing Compatibility V1
emailMarketingCompatibilityV1Landing: () =>
createRoute([emailMarketingCompatibilityV1Prefix, "landing"]),
emailMarketingCompatibilityV1SpecialOffer: () =>
createRoute([emailMarketingCompatibilityV1Prefix, "special-offer"]),
emailMarketingCompatibilityV1Landing: (queryParams?: Record<string, string>) =>
createRoute([emailMarketingCompatibilityV1Prefix, "landing"], queryParams),
emailMarketingCompatibilityV1SpecialOffer: (queryParams?: Record<string, string>) =>
createRoute([emailMarketingCompatibilityV1Prefix, "special-offer"], queryParams),
// Email Marketing Soulmate V1
emailMarketingSoulmateV1Landing: () =>
createRoute([emailMarketingSoulmateV1Prefix, "landing"]),
emailMarketingSoulmateV1SpecialOffer: () =>
createRoute([emailMarketingSoulmateV1Prefix, "special-offer"]),
emailMarketingSoulmateV1Landing: (queryParams?: Record<string, string>) =>
createRoute([emailMarketingSoulmateV1Prefix, "landing"], queryParams),
emailMarketingSoulmateV1SpecialOffer: (queryParams?: Record<string, string>) =>
createRoute([emailMarketingSoulmateV1Prefix, "special-offer"], queryParams),
// // Compatibility
// compatibilities: () => createRoute(["compatibilities"]),

132
src/shared/utils/url.ts Normal file
View File

@ -0,0 +1,132 @@
// Params that should NOT be included in state (they are passed separately)
const EXCLUDED_STATE_PARAMS = [
"paywallId",
"placementId",
"productId",
"jwtToken",
"price",
"currency",
"fb_pixels",
"sessionId",
"state",
// Tracking cookies (passed separately)
"_fbc",
"_fbp",
"_ym_uid",
"_ym_d",
"_ym_isad",
"_ym_visorc",
"yandexuid",
"ymex",
];
/**
* Parse current query params from URL
*/
export const parseQueryParams = (): Record<string, string> => {
if (typeof window === "undefined") return {};
const params = new URLSearchParams(window.location.search);
const result: Record<string, string> = {};
for (const [key, value] of params.entries()) {
result[key] = value;
}
return result;
};
/**
* Get current query params that should be passed between screens and to payment
* Includes ALL params except internal ones (productId, placementId, etc.)
* Works with utm_*, fbclid, gclid, and any other marketing params
*/
export const getCurrentQueryParams = (): Record<string, string> => {
if (typeof window === "undefined") return {};
const params = parseQueryParams();
const utmParams: Record<string, string> = {};
for (const [key, value] of Object.entries(params)) {
const isExcluded =
EXCLUDED_STATE_PARAMS.includes(key) ||
key.startsWith("_ga") ||
key.startsWith("_gid");
if (!isExcluded && value) {
utmParams[key] = value;
}
}
return utmParams;
};
/**
* Convert bytes to base64 string (handles UTF-8 properly)
* MDN recommended approach: https://developer.mozilla.org/en-US/docs/Web/API/Window/btoa#unicode_strings
*/
const bytesToBase64 = (bytes: Uint8Array): string => {
const binString = Array.from(bytes, (byte) =>
String.fromCodePoint(byte)
).join("");
return btoa(binString);
};
/**
* Encode params as base64 JSON for state parameter
* Uses URL-safe base64 encoding with UTF-8 support
* Handles Unicode characters (e.g., utm_campaign=)
*/
export const encodeStateParam = (params: Record<string, string>): string => {
if (Object.keys(params).length === 0) return "";
try {
const json = JSON.stringify(params);
// Encode string as UTF-8 bytes, then convert to base64
const bytes = new TextEncoder().encode(json);
const base64 = bytesToBase64(bytes)
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
return base64;
} catch {
return "";
}
};
/**
* Get base64-encoded state parameter with current query params
*/
export const getStateParamForRedirect = (): string => {
const params = getCurrentQueryParams();
return encodeStateParam(params);
};
/**
* Get sessionId from current URL if present
*/
export const getSessionIdFromUrl = (): string | undefined => {
if (typeof window === "undefined") return undefined;
const params = new URLSearchParams(window.location.search);
return params.get("sessionId") || undefined;
};
/**
* Build URL with current query params preserved
*/
export const buildUrlWithQueryParams = (baseUrl: string): string => {
const params = getCurrentQueryParams();
if (Object.keys(params).length === 0) return baseUrl;
const url = new URL(baseUrl, window.location.origin);
for (const [key, value] of Object.entries(params)) {
url.searchParams.set(key, value);
}
return url.pathname + url.search;
};
// Backward compatibility aliases
export const getCurrentUtmParams = getCurrentQueryParams;
export const buildUrlWithUtmParams = buildUrlWithQueryParams;