So you’ve got your WooCommerce site humming along and you’re using REST API keys to integrate with all the cool tools and apps in your stack. But what if you want to get notified (like, instantly) when someone creates or updates an API key?
Maybe you’re building a custom dashboard. Or maybe you just like being in the loop like a security-savvy ninja. Either way, here’s how to do it.
🧠 The Backstory
WordPress doesn’t fire a built-in hook specifically when REST API keys are created or updated. But good news — we can hook into the relevant user meta actions and get the job done.
🛠️ Here’s How to Do It
Add the following code to your theme’s functions.php file or a custom plugin:
add_action( 'added_user_meta', 'wp_huh_track_api_key_creation', 10, 4 );
add_action( 'updated_user_meta', 'wp_huh_track_api_key_update', 10, 4 );
function wp_huh_track_api_key_creation( $meta_id, $user_id, $meta_key, $meta_value ) {
if ( $meta_key === '_woocommerce_api_consumer_key' ) {
// 🔔 Do your webhook magic here
wp_remote_post( 'https://your-webhook-url.com', [
'method' => 'POST',
'body' => json_encode([
'event' => 'api_key_created',
'user_id' => $user_id,
'key' => $meta_value,
]),
'headers' => [
'Content-Type' => 'application/json',
],
]);
}
}
function wp_huh_track_api_key_update( $meta_id, $user_id, $meta_key, $meta_value ) {
if ( $meta_key === '_woocommerce_api_consumer_key' ) {
// 🔔 Webhook on update
wp_remote_post( 'https://your-webhook-url.com', [
'method' => 'POST',
'body' => json_encode([
'event' => 'api_key_updated',
'user_id' => $user_id,
'key' => $meta_value,
]),
'headers' => [
'Content-Type' => 'application/json',
],
]);
}
}🧐 What’s Happening Here?
added_user_metaandupdated_user_metaare triggered when user metadata changes — REST API keys are stored that way.- We’re filtering by the meta key name:
_woocommerce_api_consumer_key. - Then we’re sending a webhook with
wp_remote_post()to your chosen endpoint.
🔐 Pro Tips
- Make sure your webhook endpoint is protected and only accepts requests from trusted sources.
- If you’re logging or storing keys, be very careful with security and GDPR compliance.
- You can log these webhook calls to a file during testing before going live.
🤔 Can We Do This Without Code?
Nope — not yet. WooCommerce doesn’t support this out-of-the-box. But hey, now you’ve got a custom solution!