I am creating a payment plugin that integrates with a payment aggregator. So in the case of wooCommerce checkout, There's a possibility for the payer to pay to through mobile wallets, which would trigger a USSD and once the payer enters their pin, and I get a change of transaction status, they'll be redirected to a success or failure page. Since I am integrating with an aggregator, I have sensitive data like api_keys and token which isn't a good idea to call directly from the frontend. So I created endpoints with WordPress's app hooks and dedicated one for verifying transaction status. So the front end sends the transactionId and that endpoint calls the aggregator to verify the status of that transaction and returns the transaction payload to the front. I was asked to use a nonce by the wordpress team, but someone my nonce validation always fails when calling the created API endpoint with AJAX request.
Keeping in mind that the user is currently on the /checkout page and the API endpoint is on another endpoint like /wp-json/my-plugin/get-transaction. I create the nonce when woocommerce order is created successfully and send the created nonce to the frontend or I use the wp_nonce_field( 'my-plugin-key-'.$tx_id ); which would create the nonce and I send to the backend as part of my payload. Below is a sample code
This method would be called by woocommerce to initialize the payment method and render it
public function payment_scripts()
{
// we need JavaScript to process a token only on cart/checkout pages, right?
if (!is_cart() && !is_checkout() && !isset($_GET['pay_for_order'])) {
return;
}
// if our payment gateway is disabled, we do not have to enqueue JS too
if ('no' === $this->enabled) {
return;
}
// creating nonce input on checkout page
wp_nonce_field( 'my-plugin-key-'.$tx_id );
...
}
Handling API calls which are made to /wp-json/my-plugin/get-transaction fron /checkout page
public function apiHandler($req)
{
$transaction = new Transactions();
// $_POST['_wp_nonce'] holds the value of the nonce created when checkout page is loaded
if(!wp_verify_nonce($_POST['_wp_nonce'],'my-plugin-key-'.$_POST['txnId'])){
wp_send_json_error('Incorrect nonce ');
die();
}
...
}
This always fails validation. PLEASE HELP.