/
PayPalButton.tsx
78 lines (73 loc) · 1.89 KB
/
PayPalButton.tsx
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { type PayPalNamespace, loadScript } from "@paypal/paypal-js";
import React from "react";
let payPalPromise: Promise<PayPalNamespace | null> | null = null;
const renderPayPalButton = async (
button: HTMLDivElement,
options: {
planId: string;
clientId: string;
}
) => {
let paypal: PayPalNamespace;
if (!window.paypal && !payPalPromise) {
payPalPromise = loadScript({
clientId: options.clientId,
vault: true,
intent: "subscription",
});
}
await payPalPromise;
paypal = window.paypal!;
paypal
.Buttons?.({
style: {
shape: "pill",
color: "gold",
layout: "vertical",
label: "subscribe",
},
fundingSource: "paypal",
createSubscription: (_, actions) => {
console.log("creating subscription for ", button);
return actions.subscription.create({
plan_id: options.planId,
quantity: button.dataset.quantity,
application_context: {
shipping_preference: "NO_SHIPPING",
},
});
},
onApprove: async (data) => {
window.location.href = "/support-me/success";
},
})
.render(button);
};
export interface PayPalButtonProps {
planId: string;
clientId: string;
quantity: number;
}
export const PayPalButton = (props: PayPalButtonProps) => {
return (
<div
data-quantity={props.quantity}
key={props.planId + props.planId + props.quantity}
// See: https://github.com/paypal/react-paypal-js/issues/224
// TODO: remove this once that issue is fixed
style={{ colorScheme: "none" }}
ref={React.useCallback(
(el: HTMLDivElement | null) => {
if (!el) {
return;
}
renderPayPalButton(el, {
planId: props.planId,
clientId: props.clientId,
});
},
[props.planId]
)}
/>
);
};