templates
1 year ago
SendinblueAccount.php
1 year ago
SendinblueApiClient.php
2 months ago
function.wp_mail.php
8 years ago
http-build-url.php
1 year ago
index.php
8 years ago
mailin.php
3 years ago
push-admin.php
5 months ago
push-amp.php
1 year ago
push-api.php
3 months ago
push-httpclient.php
1 year ago
push-public.php
1 year ago
push-settings.php
3 months ago
push-utils.php
5 months ago
push-woocommerce.php
11 months ago
sendinblue.php
3 years ago
sib-api-manager.php
1 year ago
sib-form-preview.php
2 years ago
sib-sms-code.php
5 months ago
table-forms.php
1 year ago
push-woocommerce.php
587 lines
| 1 | <?php |
| 2 | if (!defined( 'ABSPATH' )) { http_response_code(403); exit(); } |
| 3 | |
| 4 | |
| 5 | if ( ! class_exists('SIB_Push_WooCommerce')) { |
| 6 | |
| 7 | class SIB_Push_WooCommerce { |
| 8 | const CART_REMINDER_STRATEGY_LATEST = 'latest'; |
| 9 | const CART_REMINDER_STRATEGY_MOST_EXPENSIVE = 'most-expensive'; |
| 10 | const CART_REMINDER_STRATEGY_LEAST_EXPENSIVE = 'least-expensive'; |
| 11 | public static function cart_reminder_strategies() { |
| 12 | return array( |
| 13 | self::CART_REMINDER_STRATEGY_LATEST, |
| 14 | self::CART_REMINDER_STRATEGY_MOST_EXPENSIVE, |
| 15 | self::CART_REMINDER_STRATEGY_LEAST_EXPENSIVE, |
| 16 | ); |
| 17 | } |
| 18 | |
| 19 | const CART_REMINDER_DESTINATION_CART = 'cart'; |
| 20 | const CART_REMINDER_DESTINATION_CHECKOUT = 'checkout'; |
| 21 | const CART_REMINDER_DESTINATION_HOMEPAGE = 'homepage'; |
| 22 | public static function cart_reminder_destinations() { |
| 23 | return array( |
| 24 | self::CART_REMINDER_DESTINATION_CART, |
| 25 | self::CART_REMINDER_DESTINATION_CHECKOUT, |
| 26 | self::CART_REMINDER_DESTINATION_HOMEPAGE, |
| 27 | ); |
| 28 | } |
| 29 | |
| 30 | /** @var WooCommerce */ |
| 31 | static $woocommerce; |
| 32 | static function init() { |
| 33 | self::$woocommerce = SIB_Push_Utils::get_woocommerce(); |
| 34 | if (!self::$woocommerce) return; |
| 35 | $cart_change_hooks = array( |
| 36 | 'woocommerce_add_to_cart', |
| 37 | 'woocommerce_cart_item_removed', |
| 38 | 'woocommerce_cart_item_restored', |
| 39 | 'woocommerce_cart_item_set_quantity', |
| 40 | 'woocommerce_cart_emptied', |
| 41 | 'woocommerce_thankyou', |
| 42 | ); |
| 43 | // Exit event on single product page |
| 44 | add_action('woocommerce_before_single_product', array(__CLASS__, 'before_single_product')); |
| 45 | |
| 46 | // Send GOAL_1 on thankyou |
| 47 | add_action('wp_head', array(__CLASS__, 'send_thankyou_event'), 10, 4); |
| 48 | |
| 49 | // Individual hooks used to fire standard WonderPush E-commerce events |
| 50 | add_action('woocommerce_add_to_cart', array(__CLASS__, 'add_to_cart')); |
| 51 | add_action('woocommerce_remove_cart_item', array(__CLASS__, 'remove_from_cart')); |
| 52 | add_action('woocommerce_cart_item_restored', array(__CLASS__, 'add_to_cart')); |
| 53 | add_action('woocommerce_thankyou', array(__CLASS__, 'purchase')); |
| 54 | |
| 55 | // Order status changes to send confirmation and shipping notifications |
| 56 | add_action('woocommerce_order_status_changed', array(__CLASS__, 'order_status_changed'), 10, 4); |
| 57 | } |
| 58 | |
| 59 | public static function add_to_cart($cart_item_key) { |
| 60 | self::send_cart_event('AddToCart', $cart_item_key); |
| 61 | } |
| 62 | |
| 63 | public static function remove_from_cart($cart_item_key) { |
| 64 | self::send_cart_event('RemoveFromCart', $cart_item_key); |
| 65 | } |
| 66 | |
| 67 | protected static function send_cart_event($event_type, $cart_item_key) { |
| 68 | if (!self::$woocommerce || !self::$woocommerce->cart) return; |
| 69 | $cart = self::$woocommerce->cart->get_cart(); |
| 70 | if (!$cart) return; |
| 71 | $item = $cart[$cart_item_key]; |
| 72 | if (!$item) return; |
| 73 | $product = $item['data']; |
| 74 | $settings = SIB_Push_Settings::getSettings(); |
| 75 | $credentials = $settings->getWonderPushCredentials(); |
| 76 | if (!$credentials) return; |
| 77 | global $wp; |
| 78 | $payload = array( |
| 79 | 'object_product' => self::event_payload_from_product($product), |
| 80 | 'string_url' => \WonderPush\Util\ArrayUtil::getIfSet($_SERVER, 'HTTP_REFERER') ?: ($wp ? home_url($wp->request) : null), |
| 81 | ); |
| 82 | try { |
| 83 | SIB_Push_Utils::track_event($credentials, $event_type, $payload); |
| 84 | } catch (Exception $e) { |
| 85 | SIB_Push_Utils::log_warn("Could not track event", $e); |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | public static function before_single_product() { |
| 90 | $product_id = get_the_ID(); |
| 91 | if (!$product_id) return; |
| 92 | $product = wc_get_product( $product_id ); |
| 93 | if (!($product instanceof WC_Product)) return; |
| 94 | $product_array = self::event_payload_from_product($product); |
| 95 | if (!$product_array) return; |
| 96 | $json_options = 0; |
| 97 | if (defined('JSON_INVALID_UTF8_SUBSTITUTE')) $json_options |= JSON_INVALID_UTF8_SUBSTITUTE; |
| 98 | else if (defined('JSON_PARTIAL_OUTPUT_ON_ERROR')) $json_options |= JSON_PARTIAL_OUTPUT_ON_ERROR; |
| 99 | $product_json = json_encode($product_array, $json_options); |
| 100 | $json_last_error = json_last_error(); |
| 101 | if ($json_last_error !== JSON_ERROR_NONE) { |
| 102 | if (function_exists('json_last_error_msg')) { |
| 103 | $msg = json_last_error_msg(); |
| 104 | } else { |
| 105 | $msg = ''; |
| 106 | } |
| 107 | SIB_Push_Utils::log_warn("Could not json_encode product array. code:" . $json_last_error . " msg:" . $msg, $product_array); |
| 108 | } |
| 109 | if ($product_json === false) return; |
| 110 | ?> |
| 111 | <script type="text/javascript"> |
| 112 | var lastExitEventDate; |
| 113 | var lastExitEventUrl; |
| 114 | document.addEventListener('mouseout', function(e) { |
| 115 | if (!e.toElement && !e.relatedTarget) { |
| 116 | if (lastExitEventUrl === window.location.href |
| 117 | && lastExitEventDate |
| 118 | && (+new Date() - lastExitEventDate.getTime()) < 5 * 60000) { |
| 119 | return; |
| 120 | } |
| 121 | lastExitEventDate = new Date(); |
| 122 | lastExitEventUrl = window.location.href; |
| 123 | window.WonderPush = window.WonderPush || []; |
| 124 | window.WonderPush.push(function() { |
| 125 | window.WonderPush.trackEvent('Exit', { |
| 126 | object_product: <?php echo $product_json; ?>, |
| 127 | string_url: window.location.href, |
| 128 | }); |
| 129 | }); |
| 130 | } |
| 131 | }); |
| 132 | </script> |
| 133 | <?php |
| 134 | } |
| 135 | |
| 136 | public static function purchase($order_id) { |
| 137 | $order = wc_get_order( $order_id ); |
| 138 | if (!($order instanceof WC_Order)) return; |
| 139 | $settings = SIB_Push_Settings::getSettings(); |
| 140 | $credentials = $settings ? $settings->getWonderPushCredentials() : null; |
| 141 | if (!$credentials) return; |
| 142 | try { |
| 143 | SIB_Push_Utils::track_event($credentials, 'Purchase', array( |
| 144 | 'float_totalAmount' => (float)$order->get_total(), |
| 145 | )); |
| 146 | } catch (Exception $e) { |
| 147 | SIB_Push_Utils::log_warn("Could not track event: ", $e); |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | public static function send_thankyou_event() { |
| 152 | if( !is_wc_endpoint_url( 'order-received' ) ) return; |
| 153 | $settings = SIB_Push_Settings::getSettings(); |
| 154 | if ($settings->getDisableThankYouEvent()) return; |
| 155 | $eventName = $settings->getThankYouEventName() ?: 'GOAL_1'; |
| 156 | $args = array('trackEvent', $eventName); |
| 157 | ?><script>WonderPush = window.WonderPush || []; WonderPush.push(<?php echo json_encode($args) ?>)</script><?php |
| 158 | } |
| 159 | |
| 160 | public static function order_status_changed($order_id, $from_status, $to_status, $order) { |
| 161 | try { |
| 162 | if (!SIB_Push_Utils::get_push_application()) return; |
| 163 | } catch (Exception $t) { |
| 164 | SIB_Push_Utils::log_warn('Could not get application', $t); |
| 165 | return; |
| 166 | } |
| 167 | $settings = SIB_Push_Settings::getSettings(); |
| 168 | |
| 169 | // Order complete notifications |
| 170 | if ($to_status === 'completed' && $from_status === 'processing') { |
| 171 | try { |
| 172 | if (!$settings->getEnableOrderCompleteNotifications()) return; |
| 173 | |
| 174 | $customer_id = !empty($order) ? $order->get_user_id() : null; |
| 175 | if (!$customer_id) return; |
| 176 | |
| 177 | // Did we send a notification already? |
| 178 | $meta_name = "order_status_complete_order_{$order_id}"; |
| 179 | $meta_value = get_user_meta($customer_id, $meta_name, true); |
| 180 | if ($meta_value) { |
| 181 | SIB_Push_Utils::log_debug('Discarding duplicate shipping notification'); |
| 182 | return; |
| 183 | } |
| 184 | |
| 185 | $message = $settings->getOrderCompleteNotificationsMessage() ?: 'We\'ve just shipped your order.'; |
| 186 | $success = self::send_order_notification($order, $message); |
| 187 | if ($success) { |
| 188 | // Avoid sending twice |
| 189 | update_user_meta($customer_id, $meta_name, true); |
| 190 | } |
| 191 | } catch (Exception $e) { |
| 192 | SIB_Push_Utils::log_warn('Caught Exception', $e); |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | if (($to_status === 'processing' && $from_status === 'pending') // Most goods |
| 197 | || ($to_status === 'completed' && $from_status === 'pending')) { // Digital goods |
| 198 | |
| 199 | try { |
| 200 | if (!$settings->getEnableOrderProcessingNotifications()) return; |
| 201 | |
| 202 | $customer_id = !empty($order) ? $order->get_user_id() : null; |
| 203 | if (!$customer_id) return; |
| 204 | |
| 205 | // Did we send a notification already? |
| 206 | $meta_name = "order_status_processing_order_{$order_id}"; |
| 207 | $meta_value = get_user_meta($customer_id, $meta_name, true); |
| 208 | if ($meta_value) { |
| 209 | SIB_Push_Utils::log_debug('Discarding duplicate order confirmation notification'); |
| 210 | return; |
| 211 | } |
| 212 | |
| 213 | $message = $settings->getOrderProcessingNotificationsMessage() ?: 'We\'re preparing your order.'; |
| 214 | $success = self::send_order_notification($order, $message); |
| 215 | if ($success) { |
| 216 | // Avoid sending twice |
| 217 | update_user_meta($customer_id, $meta_name, true); |
| 218 | } |
| 219 | } catch (Exception $e) { |
| 220 | SIB_Push_Utils::log_warn('Caught Exception', $e); |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | /** |
| 226 | * Sends a notification to the customer behind the order with a link to the order page and the image of a product. |
| 227 | * @param $order |
| 228 | * @param $message |
| 229 | * @return bool True on success |
| 230 | */ |
| 231 | private static function send_order_notification($order, $message) { |
| 232 | try { |
| 233 | $settings = SIB_Push_Settings::getSettings(); |
| 234 | $credentials = $settings->getWonderPushCredentials(); |
| 235 | |
| 236 | if (!$credentials) return false; |
| 237 | |
| 238 | $user = !empty($order) ? $order->get_user() : null; |
| 239 | if (!$user) return false; |
| 240 | if (empty($user->user_email)) return false; |
| 241 | $user_email = $user->user_email; |
| 242 | |
| 243 | // Find a product image |
| 244 | $product_icon_url = self::get_order_icon($order); |
| 245 | $product_image_url = self::get_order_image($order); |
| 246 | |
| 247 | try { |
| 248 | $app = SIB_Push_Utils::get_push_application(); |
| 249 | } catch (Exception $t) { |
| 250 | SIB_Push_Utils::log_warn('Could not get application', $t); |
| 251 | $app = null; |
| 252 | } |
| 253 | $url_params = $app ? $app->getUrlParameters() : (object)array(); |
| 254 | $site_title = SIB_Push_Utils::decode_entities($settings->getNotificationTitle() ?: get_bloginfo('name')); |
| 255 | |
| 256 | $notification = new \WonderPush\Obj\Notification(); |
| 257 | $alert = new \WonderPush\Obj\NotificationAlert(); |
| 258 | $notification->setAlert($alert); |
| 259 | $order_view_url = $order->get_view_order_url(); |
| 260 | $target_url = SIB_Push_Utils::inject_query_string_params($order_view_url, $url_params); |
| 261 | $alert->setTargetUrl($target_url); |
| 262 | $alert->setTitle($site_title); |
| 263 | $alert->setText($message); |
| 264 | |
| 265 | $ios = new \WonderPush\Obj\NotificationAlertIos(); |
| 266 | $ios->setSound('default'); |
| 267 | $alert->setIos($ios); |
| 268 | $web = new \WonderPush\Obj\NotificationAlertWeb(); |
| 269 | $alert->setWeb($web); |
| 270 | if ($product_icon_url) $web->setIcon($product_icon_url); |
| 271 | if ($product_image_url) $web->setImage($product_image_url); |
| 272 | $params = new \WonderPush\Params\DeliveriesCreateParams(); |
| 273 | $params->setInheritUrlParameters(true); |
| 274 | $params->setNotification($notification); |
| 275 | $params->setTargetUserIds(array($user_email)); |
| 276 | $params->setDeliveryDate((time() + 10) * 1000); |
| 277 | |
| 278 | // Send the notification |
| 279 | SIB_Push_Utils::log_debug('Sending WonderPush notification', $params); |
| 280 | $wonderPushClient = new \WonderPush\WonderPush($credentials); |
| 281 | $response = $wonderPushClient->deliveries()->create($params); |
| 282 | |
| 283 | if ($response->isSuccess()) { |
| 284 | return true; |
| 285 | } else { |
| 286 | SIB_Push_Utils::log_warn('Could not send WonderPush order confirmation notification.'); |
| 287 | return false; |
| 288 | } |
| 289 | } catch (Exception $e) { |
| 290 | SIB_Push_Utils::log_warn('Caught Exception', $e); |
| 291 | return false; |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | private static function get_order_assets($order) { |
| 296 | $result = array(); |
| 297 | foreach ($order->get_items() as $item) { |
| 298 | if ($item->is_type('line_item')) { |
| 299 | $product = $item->get_product(); |
| 300 | $image_id = null; |
| 301 | if ($product->get_image_id()) $image_id = $product->get_image_id(); |
| 302 | else if ($product->get_parent_id()) { |
| 303 | $parent = wc_get_product($product->get_parent_id()); |
| 304 | if ($parent) { |
| 305 | $image_id = $parent->get_image_id(); |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | if ($image_id) { |
| 310 | // Higher resolution (2x retina, + a little more) for the notification small icon |
| 311 | $thumbnail_sized_images_array = wp_get_attachment_image_src($image_id, array(192, 192), true); |
| 312 | // Much higher resolution for the notification large image |
| 313 | $large_sized_images_array = wp_get_attachment_image_src($image_id, 'large', true); |
| 314 | if (!empty($thumbnail_sized_images_array)) $result['product_icon_url'] = $thumbnail_sized_images_array[0]; |
| 315 | if (!empty($large_sized_images_array)) $result['product_image_url'] = $large_sized_images_array[0]; |
| 316 | } |
| 317 | |
| 318 | // We want at least an icon |
| 319 | if (isset($result['product_icon_url'])) break; |
| 320 | } |
| 321 | } |
| 322 | return $result; |
| 323 | } |
| 324 | |
| 325 | protected static function get_order_icon($order) { |
| 326 | $assets = self::get_order_assets($order); |
| 327 | return isset($assets['product_icon_url']) ? $assets['product_icon_url'] : null; |
| 328 | } |
| 329 | |
| 330 | protected static function get_order_image($order) { |
| 331 | $assets = self::get_order_assets($order); |
| 332 | return isset($assets['product_image_url']) ? $assets['product_image_url'] : null; |
| 333 | } |
| 334 | |
| 335 | protected static function sanitize($str) { |
| 336 | if (!is_string($str)) return null; |
| 337 | if (!$str) return $str; |
| 338 | $html_entity_decode_flags = ENT_QUOTES; |
| 339 | if (defined('ENT_HTML5')) $html_entity_decode_flags |= ENT_HTML5; // Whether to decode ' |
| 340 | $stripped = html_entity_decode(strip_tags($str), $html_entity_decode_flags); |
| 341 | $stripped = preg_replace('/\s+/', ' ', $stripped); |
| 342 | return strlen($stripped) > 120 ? substr($stripped, 0, 119) . '…' : $stripped; |
| 343 | } |
| 344 | |
| 345 | protected static function event_payload_from_product($product) { |
| 346 | if (!($product instanceof WC_Product)) return null; |
| 347 | $settings = SIB_Push_Settings::getSettings(); |
| 348 | $pictureUrl = null; |
| 349 | if ( $product->get_image_id() ) { |
| 350 | $pictureUrl = wp_get_attachment_url($product->get_image_id()); |
| 351 | } elseif ( $product->get_parent_id() ) { |
| 352 | $parent_product = wc_get_product( $product->get_parent_id() ); |
| 353 | if ( $parent_product && $parent_product->get_image_id() ) { |
| 354 | $pictureUrl = wp_get_attachment_url($parent_product->get_image_id()); |
| 355 | } |
| 356 | } |
| 357 | $availability = null; |
| 358 | if (is_array($product->get_availability())) { |
| 359 | $availabilityArray = $product->get_availability(); |
| 360 | switch ( $availabilityArray['class'] ) { |
| 361 | case 'out-of-stock': |
| 362 | $availability = 'OutOfStock'; |
| 363 | break; |
| 364 | case 'in-stock': |
| 365 | $availability = 'InStock'; |
| 366 | break; |
| 367 | case 'available-on-backorder': |
| 368 | $availability = 'BackOrder'; |
| 369 | break; |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | $currency = null; |
| 374 | if (function_exists('get_woocommerce_currency')) { |
| 375 | $currency = get_woocommerce_currency(); |
| 376 | } |
| 377 | return array( |
| 378 | 'string_type' => 'Product', |
| 379 | 'string_image' => $pictureUrl && is_string($pictureUrl) ? $pictureUrl : null, |
| 380 | 'string_name' => $product->get_name() ? self::sanitize($product->get_name()): null, |
| 381 | 'string_description' => $product->get_description() ? self::sanitize($product->get_description()) : null, |
| 382 | 'string_sku' => $product->get_sku() && is_string($product->get_sku()) ? $product->get_sku() : null, |
| 383 | 'object_offers' => array( |
| 384 | 'string_type' => 'Offer', |
| 385 | 'float_price' => (float)$product->get_price(), |
| 386 | 'string_priceCurrency' => $currency && is_string($currency) ? $currency : null, |
| 387 | 'string_url' => $product->get_permalink() && is_string($product->get_permalink()) ? $product->get_permalink() : null, |
| 388 | 'string_availability' => $availability, |
| 389 | ) |
| 390 | ); |
| 391 | } |
| 392 | |
| 393 | /** |
| 394 | * @param WonderPush\BrevoAPIKeyV3Credentials $credentials |
| 395 | * @return string |
| 396 | */ |
| 397 | protected static function get_cart_reminder_campaign_cache_key($credentials) { |
| 398 | return "sib_push_cart_campaign_" . $credentials->apiKey; |
| 399 | } |
| 400 | |
| 401 | protected static function get_cart_reminder_campaign($maxAge = null, $forceFetch = false) { |
| 402 | // Check creds |
| 403 | $settings = SIB_Push_Settings::getSettings(); |
| 404 | $credentials = $settings->getWonderPushCredentials(); |
| 405 | if (!$credentials) throw new SIB_Push_MissingCredentialsException('No push credentials'); |
| 406 | $campaignId = $settings->getCartReminderCampaignId(); |
| 407 | if (!$campaignId) return null; |
| 408 | |
| 409 | // Cached value ? |
| 410 | $cache_key = self::get_cart_reminder_campaign_cache_key($credentials); |
| 411 | $cached = $forceFetch ? null : get_transient($cache_key); |
| 412 | $now = time(); |
| 413 | if ($cached && is_array($cached)) { |
| 414 | $campaign = isset($cached['campaign']) ? $cached['campaign'] : null; |
| 415 | $ts = isset($cached['ts']) ? $cached['ts'] : 0; |
| 416 | if ($maxAge === null || $maxAge > ($now - $ts)) { |
| 417 | if ($campaign instanceof \WonderPush\Obj\Campaign) { |
| 418 | if ($campaign->getId() === $settings->getCartReminderCampaignId()) { |
| 419 | // SIB_Push_Utils::log_debug('Getting cart reminder campaign from cache', $campaign->getId(), 'key', $cache_key, 'maxAge', $maxAge, 'ts', $ts, 'now', $now); |
| 420 | return $campaign; |
| 421 | } |
| 422 | // Continue to network |
| 423 | } else { |
| 424 | // It's not a campaign object |
| 425 | // SIB_Push_Utils::log_debug('Getting cart reminder campaign from cache (null)', $campaign, 'key', $cache_key, 'maxAge', $maxAge, 'ts', $ts, 'now', $now); |
| 426 | return null; |
| 427 | } |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | // SIB_Push_Utils::log_debug('Getting cart reminder campaign from network', $cache_key, 'forceFetch', $forceFetch); |
| 432 | // Check access token with the API |
| 433 | $wp = SIB_Push_Utils::management_api_client($credentials); |
| 434 | try { |
| 435 | $campaign = $wp->campaigns()->get($campaignId, array('expand' => 'notifications,segment')); |
| 436 | if ($campaign) { |
| 437 | self::update_cart_reminder_campaign_cache($campaign); |
| 438 | return $campaign; |
| 439 | } |
| 440 | // Do not cache misses |
| 441 | self::clear_cart_reminder_campaign_cache(); |
| 442 | return null; |
| 443 | } catch (\WonderPush\Errors\Server $e) { |
| 444 | if ($e->getResponse() && $e->getResponse()->getStatusCode() === 404) { |
| 445 | SIB_Push_Utils::log_warn('Cart reminder campaign not found, removing cartReminderCampaignId in settings'); |
| 446 | $settings->setCartReminderCampaignId(null); |
| 447 | $settings->save(); |
| 448 | } else { |
| 449 | throw $e; |
| 450 | } |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | protected static function update_cart_reminder_campaign_cache($campaign) { |
| 455 | // Check creds |
| 456 | $settings = SIB_Push_Settings::getSettings(); |
| 457 | $credentials = $settings->getWonderPushCredentials(); |
| 458 | if (!$credentials) throw new SIB_Push_MissingCredentialsException('No push credentials'); |
| 459 | // Cache value |
| 460 | $cache_key = self::get_cart_reminder_campaign_cache_key($credentials); |
| 461 | set_transient($cache_key, array('ts' => time(), 'campaign' => $campaign), $campaign === 'error' ? 300 : 0); |
| 462 | } |
| 463 | |
| 464 | public static function clear_cart_reminder_campaign_cache() { |
| 465 | // Check creds |
| 466 | $settings = SIB_Push_Settings::getSettings(); |
| 467 | $credentials = $settings->getWonderPushCredentials(); |
| 468 | if (!$credentials) throw new SIB_Push_MissingCredentialsException('No push credentials'); |
| 469 | $cache_key = self::get_cart_reminder_campaign_cache_key($credentials); |
| 470 | delete_transient($cache_key); |
| 471 | } |
| 472 | |
| 473 | public static function ensure_cart_reminder_campaign_exists($forceFetch = false) { |
| 474 | if (!self::$woocommerce) return null; |
| 475 | if (!SIB_Push_Utils::is_push_active()) return null; |
| 476 | $settings = SIB_Push_Settings::getSettings(); |
| 477 | $credentials = $settings->getWonderPushCredentials(); |
| 478 | if (!$credentials) throw new SIB_Push_MissingCredentialsException('No push credentials'); |
| 479 | $wp = SIB_Push_Utils::management_api_client($credentials); |
| 480 | |
| 481 | if (!$forceFetch) { |
| 482 | $campaign = self::get_cart_reminder_campaign(null); |
| 483 | if ($campaign) return $campaign; |
| 484 | } |
| 485 | |
| 486 | $campaignId = $settings->getCartReminderCampaignId(); |
| 487 | if ($campaignId) { |
| 488 | // Check that the campaign exists |
| 489 | try { |
| 490 | return $wp->campaigns()->get($campaignId, array('expand' => 'notifications,segment')); |
| 491 | } catch (WonderPush\Errors\Server $e) { |
| 492 | if ($e->getResponse() && $e->getResponse()->getStatusCode() === 404) { |
| 493 | // Campaign not found |
| 494 | $campaignId = null; |
| 495 | } else { |
| 496 | throw $e; |
| 497 | } |
| 498 | } |
| 499 | } |
| 500 | // Create the campaign |
| 501 | $campaign = new \WonderPush\Obj\Campaign(json_decode(self::cart_reminder_json())); |
| 502 | $params = new WonderPush\Params\CreateCampaignParams(); |
| 503 | $params->setChannel('alert'); |
| 504 | $params->setViewId(''); |
| 505 | $params->setCampaign($campaign); |
| 506 | $params->setNotifications($campaign->getNotifications()); |
| 507 | $params->setQuery('null'); |
| 508 | try { |
| 509 | $response = $wp->campaigns()->create($params); |
| 510 | $campaign = $response->getCampaign(); |
| 511 | $settings->setCartReminderCampaignId($campaign->getId()); |
| 512 | $settings->save(); |
| 513 | return $campaign; |
| 514 | |
| 515 | } catch (\WonderPush\Errors\Server $e) { |
| 516 | SIB_Push_Utils::log_warn('Could not create cart reminder campaign', $e); |
| 517 | throw $e; |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | public static function cart_reminder_enabled() { |
| 522 | // NOTE: deactivate woocommerce |
| 523 | return false; |
| 524 | // $campaign = self::get_cart_reminder_campaign(300); |
| 525 | // return $campaign && $campaign->getState() === 'on'; |
| 526 | } |
| 527 | |
| 528 | /** |
| 529 | * @return string |
| 530 | */ |
| 531 | private static function cart_reminder_json() { |
| 532 | $campaignTitle = json_encode(__('Cart Reminder', 'mailin')); |
| 533 | $notificationText = json_encode(__('Your cart is about to expire! Don\'t miss out the brand you love! 😍', 'mailin')); |
| 534 | $notificationTitle = json_encode('🛒 {{event.custom.object_product.string_name}}'); |
| 535 | $startDate = json_encode(time() * 1000); |
| 536 | $campaignBuilder = json_encode(\WonderPush\Obj\Campaign::CAMPAIGN_BUILDER_BREVO_WORDPRESS_PLUGIN); |
| 537 | return <<<JSON |
| 538 | { |
| 539 | "name": {$campaignTitle}, |
| 540 | "state": "off", |
| 541 | "channels": [ |
| 542 | "alert" |
| 543 | ], |
| 544 | "segmentId": "@ALL", |
| 545 | "campaignBuilder": {$campaignBuilder}, |
| 546 | "scheduling": { |
| 547 | "eventType": "AddToCart", |
| 548 | "cancelEventTypes": [ |
| 549 | "Purchase" |
| 550 | ], |
| 551 | "type": "event", |
| 552 | "startDate": {$startDate}, |
| 553 | "delay": "PT5M" |
| 554 | }, |
| 555 | "notifications": [ |
| 556 | { |
| 557 | "alert": { |
| 558 | "text": {$notificationText}, |
| 559 | "title": {$notificationTitle}, |
| 560 | "targetUrl": "{{event.custom.object_product.object_offers.string_url | default: event.custom.string_url | default: \"wonderpush://notificationOpen/default\" }}", |
| 561 | "ios": { |
| 562 | "attachments": [ |
| 563 | { |
| 564 | "url": "{{event.custom.object_product.string_image}}", |
| 565 | "type": "image/png" |
| 566 | } |
| 567 | ] |
| 568 | }, |
| 569 | "android": { |
| 570 | "type": "bigPicture", |
| 571 | "largeIcon": "{{event.custom.object_product.string_image}}", |
| 572 | "bigPicture": "{{event.custom.object_product.string_image}}", |
| 573 | "bigLargeIcon": null |
| 574 | }, |
| 575 | "web": { |
| 576 | "icon": "{{event.custom.object_product.string_image}}" |
| 577 | } |
| 578 | } |
| 579 | } |
| 580 | ] |
| 581 | } |
| 582 | JSON; |
| 583 | } |
| 584 | } |
| 585 | |
| 586 | } |
| 587 |