Untitled

 avatar
unknown
plain_text
2 years ago
3.2 kB
8
Indexable
import React from 'react';
import { useFormik } from 'formik';
import * as Yup from 'yup';

const FlutterwavePaymentForm = () => {
  const formik = useFormik({
    initialValues: {
      public_key: 'FLWPUBK_TEST-SANDBOXDEMOKEY-X',
      tx_ref: 'bitethtx-019203',
      amount: 3400,
      currency: 'NGN',
      payment_options: 'card, ussd',
      redirect_url: 'https://demoredirect.localhost.me/',
      meta: {
        token: 54,
      },
      customer: {
        name: 'Jesse Pinkman',
        email: 'jessepinkman@walterwhite.org',
      },
    },
    validationSchema: Yup.object({
      amount: Yup.number().required('Amount is required').positive('Amount must be positive'),
      // Add more validation if necessary
    }),
    onSubmit: async (values, { setSubmitting, setFieldError }) => {
      try {
        const response = await fetch('https://checkout.flutterwave.com/v3/hosted/pay', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(values),
        });

        const result = await response.json();

        // Handle the payment response, you might want to redirect to a success page or show a confirmation message
        console.log(result);

        // Clear form and handle success
        formik.resetForm();
        alert('Payment successful! Redirect or show success message here.');
      } catch (error) {
        console.error('Error submitting payment:', error);
        setFieldError('submit', 'Payment failed. Please try again.');
      } finally {
        setSubmitting(false);
      }
    },
  });

  return (
    <div className="max-w-md mx-auto mt-8 p-4 bg-gray-100 rounded-md shadow-md">
      <form onSubmit={formik.handleSubmit}>
        <input type="hidden" name="public_key" value={formik.values.public_key} />
        <input type="hidden" name="tx_ref" value={formik.values.tx_ref} />
        <div className="mb-4">
          <label htmlFor="amount" className="block text-sm font-medium text-gray-700">
            Amount
          </label>
          <input
            type="number"
            id="amount"
            name="amount"
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            value={formik.values.amount}
            className={`mt-1 p-2 w-full border rounded-md ${
              formik.touched.amount && formik.errors.amount ? 'border-red-500' : 'border-gray-300'
            }`}
          />
          {formik.touched.amount && formik.errors.amount && (
            <p className="text-red-500 text-xs mt-1">{formik.errors.amount}</p>
          )}
        </div>
        {/* Add more input fields here for other parameters */}
        <button
          type="submit"
          className="bg-blue-500 text-white py-2 px-4 rounded-md hover:bg-blue-600"
          disabled={formik.isSubmitting}
        >
          Pay Now
        </button>
        {formik.errors.submit && (
          <p className="text-red-500 text-xs mt-2">{formik.errors.submit}</p>
        )}
      </form>
    </div>
  );
};

export default FlutterwavePaymentForm;
Editor is loading...
Leave a Comment