feat(MED-100): update montonio redirect
This commit is contained in:
@@ -58,12 +58,6 @@ export const POST = enhanceRouteHandler(
|
||||
algorithms: ['HS256'],
|
||||
}) as MontonioOrderToken;
|
||||
|
||||
const activeCartId = request.cookies.get('_medusa_cart_id')?.value;
|
||||
const [, cartId] = decoded.merchantReferenceDisplay.split(':');
|
||||
if (cartId !== activeCartId) {
|
||||
throw new Error('Invalid cart id');
|
||||
}
|
||||
|
||||
logger.info(
|
||||
{
|
||||
name: namespace,
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page';
|
||||
import { MontonioCheckoutCallback } from '../../../../_components/cart/montonio-checkout-callback';
|
||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
|
||||
export async function generateMetadata() {
|
||||
const { t } = await createI18nServerInstance();
|
||||
|
||||
return {
|
||||
title: t('cart:montonioCallback.title'),
|
||||
};
|
||||
}
|
||||
|
||||
export default async function MontonioCheckoutCallbackPage() {
|
||||
return (
|
||||
<div className={'flex h-full flex-1 flex-col'}>
|
||||
<PageHeader title={<Trans i18nKey="cart:montonioCallback.title" />} />
|
||||
<PageBody>
|
||||
<MontonioCheckoutCallback />
|
||||
</PageBody>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { MontonioOrderToken } from "@/app/home/(user)/_components/cart/types";
|
||||
import { loadCurrentUserAccount } from "@/app/home/(user)/_lib/server/load-user-account";
|
||||
import { placeOrder } from "@lib/data/cart";
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { z } from "zod";
|
||||
import { createI18nServerInstance } from "~/lib/i18n/i18n.server";
|
||||
|
||||
const emailSender = process.env.EMAIL_SENDER;
|
||||
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL!;
|
||||
|
||||
const env = z
|
||||
.object({
|
||||
emailSender: z
|
||||
.string({
|
||||
required_error: 'EMAIL_SENDER is required',
|
||||
})
|
||||
.min(1),
|
||||
siteUrl: z
|
||||
.string({
|
||||
required_error: 'NEXT_PUBLIC_SITE_URL is required',
|
||||
})
|
||||
.min(1),
|
||||
})
|
||||
.parse({
|
||||
emailSender,
|
||||
siteUrl,
|
||||
});
|
||||
|
||||
const sendEmail = async ({ email, analysisPackageName, personName, partnerLocationName, language }: { email: string, analysisPackageName: string, personName: string, partnerLocationName: string, language: string }) => {
|
||||
try {
|
||||
const { renderSynlabAnalysisPackageEmail } = await import('@kit/email-templates');
|
||||
const { getMailer } = await import('@kit/mailers');
|
||||
|
||||
const mailer = await getMailer();
|
||||
|
||||
const { html, subject } = await renderSynlabAnalysisPackageEmail({
|
||||
analysisPackageName,
|
||||
personName,
|
||||
partnerLocationName,
|
||||
language,
|
||||
});
|
||||
|
||||
await mailer
|
||||
.sendEmail({
|
||||
from: env.emailSender,
|
||||
to: email,
|
||||
subject,
|
||||
html,
|
||||
})
|
||||
.catch((error) => {
|
||||
throw new Error(`Failed to send email, message=${error}`);
|
||||
});
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to send email, message=${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
const handleOrderToken = async (orderToken: string) => {
|
||||
const secretKey = process.env.MONTONIO_SECRET_KEY as string;
|
||||
|
||||
const decoded = jwt.verify(orderToken, secretKey, {
|
||||
algorithms: ['HS256'],
|
||||
}) as MontonioOrderToken;
|
||||
if (decoded.paymentStatus !== 'PAID') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const [, , cartId] = decoded.merchantReferenceDisplay.split(':');
|
||||
if (!cartId) {
|
||||
throw new Error("Cart ID not found");
|
||||
}
|
||||
const { order } = await placeOrder(cartId, { revalidateCacheTags: true });
|
||||
return {
|
||||
email: order.email,
|
||||
partnerLocationName: order.metadata?.partner_location_name as string ?? '',
|
||||
analysisPackageName: order.items?.[0]?.title ?? '',
|
||||
};
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to place order, message=${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const { language } = await createI18nServerInstance();
|
||||
const baseUrl = new URL(env.siteUrl.replace("localhost", "webhook.site"));
|
||||
try {
|
||||
const orderToken = new URL(request.url).searchParams.get('order-token');
|
||||
if (!orderToken) {
|
||||
throw new Error("Order token is missing");
|
||||
}
|
||||
|
||||
const account = await loadCurrentUserAccount();
|
||||
if (!account) {
|
||||
throw new Error("Account not found in context");
|
||||
}
|
||||
|
||||
const orderResult = await handleOrderToken(orderToken);
|
||||
if (!orderResult) {
|
||||
throw new Error("Order result is missing");
|
||||
}
|
||||
|
||||
const { email, partnerLocationName, analysisPackageName } = orderResult;
|
||||
const personName = account.name;
|
||||
if (email) {
|
||||
await sendEmail({ email, analysisPackageName, personName, partnerLocationName, language });
|
||||
}
|
||||
return Response.redirect(new URL('/home/order', baseUrl))
|
||||
} catch (error) {
|
||||
console.error("Failed to place order", error);
|
||||
return Response.redirect(new URL('/home/cart/montonio-callback/error', baseUrl));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import Link from 'next/link';
|
||||
|
||||
import { PageBody, PageHeader } from '@/packages/ui/src/makerkit/page';
|
||||
import { createI18nServerInstance } from '@/lib/i18n/i18n.server';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
import { Alert, AlertDescription } from '@kit/ui/shadcn/alert';
|
||||
import { AlertTitle } from '@kit/ui/shadcn/alert';
|
||||
import { Button } from '@kit/ui/button';
|
||||
|
||||
export async function generateMetadata() {
|
||||
const { t } = await createI18nServerInstance();
|
||||
|
||||
return {
|
||||
title: t('cart:montonioCallback.title'),
|
||||
};
|
||||
}
|
||||
|
||||
export default async function MontonioCheckoutCallbackErrorPage() {
|
||||
return (
|
||||
<div className={'flex h-full flex-1 flex-col'}>
|
||||
<PageHeader title={<Trans i18nKey="cart:montonioCallback.title" />} />
|
||||
<PageBody>
|
||||
<div className={'flex flex-col space-y-4'}>
|
||||
<Alert variant={'destructive'}>
|
||||
<AlertTitle>
|
||||
<Trans i18nKey={'checkout.error.title'} />
|
||||
</AlertTitle>
|
||||
|
||||
<AlertDescription>
|
||||
<p>
|
||||
<Trans i18nKey={'checkout.error.description'} />
|
||||
</p>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<div className={'flex'}>
|
||||
<Button asChild>
|
||||
<Link href={'/home'}>
|
||||
<Trans i18nKey={'checkout.goToDashboard'} />
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</PageBody>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { StoreCart, StoreCartLineItem } from "@medusajs/types"
|
||||
import CartItems from "./cart-items"
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
@@ -10,7 +12,6 @@ import {
|
||||
CardHeader,
|
||||
} from '@kit/ui/card';
|
||||
import DiscountCode from "./discount-code";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { initiatePaymentSession } from "@lib/data/cart";
|
||||
import { formatCurrency } from "@/packages/shared/src/utils";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -27,9 +28,10 @@ export default function Cart({
|
||||
analysisPackages: StoreCartLineItem[];
|
||||
otherItems: StoreCartLineItem[];
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const { i18n: { language } } = useTranslation();
|
||||
|
||||
const [isInitiatingSession, setIsInitiatingSession] = useState(false);
|
||||
|
||||
const items = cart?.items ?? [];
|
||||
|
||||
if (!cart || items.length === 0) {
|
||||
@@ -49,13 +51,18 @@ export default function Cart({
|
||||
);
|
||||
}
|
||||
|
||||
async function handlePayment() {
|
||||
async function initiatePayment() {
|
||||
setIsInitiatingSession(true);
|
||||
const response = await initiatePaymentSession(cart!, {
|
||||
provider_id: 'pp_system_default',
|
||||
provider_id: 'pp_montonio_montonio',
|
||||
});
|
||||
if (response.payment_collection) {
|
||||
const url = await handleNavigateToPayment({ language });
|
||||
router.push(url);
|
||||
const { payment_sessions } = response.payment_collection;
|
||||
const paymentSessionId = payment_sessions![0]!.id;
|
||||
const url = await handleNavigateToPayment({ language, paymentSessionId });
|
||||
window.location.href = url;
|
||||
} else {
|
||||
setIsInitiatingSession(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,7 +109,8 @@ export default function Cart({
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Button className="h-10" onClick={handlePayment}>
|
||||
<Button className="h-10" onClick={initiatePayment} disabled={isInitiatingSession}>
|
||||
{isInitiatingSession && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
<Trans i18nKey="cart:checkout.goToCheckout" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { Alert, AlertDescription, AlertTitle } from '@kit/ui/alert';
|
||||
import { Button } from '@kit/ui/button';
|
||||
import { Trans } from '@kit/ui/trans';
|
||||
import { placeOrder } from "@lib/data/cart"
|
||||
import Link from 'next/link';
|
||||
import GlobalLoader from '../../loading';
|
||||
|
||||
enum Status {
|
||||
LOADING = 'LOADING',
|
||||
ERROR = 'ERROR',
|
||||
}
|
||||
|
||||
export function MontonioCheckoutCallback() {
|
||||
const router = useRouter();
|
||||
const [status, setStatus] = useState<Status>(Status.LOADING);
|
||||
const [isFinalized, setIsFinalized] = useState(false);
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
useEffect(() => {
|
||||
if (isFinalized) {
|
||||
return;
|
||||
}
|
||||
|
||||
const token = searchParams.get('order-token');
|
||||
if (!token) {
|
||||
router.push('/home/cart');
|
||||
return;
|
||||
}
|
||||
|
||||
async function verifyToken() {
|
||||
setStatus(Status.LOADING);
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/montonio/verify-token', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
setIsFinalized(true);
|
||||
|
||||
if (!response.ok) {
|
||||
const body = await response.json();
|
||||
throw new Error(body.error ?? 'Failed to verify payment status.');
|
||||
}
|
||||
|
||||
const body = await response.json();
|
||||
const paymentStatus = body.status as string;
|
||||
if (paymentStatus === 'PAID') {
|
||||
try {
|
||||
await placeOrder();
|
||||
} catch (e) {
|
||||
console.error("Error placing order", e);
|
||||
router.push('/home/cart');
|
||||
}
|
||||
} else {
|
||||
throw new Error('Payment failed or pending');
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Error verifying token", e);
|
||||
setStatus(Status.ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
void verifyToken();
|
||||
}, [searchParams, isFinalized]);
|
||||
|
||||
if (status === Status.ERROR) {
|
||||
return (
|
||||
<div className={'flex flex-col space-y-4'}>
|
||||
<Alert variant={'destructive'}>
|
||||
<AlertTitle>
|
||||
<Trans i18nKey={'checkout.error.title'} />
|
||||
</AlertTitle>
|
||||
|
||||
<AlertDescription>
|
||||
<p>
|
||||
<Trans i18nKey={'checkout.error.description'} />
|
||||
</p>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<div className={'flex'}>
|
||||
<Button asChild>
|
||||
<Link href={'/home'}>
|
||||
<Trans i18nKey={'checkout.goToDashboard'} />
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <GlobalLoader />;
|
||||
}
|
||||
22
app/home/(user)/_components/cart/types.ts
Normal file
22
app/home/(user)/_components/cart/types.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
export interface MontonioOrderToken {
|
||||
uuid: string;
|
||||
accessKey: string;
|
||||
merchantReference: string;
|
||||
merchantReferenceDisplay: string;
|
||||
paymentStatus:
|
||||
| 'PAID'
|
||||
| 'FAILED'
|
||||
| 'CANCELLED'
|
||||
| 'PENDING'
|
||||
| 'EXPIRED'
|
||||
| 'REFUNDED';
|
||||
paymentMethod: string;
|
||||
grandTotal: number;
|
||||
currency: string;
|
||||
senderIban?: string;
|
||||
senderName?: string;
|
||||
paymentProviderName?: string;
|
||||
paymentLinkUuid: string;
|
||||
iat: number;
|
||||
exp: number;
|
||||
}
|
||||
Reference in New Issue
Block a user