【问题标题】:How to redirect user after a callback of API EndPoint in WordPress?WordPress中API端点回调后如何重定向用户?
【发布时间】:2020-01-05 10:14:13
【问题描述】:

我正在 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');

}

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

【问题讨论】:

    标签: wordpress wordpress-rest-api


    【解决方案1】:

    您可以添加“退出;”在 wp_redirect() 函数之后。 它将立即停止其余 api 部分的进一步处理。

    【讨论】:

      【解决方案2】:
      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();
      }
      

      【讨论】:

        【解决方案3】:

        除了使用wp_redirectexit 进行重定向之外,您还可以通过返回状态代码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
          )
        ));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-01-04
          • 1970-01-01
          • 1970-01-01
          • 2018-09-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多