Webhook.php
| 1 | <?php |
| 2 | |
| 3 | namespace SureCart\Models; |
| 4 | |
| 5 | use SureCart\Support\Encryption; |
| 6 | |
| 7 | /** |
| 8 | * Price model |
| 9 | */ |
| 10 | class Webhook extends Model { |
| 11 | /** |
| 12 | * Rest API endpoint |
| 13 | * |
| 14 | * @var string |
| 15 | */ |
| 16 | protected $endpoint = 'webhook_endpoints'; |
| 17 | |
| 18 | /** |
| 19 | * Object name |
| 20 | * |
| 21 | * @var string |
| 22 | */ |
| 23 | protected $object_name = 'webhook_endpoint'; |
| 24 | |
| 25 | /** |
| 26 | * Get the listener url. |
| 27 | * |
| 28 | * @return string |
| 29 | */ |
| 30 | protected function getListenerUrl() { |
| 31 | return get_site_url( null, '/surecart/webhooks', is_ssl() ? 'https' : 'http' ); |
| 32 | } |
| 33 | |
| 34 | /** |
| 35 | * Register webhook for this site |
| 36 | * |
| 37 | * @return $this|false |
| 38 | */ |
| 39 | protected function register() { |
| 40 | $existing = $this->findExisting(); |
| 41 | |
| 42 | if ( $existing ) { |
| 43 | return $existing; |
| 44 | } |
| 45 | |
| 46 | return $this->create( |
| 47 | [ |
| 48 | 'description' => 'Main webhook for SureCart', |
| 49 | 'enabled' => true, |
| 50 | 'destination' => 'wordpress', |
| 51 | 'url' => $this->getListenerUrl(), |
| 52 | ] |
| 53 | ); |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * Find existing webhook with the same listner url. |
| 58 | * |
| 59 | * @return \SureCart\Models\Webhook|false |
| 60 | */ |
| 61 | public function findExisting() { |
| 62 | $webhooks = $this->setPagination( [ 'per_page' => 100 ] )->get(); |
| 63 | if ( is_array( $webhooks ) && ! empty( $webhooks ) ) { |
| 64 | foreach ( $webhooks as $webhook ) { |
| 65 | if ( $webhook['url'] === $this->getListenerUrl() ) { |
| 66 | return $webhook; |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | return false; |
| 71 | } |
| 72 | } |
| 73 |