php - WP rest api - POST endpoint and store in the user meta data
Get the solution ↓↓↓
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 thewordpress_url/xxx/v1/authkeys. It also needs to support https.
I am trying to add thisxxx/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 theconsumer_key,consumer_secret andkey_permissions in the user meta-data related to theuser_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 ifconsumer_key,consumer_secret andkey_permissions do not exist in the DB, we create the fields.
For now, I have added in thefunction.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
Answer
Solution:
If all you are missing is the DB store part then it's very easy with WP, you just need this:
// Load wp user object (if needed)
$user = new WP_User($user_id);
// or just save the data..
update_user_meta($user_id,'consumer_key',$consumer_key);
update_user_meta($user_id,'consumer_secret',$consumer_secret);
update_user_meta($user_id,'key_permissions',$key_permissions);
update_user_meta already does that check with missing -> create or existing -> update
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: a non-numeric value encountered in
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

