All files / server/api/checkout paypal.post.ts

100% Statements 38/38
94.11% Branches 16/17
100% Functions 0/0
100% Lines 38/38

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 391x 4x 4x 3x 3x 4x 1x 1x 1x 2x 4x 4x 2x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 4x 4x  
export default defineEventHandler(async event => {
    const user = await requireUser(event);
    if (user.role === 'demo') throw createError({statusCode: 403, statusMessage: 'Le paiement est indisponible avec un compte de démonstration'});
    const config = useRuntimeConfig(event);
    const clientId = config.public.paypalClientId;
    if (!clientId || !config.paypalClientSecret) throw createError({
        statusCode: 503,
        statusMessage: "PayPal n’est pas encore configuré"
    });
    const body = await readBody(event);
    const {lines, promoError} = await checkoutLines(event, body.lines || [], body.promoCode);
    if (promoError) throw createError({statusCode: 400, statusMessage: promoError});
    const total = lines.reduce((s, l) => s + l.price * l.quantity, 0);
    const origin = config.public.siteUrl || getRequestURL(event).origin;
    const token = await paypalToken(clientId, config.paypalClientSecret);
    const response = await fetch("https://api-m.paypal.com/v2/checkout/orders", {
        method: "POST",
        headers: {Authorization: `Bearer ${token}`, "Content-Type": "application/json"},
        body: JSON.stringify({
            intent: "CAPTURE",
            purchase_units: [{
                amount: {currency_code: "EUR", value: (total / 100).toFixed(2)},
                items: lines.map(l => ({
                    name: l.name,
                    quantity: String(l.quantity),
                    unit_amount: {currency_code: "EUR", value: (l.price / 100).toFixed(2)}
                }))
            }],
            application_context: {
                return_url: `${origin}/api/checkout/paypal/capture`,
                cancel_url: `${origin}/panier?cancelled=1`
            }
        })
    });
    const order = await response.json() as any;
    if (!response.ok) throw createError({statusCode: 502, statusMessage: "Impossible de créer le paiement PayPal"});
    return {url: order.links?.find((l: any) => l.rel === "approve")?.href};
});