如何在WordPress中回调API EndPoint后重定向用户?



我正在woocommerce中创建一个支付网关。向支付处理器服务器发送请求并返回 Success 作为状态代码后。服务器将向我自己平台的端点发送一个GET请求,并带有一些参数,指示已从用户中扣除了金额并且交易已成功。

根据(成功的参数(,用户将被重定向到"谢谢"页面。

我设法创建了一个简单的 API 端点,但我无法响应状态代码并将用户重定向到感谢页面


add_action( 'rest_api_init', function () {
register_rest_route( 'zaindob/v1', '/reqendpoint/' . 'statuscode=' . '(?P<statuscode>d+)' , array(
'methods' => 'GET',
'callback' => 'respondfun',
) );
} );
function respondfun(){

$order = wc_get_order($order_id);
wc_add_notice('Success = true' , 'Success' );           
$order->payment_complete();      
$woocommerce->cart->empty_cart();
wp_redirect('https://iotkidsiq.com/thank-you');
}

响应后,不会重定向用户。我确定我的代码不正确,但我只想向您展示到目前为止我创建的内容

你可以在wp_redirect((函数后面添加"exit;"。 它将立即停止其余 API 部分的进一步处理。

You can use below code   

add_action( 'rest_api_init', 'add_form_data_into_custom_database' );

WP-REST API 的 API 自定义端点

http://localhost/wp-form/wp-json/custom-plugin/add/formdata

function add_form_data_into_custom_database() {
register_rest_route('custom-plugin', '/add/formdata', array(
'methods'  => 'POST',
'callback' => 'add_formdata',
)
);

}
function add_formdata($request) {
$create_id = $_POST['create_id']?$_POST['create_id']:"";
$create_name = $_POST['create_name'] ?$_POST['create_name']:"";
$create_email =$_POST['create_email'] ?$_POST['create_email']:"";
global $wpdb;       
$table_name = $wpdb->prefix . 'userstable';
wp_handle_upload($_FILES["create_file"], array('test_form' => FALSE));
$wpdb->insert(
$table_name, //table
array('user_id' => $create_id,'name' => $create_name,'email' => $create_email), //data
array('%s','%s') //data format          
);
wp_redirect( home_url() );
exit();
}

无需使用wp_redirect执行重定向并执行exit,您只需通过返回状态代码302(或其他 3xx 代码,具体取决于您想要的结果(来导航浏览器以执行重定向。有关更多信息,请访问 MDN( 并指定Location标头。

因此,要执行重定向,只需返回以下内容:

return rest_ensure_response(new WP_REST_Response(
null,
302,
array(
'Location' => get_home_url() // or set any other URL you wish to redirect to
)
));

最新更新