WC_API_Webhooks::create_webhook( array $data )
Create an webhook
Description Description
Parameters Parameters
- $data
-
(Required) parsed webhook data
Return Return
(array|WP_Error)
Source Source
File: includes/legacy/api/v2/class-wc-api-webhooks.php
public function create_webhook( $data ) { try { if ( ! isset( $data['webhook'] ) ) { throw new WC_API_Exception( 'woocommerce_api_missing_webhook_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'webhook' ), 400 ); } $data = $data['webhook']; // permission check if ( ! current_user_can( 'manage_woocommerce' ) ) { throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_webhooks', __( 'You do not have permission to create webhooks.', 'woocommerce' ), 401 ); } $data = apply_filters( 'woocommerce_api_create_webhook_data', $data, $this ); // validate topic if ( empty( $data['topic'] ) || ! wc_is_webhook_valid_topic( strtolower( $data['topic'] ) ) ) { throw new WC_API_Exception( 'woocommerce_api_invalid_webhook_topic', __( 'Webhook topic is required and must be valid.', 'woocommerce' ), 400 ); } // validate delivery URL if ( empty( $data['delivery_url'] ) || ! wc_is_valid_url( $data['delivery_url'] ) ) { throw new WC_API_Exception( 'woocommerce_api_invalid_webhook_delivery_url', __( 'Webhook delivery URL must be a valid URL starting with http:// or https://', 'woocommerce' ), 400 ); } $webhook_data = apply_filters( 'woocommerce_new_webhook_data', array( 'post_type' => 'shop_webhook', 'post_status' => 'publish', 'ping_status' => 'closed', 'post_author' => get_current_user_id(), 'post_password' => 'webhook_' . wp_generate_password(), 'post_title' => ! empty( $data['name'] ) ? $data['name'] : sprintf( __( 'Webhook created on %s', 'woocommerce' ), strftime( _x( '%b %d, %Y @ %I:%M %p', 'Webhook created on date parsed by strftime', 'woocommerce' ) ) ), ), $data, $this ); $webhook = new WC_Webhook(); $webhook->set_name( $webhook_data['post_title'] ); $webhook->set_user_id( $webhook_data['post_author'] ); $webhook->set_status( 'publish' === $webhook_data['post_status'] ? 'active' : 'disabled' ); $webhook->set_topic( $data['topic'] ); $webhook->set_delivery_url( $data['delivery_url'] ); $webhook->set_secret( ! empty( $data['secret'] ) ? $data['secret'] : wp_generate_password( 50, true, true ) ); $webhook->set_api_version( 'legacy_v3' ); $webhook->save(); $webhook->deliver_ping(); // HTTP 201 Created $this->server->send_status( 201 ); do_action( 'woocommerce_api_create_webhook', $webhook->get_id(), $this ); return $this->get_webhook( $webhook->get_id() ); } catch ( WC_API_Exception $e ) { return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) ); } }
Changelog Changelog
Version | Description |
---|---|
2.2 | Introduced. |