使用 WooCommerce 身份验证的 WordPress 自定义 API

WordPress custom API with WooCommerce Authentication

我在 WordPress 中创建了自定义 API,并且我在此 API 中获取 WooCommerce 订阅数据,并且根据我的要求工作正常。

但是,现在我想在此 API 中添加基本身份验证,它可以像其他 WooCommerce API 端点一样检查消费者密钥和机密。

这是我的样本API,我想在其中检查基本身份验证。

// Action to execute Rest API routes
add_action('rest_api_init', function () {

    // Getting Product data based on subscription id
    register_rest_route('getproductdata', '/(?P<id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'getProductData',
    ));
});


function getProductData($request) {
    // I WANT TO CHECK BASIC AUTHENTICATION HERE BEFORE EXECUTING BELOW CODE 


    die('inside my api');
}

我已经检查了这个 https://woocommerce.github.io/woocommerce-rest-api-docs/#authentication-over-http and https://wordpress.stackexchange.com/questions/355041/how-to-authenticate-custom-api-endpoint-in-woocommerce 这个网址,但我还没有找到合适的方法或过滤器或教程来满足我的要求。

至少有人可以指导我如何在此处添加身份验证.. 任何建议将不胜感激。

谢谢

在这种情况下,您可以使用 permission_callback 键:

// Action to execute Rest API routes
add_action('rest_api_init', function () {

    // Getting Product data based on subscription id
    register_rest_route('getproductdata', '/(?P<id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'getProductData',
        'permission_callback' => 'restCheckUser'
    ));
});


function getProductData($request) {
    // I WANT TO CHECK BASIC AUTHENTICATION HERE BEFORE EXECUTING BELOW CODE


    die('inside my api');
}

function restCheckUser(WP_REST_Request $request) {
    if ('get_token_from_database' === $request->get_param('token')) {
         return true;
    }
    return false;
}

完整文档在这里 - https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/

好的,伙计们..最终我使用 JWT Authentication for WP REST API 在我的自定义端点 API 中进行了身份验证。

感谢大家的帮助、支持和指导。