Suyash Nachankar
Suyash Nachankar

Reputation: 69

How to Redirect to an external URL while sending formData with POST request via fetch() in ReactJS?

I want to POST some form fields to an external API with a POST request. I tried using HTML form tag with action and method attribute in React. Submitting this form works fine. BUT when I use fetch() to POST the same, it does NOT redirect to the external url. I just get a response with status 200 and redirected false. When I manually try to redirect using window.location.href = url, it redirects BUT does NOT supply the form fields to the API. How to POST fields and get redirected using fetch() in React ?

const formData = new FormData();
  formData.append("MID", mId);
  formData.append("WEBSITE", "WEBSTAGING");
  formData.append("ORDER_ID", orderId);
  formData.append("CUST_ID", userId);
  formData.append("MOBILE_NO", mobile);
  formData.append("EMAIL", email);
  formData.append("INDUSTRY_TYPE_ID", "Retail");
  formData.append("CHANNEL_ID", "WEB");
  formData.append("TXN_AMOUNT", calculateTotal().toString());
  formData.append(
    "CALLBACK_URL",
    "http://localhost:5050/api/payments/verify"
  );
  formData.append("CHECKSUMHASH", checksum);

  console.log(formData);

  fetch("https://securegw-stage.paytm.in/order/process", {
    method: "POST",
    headers: {
      "Content-Type": "multipart/form-data",
    },
    redirect: "follow",
    body: formData,
  }).then((res) => {
    console.log(res);
    //window.location.href = res.url;
  });

Upvotes: 0

Views: 2202

Answers (1)

Arpan Nagar
Arpan Nagar

Reputation: 51

As of October 2020, the HTML form-data for PayTm gateway has depreciated.

You can try using a vanilla HTTP request.

const paytmParams = {};

        paytmParams.body = {
            requestType: 'Payment',
            mid: PaytmConfig.PaytmConfig.mid,
            websiteName: PaytmConfig.PaytmConfig.website,
            orderId: orderId,
            callbackUrl: 'YOUR CALLBACK URL',
            txnAmount: {
                value: 'VALUE',
                currency: 'CURRENCY'
            },
            userInfo: {
                custId: 'CUSTOMER EMAIL'
            }
        };
        PaytmChecksum.generateSignature(
            JSON.stringify(paytmParams.body),
            PaytmConfig.PaytmConfig.key
        ).then(function (checksum) {
            paytmParams.head = {
                signature: checksum
            };

            let post_data = JSON.stringify(paytmParams);

            let options = {
                /* for Staging */
                hostname: 'securegw-stage.paytm.in',

                /* for Production */
                // hostname: 'securegw.paytm.in',

                port: 443,
                path: `/theia/api/v1/initiateTransaction?mid=${PaytmConfig.PaytmConfig.mid}&orderId=${orderId}`,
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Content-Length': post_data.length
                }
            };
            let response = '';
            let post_req = https.request(options, function (
                post_res
            ) {
                post_res.on('data', function (chunk) {
                    response += chunk;
                });

                post_res.on('end', function () {
                    response = JSON.parse(response);
                    console.log('txnToken:', response);

                    res.writeHead(200, {
                        'Content-Type': 'text/html'
                    });
                    res.write(`<html>
                                <head>
                                    <title>Show Payment Page</title>
                                </head>
                                <body>
                                    <center>
                                        <h1>Please do not refresh this page...</h1>
                                    </center>
                                    <form method="post" action="https://securegw-stage.paytm.in/theia/api/v1/showPaymentPage?mid=${PaytmConfig.PaytmConfig.mid}&orderId=${orderId}" name="paytm">
                                        <table border="1">
                                            <tbody>
                                                <input type="hidden" name="mid" value="${PaytmConfig.PaytmConfig.mid}">
                                                    <input type="hidden" name="orderId" value="${orderId}">
                                                    <input type="hidden" name="txnToken" value="${response.body.txnToken}">
                                         </tbody>
                                      </table>
                                                    <script type="text/javascript"> document.paytm.submit(); </script>
                                   </form>
                                </body>
                             </html>`);
                    res.end();
                });
            });
            console.log(post_data);
            post_req.write(post_data);
            post_req.end();
        });```

Upvotes: 1

Related Questions