Webhook.php
| 1 | <?php |
| 2 | |
| 3 | namespace SureCart\Models; |
| 4 | |
| 5 | /** |
| 6 | * Price model |
| 7 | */ |
| 8 | class Webhook extends Model { |
| 9 | /** |
| 10 | * Rest API endpoint |
| 11 | * |
| 12 | * @var string |
| 13 | */ |
| 14 | protected $endpoint = 'webhook_endpoints'; |
| 15 | |
| 16 | /** |
| 17 | * Object name |
| 18 | * |
| 19 | * @var string |
| 20 | */ |
| 21 | protected $object_name = 'webhook_endpoint'; |
| 22 | |
| 23 | /** |
| 24 | * Get the listener url. |
| 25 | * |
| 26 | * @return string |
| 27 | */ |
| 28 | protected function getListenerUrl() { |
| 29 | return get_home_url( null, '/surecart/webhooks', is_ssl() ? 'https' : 'http' ); |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * Register webhook for this site |
| 34 | * |
| 35 | * @return $this|false |
| 36 | */ |
| 37 | protected function register() { |
| 38 | $existing = $this->findExisting(); |
| 39 | |
| 40 | if ( $existing ) { |
| 41 | return $existing; |
| 42 | } |
| 43 | |
| 44 | return $this->create( |
| 45 | [ |
| 46 | 'description' => 'Main webhook for SureCart', |
| 47 | 'enabled' => true, |
| 48 | 'destination' => 'wordpress', |
| 49 | 'url' => $this->getListenerUrl(), |
| 50 | 'webhook_events' => [ |
| 51 | // 'cancellation_act.updated', |
| 52 | // 'customer.created', |
| 53 | // 'customer.updated', |
| 54 | // 'order.created', |
| 55 | // 'order.made_processing', |
| 56 | // 'order.paid', // In doc |
| 57 | // 'order.payment_failed', |
| 58 | 'purchase.created', |
| 59 | 'purchase.invoked', |
| 60 | 'purchase.updated', |
| 61 | 'purchase.revoked', |
| 62 | // 'refund.created', |
| 63 | // 'refund.succeeded', // In doc |
| 64 | // 'subscription.canceled', // In doc |
| 65 | // 'subscription.created', |
| 66 | // 'subscription.completed', |
| 67 | // 'subscription.made_active', // In doc |
| 68 | // 'subscription.made_past_due', |
| 69 | // 'subscription.made_trialing', // In doc |
| 70 | 'subscription.renewed', // needed for AffiliateWP recurring referrals. |
| 71 | // 'subscription.updated', |
| 72 | ], |
| 73 | ] |
| 74 | ); |
| 75 | } |
| 76 | |
| 77 | /** |
| 78 | * Find existing webhook with the same listner url. |
| 79 | * |
| 80 | * @return \SureCart\Models\Webhook|false |
| 81 | */ |
| 82 | public function findExisting() { |
| 83 | $webhooks = $this->setPagination( [ 'per_page' => 100 ] )->get(); |
| 84 | if ( is_array( $webhooks ) && ! empty( $webhooks ) ) { |
| 85 | foreach ( $webhooks as $webhook ) { |
| 86 | if ( $webhook['url'] === $this->getListenerUrl() ) { |
| 87 | return $webhook; |
| 88 | } |
| 89 | } |
| 90 | } |
| 91 | return false; |
| 92 | } |
| 93 | } |
| 94 |