Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions components/Payment/Payment.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,47 @@
import { useState } from 'react';

import { usePayment, useTrip, useTranslation } from '../../hooks';
import {
createContext,
useContext,
} from 'react';
import { usePayment, useTrip, useTranslation, usePaymentTranslations } from '../../hooks';

import { Select } from '../Select';

import {
wrapper,
headline,
amount,
select,
button,
} from './Payment.module.css';

const PaymentContext = createContext({});

export default function Payment() {
const { t, formatNumber } = useTranslation();
const {
trip: { cost },
} = useTrip();
const { process } = usePayment();
const { recipients } = usePaymentTranslations();

// Destination is view-only and we'll individually reach out to donors
let { recipient } = useContext(PaymentContext);
recipient = Object.keys(recipients)[0];

return (
<div className={wrapper}>
<h3 className={headline}>{t('paymentHeadline')}</h3>
<p className={amount}>{formatNumber(cost, 2)} €</p>
<button className={button} onClick={()=> process(cost)}>
<Select
value={recipient}
options={recipients}
onChange={newValue => recipient = newValue}
invert={true}
hideLabel={true}
className={select}
label={t('chooseOrganization')}
/>
<button className={button} onClick={()=> process(cost, recipient)}>
{t('makeDonation')}
</button>
</div>
Expand Down
5 changes: 4 additions & 1 deletion data/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@
"analysis": "Analyse",
"business": "Business",
"calculateEmissions": "Emissionen berechnen",
"chooseOrganization": "Organisation auswählen",
"cookieConsentButton": "Cookies Akzeptieren",
"ch4": "Methan",
"co2": "Kohlendioxid",
"destination": "Zielflughafen",
"distance": "Entfernung",
"donationRecipient_greenpeace": "Greenpeace unterstützen",
"donationRecipient_atmosfair": "Atmosfair unterstützen",
"economy": "Economy",
"emissions": "Emissionen",
"first": "First",
Expand All @@ -23,7 +26,7 @@
"passengers": "Passagiere",
"paymentHeadline": "Offsetting-Kosten",
"paymentName": "CO2-Kompensation",
"paymentDescription": "Flugreise mit diesen Stationen: {{ airports }}",
"paymentDescription": "Flugreise mit diesen Stationen: {{ airports }}. Diese Spende wird {{ recipient }}",
"premium": "Economy Premium",
"removeStopover": "Zwischenstop entfernen",
"roundTrip": "Rückflug",
Expand Down
2 changes: 1 addition & 1 deletion hooks/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export { usePayment } from './usePayment';
export { usePayment, usePaymentTranslations } from './usePayment';
export { useSuggestions } from './useSuggestions';
export { useTracking, withTracking } from './useTracking';
export { useTranslation, withTranslation } from './useTranslation';
Expand Down
33 changes: 24 additions & 9 deletions hooks/usePayment.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,51 @@
import { useState } from 'react';
import { useTranslation } from './useTranslation';

function getPaymentURL(amount) {
const params = new URLSearchParams({ amount: Number(amount) });
function getPaymentURL(amount, recipient) {
const params = new URLSearchParams({
amount: Number(amount),
recipient: recipient.replace(/[^a-z]+/gi, '')
});
return `/api/payment?${params.toString()}`;
}

async function fetchPaymentSession(amount) {
const response = await fetch(getPaymentURL(amount));
async function fetchPaymentSession(amount, recipient) {
const response = await fetch(getPaymentURL(amount, recipient));
return response.ok
? response.json()
: Promise.reject(new Error(response.statusText));
}

async function processPayment(amount) {
async function processPayment(amount, recipient) {
try {
const { loadStripe } = await import('@stripe/stripe-js');
const [stripe, { sessionId }] = await Promise.all([
loadStripe(window.stripeKey),
fetchPaymentSession(amount),
fetchPaymentSession(amount, recipient),
]);
stripe.redirectToCheckout({ sessionId });
} catch (error) {
console.error(error);
}
}
}


export function usePayment() {
const [processing, setProcessing] = useState(false);
const process = (amount) => {
const process = (amount, recipient) => {
if (processing) return;
setProcessing(true);
processPayment(amount);
processPayment(amount, recipient);
};
return { processing, process };
}

export function usePaymentTranslations() {
const { t } = useTranslation();
return {
recipients: {
atmosfair: t("donationRecipient_atmosfair"),
greenpeace: t("donationRecipient_greenpeace"),
}
};
}
14 changes: 9 additions & 5 deletions pages/api/payment.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Stripe from 'stripe';

import { useTranslation } from '../../hooks';
import { usePaymentTranslations, useTranslation } from '../../hooks';

const stripe = new Stripe(process.env.STRIPE_PRIVATE_KEY);

Expand All @@ -10,24 +10,28 @@ const getSuccessUrl = (referer) => {
return url.toString();
};

const getDescription = (referer) => {
const getDescription = (referer, recipient) => {
const { t } = useTranslation();
const url = new URL(referer);
const trip = url.searchParams.get('a') || '';
return t('paymentDescription').replace('{{ airports }}', trip.split(',').join(', '));

return t('paymentDescription')
.replace('{{ airports }}', trip.split(',').join(', '))
.replace('{{ recipient }}', recipient);
};

export default async (req, res) => {
const { t } = useTranslation();
const { amount } = req.query;
const { recipients } = usePaymentTranslations();
const { amount, recipient } = req.query;
const { referer } = req.headers;
const { id: sessionId } = await stripe.checkout.sessions.create({
submit_type: 'donate',
payment_method_types: ['card'],
line_items: [
{
name: t('paymentName'),
description: getDescription(referer),
description: getDescription(referer, recipients[recipient.replace(/[^a-z]+/gi, '')]),
amount: amount * 100,
currency: 'eur',
quantity: 1,
Expand Down