Reputation: 1242
I have created custom API in WordPress and I am getting WooCommerce Subscription data in this API and its working fine as per my requirements.
Howerver, now I want to add basic authentication in this API which can check consumer key and secret like other WooCommerce API endpoints.
This is my sample API looks like in which I want to check basic authentication.
// 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');
}
I have checked this 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 this urls but I have not found yet proper method or filter or tutorial yet to accomplish my requirements.
Can someone at-least guide me how can I add authentication here .. any suggestion will be highly appreciated.
Thanks
Upvotes: 2
Views: 3378
Reputation: 1242
OK Guys.. Eventually I made authentication in my custom endpoint APIs using JWT Authentication for WP REST API.
Thanks everyone for help , support and guidance.
Upvotes: 1
Reputation: 4372
In this case you can use the permission_callback
key:
// 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;
}
Full Documentation is here - https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/
Upvotes: 4