Reputation: 43
Hi Everyone I am a newbie in React. I am building my react app with typescript and would like to add Stripe to do the online payment. But I cannot find the typescript tutorial on stripe, so I try to use javascript to write the stripe part. But when I trigger the stripe. The errors below appear:
Referring to other solutions on stackOverFlow, i have used different import methods like
import stripe from './stripe';
import * as stripe from './stripe';
but none of them can solve my problem.
What's wrong with my code?
Here are the codes: For Stripe file:
import React from 'react'
import { Element } from "@stripe/react-stripe-js"
import { loadStripe } from '@stripe/stripe-js'
import "./Stripe.css"
const PaymentForm = require ('./PaymentForm.js')
const PUBLIC_KEY = "pk_test_XXXXXXX"
const stripeTestPromise = loadStripe(PUBLIC_KEY)
export default function Stripe() {
return (
<Element stripe={stripeTestPromise}>
<PaymentForm />
</Element>
)
}
For paymentFrom file:
import React, { useState } from 'react'
import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js"
import * as axios from 'axios'
import "./Stripe.css"
const CARD_OPTIONS = {
iconStyle: "solid",
style: {
base: {
iconColor: "#c4f0ff",
color:"fff",
fontWeight: 500,
fontSize: "16px",
fontSmoothing:"antialiased",
},
invaild: {
iconColor: "#ffc7ee",
color: "ffc7ee"
}
}
}
export default function PaymentForm() {
const [success, setSuccess] = useState(false)
const stripe = useStripe()
const elements = useElements()
const handleSubmit = async (e) => {
e.preventDefault()
const { error, paymentMethod } = await stripe.createPaymentMethod({
type: "card",
card: elements.getElement(CardElement)
})
if (!error) {
try {
const { id } = paymentMethod
const response = await axios.post('http://localhost:8080/checkout', {
amount: 500,
id
})
if (response.data.success) {
console.log('Successful payment')
setSuccess(true)
}
} catch (error) {
console.log('Error', error)
}
} else {
console.log(error.message)
}
}
return (
<div>
{!success ?
<form onSubmit={handleSubmit}>
<fieldset className="FormGroup">
<div className="FormRow">
<CardElement options={CARD_OPTIONS} />
</div>
</fieldset>
<button>Pay</button>
</form >
:
<div>
<h2>You just bought a sweet saptula</h2>
</div>
}
</div>
)
}
Upvotes: 0
Views: 1299
Reputation: 134
I'd like to put a comment but I don't have the reputation to do it, so I'll submit an answer:
If you're trying to insert the elements provider following the documentation the provider needs to be inserted this way:
import {Elements} from '@stripe/react-stripe-js';
you are importing this like
import {Element} from '@stripe/react-stripe-js';
it's possible that the element you're importing it's an interface or another object and not the provider you want
Upvotes: 3