概要
woocommerce_webhook_delivery
アクションフックは、WooCommerce においてウェブフックが正常に配信されるたびに発火します。このアクションを使用することで、特定のイベントが発生した際に追加の処理を行うことが可能です。主に以下のような機能を実装する際に利用されます。
- ウェブフックレスポンスのログ記録
- 配信失敗時のリトライ処理
- カスタム通知の送信(例:Slackなどへの通知)
- 外部システムとのデータ同期
- データの検証とエラー処理
- ステータスの監視とロギング
構文
do_action('woocommerce_webhook_delivery', $order_id, $webhook_id, $response);
パラメータ
$order_id
(int) – 注文の ID。$webhook_id
(int) – ウェブフックの ID。$response
(array) – 配信時のレスポンスデータ。
戻り値
このアクションフック自体は値を返しません。
使用可能なプラグインのバージョン
- WooCommerce のバージョン: 3.0以降
- WordPress のバージョン: 4.7以降
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | |
wp | |
template_redirect | |
get_header | |
wp_head |
サンプルコード
サンプルコード 1: ウェブフックの配信をログに記録
add_action('woocommerce_webhook_delivery', 'log_webhook_delivery', 10, 3);
function log_webhook_delivery($order_id, $webhook_id, $response) {
$log_message = "Webhook delivered for Order ID: {$order_id}, Webhook ID: {$webhook_id} with response: " . json_encode($response);
error_log($log_message);
}
このコードは、ウェブフック配信が行われるたびに、指定された内容をエラーログに記録します。
サンプルコード 2: ウェブフック配信失敗のリトライ
add_action('woocommerce_webhook_delivery', 'retry_failed_webhook_delivery', 10, 3);
function retry_failed_webhook_delivery($order_id, $webhook_id, $response) {
if (isset($response['status']) && $response['status'] !== 'success') {
// リトライ処理を実装
send_webhook($order_id, $webhook_id);
}
}
この例では、ウェブフックの配信が成功しなかった場合に、リトライ用の関数を呼び出します。
サンプルコード 3: Slack への通知を送信
add_action('woocommerce_webhook_delivery', 'send_slack_notification', 10, 3);
function send_slack_notification($order_id, $webhook_id, $response) {
$message = "Webhook delivered for Order ID: {$order_id}. Response: " . json_encode($response);
wp_remote_post('https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK', [
'body' => json_encode(['text' => $message]),
'headers' => ['Content-Type' => 'application/json'],
]);
}
このコードは、ウェブフックの配信成功後に指定されたSlackウェブフックに通知を送信します。
サンプルコード 4: データの検証とエラーハンドリング
add_action('woocommerce_webhook_delivery', 'validate_webhook_data', 10, 3);
function validate_webhook_data($order_id, $webhook_id, $response) {
if (!isset($response['data'])) {
// エラーハンドリング
error_log("Invalid data received for Order ID: {$order_id}");
}
}
このコードは、ウェブフックのレスポンスにデータが含まれていない場合のエラーハンドリングを実装しています。
サンプルコード 5: 配信ステータスの更新
add_action('woocommerce_webhook_delivery', 'update_delivery_status', 10, 3);
function update_delivery_status($order_id, $webhook_id, $response) {
// データベースのステータスを更新
update_post_meta($order_id, '_webhook_delivery_status', $response['status']);
}
この例では、ウェブフックの配信後、注文のメタデータにステータスを更新します。