I am trying to create a custom endpoint on Wordpress to handle the WooCommerce authentication keys.
At high-level when you use rest api to generate authentication keys, those API keys will be sent back in a separate POST request.
So what happened is, my react website submit the authoziation request to WooCommerce/Wordpress headless server and the callback is the wordpress_url/xxx/v1/authkeys
. It also needs to support https.
I am trying to add this xxx/v1/authkeys
endpoint to wordpress and the purpose will be to extract the JSON data as below:
{
"key_id": 1,
"user_id": 123,
"consumer_key": "ck_xxxxxxxxxxxxxxxx",
"consumer_secret": "cs_xxxxxxxxxxxxxxxx",
"key_permissions": "read_write"
}
and store the consumer_key
, consumer_secret
and key_permissions
in the user meta-data related to the user_id
.
My goal is to be able to get the keys when I am pulling the user information including those meta-data.
By default those fields are new, So I need to make sure that if consumer_key
, consumer_secret
and key_permissions
do not exist in the DB, we create the fields.
For now, I have added in the function.php
:
function handle_woocommerce_keys($request){
$user_id = $request[user_id];
$consumer_key=$request[consumer_key];
$consumer_secret=$request[consumer_secret];
$key_permissions=$request[key_permissions];
/* search user_id in db and store the keys as meta_data */
$response = new WP_REST_Response();
$response->set_status(200);
return $response;
}
add_action('rest_api_init', function () {
register_rest_route( 'village/v1', 'authkeys',array(
'methods' => 'POST',
'callback' => 'handle_woocommerce_keys'
));
});
As I am newby in php/wordpress, I have no clue how to add data in the user database for a specific user_id
thanks for your help
If all you are missing is the DB store part then it's very easy with WP, you just need this:
update_user_meta already does that check with missing -> create or existing -> update