InternalNotificationDispatcher.php
87 lines
| 1 | <?php |
| 2 | |
| 3 | declare( strict_types = 1 ); |
| 4 | |
| 5 | namespace Automattic\WooCommerce\Internal\PushNotifications\Dispatchers; |
| 6 | |
| 7 | defined( 'ABSPATH' ) || exit; |
| 8 | |
| 9 | use Automattic\WooCommerce\Internal\PushNotifications\Notifications\Notification; |
| 10 | use Automattic\WooCommerce\Internal\PushNotifications\PushNotifications; |
| 11 | use Automattic\WooCommerce\StoreApi\Utilities\JsonWebToken; |
| 12 | |
| 13 | /** |
| 14 | * Fires a non-blocking POST to the internal REST endpoint with JSON-encoded |
| 15 | * notification data and a signed JWT. |
| 16 | * |
| 17 | * Called directly by PendingNotificationStore::dispatch_all() on shutdown. |
| 18 | * |
| 19 | * @internal |
| 20 | * @since 10.7.0 |
| 21 | */ |
| 22 | class InternalNotificationDispatcher { |
| 23 | |
| 24 | /** |
| 25 | * REST route for the send endpoint. |
| 26 | */ |
| 27 | const SEND_ENDPOINT = 'wc-push-notifications/send'; |
| 28 | |
| 29 | /** |
| 30 | * JWT expiry in seconds. |
| 31 | */ |
| 32 | const JWT_EXPIRY_SECONDS = 30; |
| 33 | |
| 34 | /** |
| 35 | * JSON-encodes notifications and fires a non-blocking POST to the internal |
| 36 | * REST endpoint. |
| 37 | * |
| 38 | * @param Notification[] $notifications The notifications to dispatch. |
| 39 | * @return void |
| 40 | * |
| 41 | * @since 10.7.0 |
| 42 | */ |
| 43 | public function dispatch( array $notifications ): void { |
| 44 | if ( empty( $notifications ) ) { |
| 45 | return; |
| 46 | } |
| 47 | |
| 48 | $encoded = array_map( fn ( Notification $notification ) => $notification->to_array(), $notifications ); |
| 49 | $body = wp_json_encode( array( 'notifications' => $encoded ) ); |
| 50 | |
| 51 | if ( false === $body ) { |
| 52 | wc_get_logger()->error( |
| 53 | 'Failed to JSON-encode push notification payload.', |
| 54 | array( 'source' => PushNotifications::FEATURE_NAME ) |
| 55 | ); |
| 56 | return; |
| 57 | } |
| 58 | |
| 59 | $token = JsonWebToken::create( |
| 60 | array( |
| 61 | 'iss' => get_site_url(), |
| 62 | 'exp' => time() + self::JWT_EXPIRY_SECONDS, |
| 63 | 'body_hash' => hash( 'sha256', $body ), |
| 64 | ), |
| 65 | wp_salt( 'auth' ) |
| 66 | ); |
| 67 | |
| 68 | /** |
| 69 | * The request is non-blocking so the response is not handled anywhere. |
| 70 | * If the request fails, the ActionScheduler safety net will pick up |
| 71 | * unsent notifications after 60 seconds. |
| 72 | */ |
| 73 | wp_remote_post( |
| 74 | rest_url( self::SEND_ENDPOINT ), |
| 75 | array( |
| 76 | 'blocking' => false, |
| 77 | 'timeout' => 1, |
| 78 | 'headers' => array( |
| 79 | 'Content-Type' => 'application/json', |
| 80 | 'Authorization' => 'Bearer ' . $token, |
| 81 | ), |
| 82 | 'body' => $body, |
| 83 | ) |
| 84 | ); |
| 85 | } |
| 86 | } |
| 87 |