简体   繁体   English

如何在 next.js 页面中实现 Razorpay 支付按钮

[英]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使用网站上的 Razorpay 支付按钮非常简单,它会给出如下代码

<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.但是在 react.js 上实现这个按钮时存在一些问题 按钮在检查器元素中可见但在屏幕中不可见。

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.所以现在我在这里提出了一个解决方案,用于在渲染组件后执行这些脚本,方法是使用 react.js 中的 useEffect() 选择该元素并在第一次渲染后附加脚本。

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 https://github.com/utterance/utterances/issues/161

Adding script tag to React/JSX 将脚本标签添加到 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此代码适用于 .jsx 页面

For integrating razorpay payment button on a nextjs site, the following code works.为了在 nextjs 网站上集成 razorpay 支付按钮,以下代码有效。

  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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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