简体   繁体   中英

How to implement Razorpay payment button in next.js page

Using the Razorpay payment button on the website is quite simple it gives a code like

<form>
<script 
  src = "https://cdn.razorpay.com/static/widget/payment-button.js"
  data-payment_button_id = "pl_FNmjTJSGXBYIfp"
  data-button_text = "Buy Now"
  data-button_theme = "brand-color">
</script>
</form>

But there's some problem when implementing this button on react.js Button is visible in inspector element but not visible in the screen.

As you may not know but the real problem lies on script tag inside component not executed after rendering that component. So now here I came with a solution for executing those script after rendering the component by using useEffect() from react.js to select that element and append script after first render.

useEffect(()=>{
  const Script = document.createElement("script");
  //id should be same as given to form element
  const Form = document.getElementById('donateForm');
  Script.setAttribute('src','your src')
  Script.setAttribute('data-payment_button_id','your id')
  Form.appendChild(Script);
},[])
. 
.
.
// form component
<form id='donateForm'> </form>

Some references I used which helped me searching the solution

https://github.com/utterance/utterances/issues/161

Adding script tag to React/JSX

useEffect(()=>{
async function makeForm() {
  const Script = document.createElement("script");
  const Form = document.getElementById('donateForm');
  Script.setAttribute('src','https://cdn.razorpay.com/static/widget/subscription-button.js')
  Script.setAttribute('data-subscription_button_id','pl_somethingsomething')
  Script.setAttribute('data-button_theme','brand-color')
  Form.appendChild(Script); 
}
makeForm()},[])

return(
<>
  <form id='donateForm'> </form>
</>

this code is working in .jsx page for

For integrating razorpay payment button on a nextjs site, the following code works.

  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);
  useEffect(() => {
    const Script = document.createElement("script");
    //id should be same as given to form element
    const Form = document.getElementById("donateForm");
    Script.setAttribute(
      "src",
      "https://checkout.razorpay.com/v1/payment-button.js"
    );
    Script.setAttribute("data-payment_button_id", "YOUR ID");
    if (Form) {
      Form.appendChild(Script);
    }
  }, [mounted]);


return mounted ? <form id="donateForm"></form> : null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM