Added packages for students to be able to purchase
This commit is contained in:
70
src/components/PayPalPayment.tsx
Normal file
70
src/components/PayPalPayment.tsx
Normal file
@@ -0,0 +1,70 @@
|
||||
import {DurationUnit} from "@/interfaces/paypal";
|
||||
import {CreateOrderActions, CreateOrderData, OnApproveActions, OnApproveData, OnCancelledActions, OrderResponseBody} from "@paypal/paypal-js";
|
||||
import {PayPalButtons, usePayPalScriptReducer} from "@paypal/react-paypal-js";
|
||||
import axios from "axios";
|
||||
import {useEffect, useState} from "react";
|
||||
import {toast} from "react-toastify";
|
||||
|
||||
interface Props {
|
||||
currency: string;
|
||||
price: number;
|
||||
duration: number;
|
||||
duration_unit: DurationUnit;
|
||||
onSuccess: (duration: number, duration_unit: DurationUnit) => void;
|
||||
}
|
||||
|
||||
export default function PayPalPayment({price, currency, duration, duration_unit, onSuccess}: Props) {
|
||||
const [{options}, dispatch] = usePayPalScriptReducer();
|
||||
|
||||
useEffect(() => {
|
||||
dispatch({
|
||||
type: "resetOptions",
|
||||
value: {
|
||||
...options,
|
||||
currency,
|
||||
},
|
||||
});
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [currency]);
|
||||
|
||||
const createOrder = async (data: CreateOrderData, actions: CreateOrderActions): Promise<string> => {
|
||||
console.log(data, actions);
|
||||
|
||||
return axios
|
||||
.post<OrderResponseBody>("/api/paypal", {currencyCode: currency, price})
|
||||
.then((response) => response.data)
|
||||
.then((data) => data.id);
|
||||
};
|
||||
|
||||
const onApprove = async (data: OnApproveData, actions: OnApproveActions) => {
|
||||
const request = await axios.post<{ok: boolean; reason?: string}>("/api/paypal/approve", {id: data.orderID, duration, duration_unit});
|
||||
|
||||
if (request.status !== 200) {
|
||||
toast.error("Something went wrong, please try again later");
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success("Your account has been credited more time!");
|
||||
return onSuccess(duration, duration_unit);
|
||||
};
|
||||
|
||||
const onError = async (data: Record<string, unknown>) => {
|
||||
console.log(data);
|
||||
toast.error("ERROR!");
|
||||
};
|
||||
|
||||
const onCancel = async (data: Record<string, unknown>, actions: OnCancelledActions) => {
|
||||
console.log(data, actions);
|
||||
toast.error("CANCEL!");
|
||||
};
|
||||
|
||||
return (
|
||||
<PayPalButtons
|
||||
className="w-full"
|
||||
style={{layout: "vertical"}}
|
||||
createOrder={createOrder}
|
||||
onApprove={onApprove}
|
||||
onCancel={onCancel}
|
||||
onError={onError}></PayPalButtons>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user