【问题标题】:WordPress custom API with WooCommerce Authentication带有 WooCommerce 身份验证的 WordPress 自定义 API
【发布时间】:2021-06-18 18:11:57
【问题描述】:

我已经在 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-httphttps://wordpress.stackexchange.com/questions/355041/how-to-authenticate-custom-api-endpoint-in-woocommerce 这个网址,但我还没有找到合适的方法或过滤器或教程来满足我的要求。

至少有人可以指导我如何在此处添加身份验证.. 任何建议都将受到高度赞赏。

谢谢

【问题讨论】:

    标签: php wordpress woocommerce wordpress-rest-api


    【解决方案1】:

    在这种情况下,您可以使用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/

    【讨论】:

    • 非常感谢你的回答..你能告诉我我需要在这里输入一些类似身份验证的逻辑吗?
    • @MittulAtTechnoBrave perrmission_callbackcallback 之前执行
    • 是的 .. 我知道 .. 但我想要这样的东西 http://localhost/wordpress/wp-json/wc/v1/orders 如果你直接运行这个 woocomerce wordpress api .. 那么它不会被执行 .. 它会要求我们输入授权输入像消费者密钥和秘密..我想在我的自定义 api 中使用这个功能..
    • 所以我使用邮递员并输入授权.. oauth1 选择然后只有我可以获取订单数据.. 所以我想在你建议的permission_callback 中实现此授权.. 所以我的问题是,我怎样才能做到这一点?
    • 我知道类似 'permission_callback' =&gt; function() { return current_user_can( 'edit_posts' ); }, 的东西,但我不想检查这个 .. 而我想要授权检查..
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-07-27
      • 1970-01-01
      • 2016-12-31
      • 2020-04-22
      • 2016-03-15
      • 2019-08-19
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      相关资源
      最近更新 更多