| @@ -1,17 +1,14 @@ | ||
| 1 | 1 | <?php |
| 2 | 2 | |
| 3 | 3 | namespace SureCart\Models; |
| 4 | 4 | |
| 5 | -use SureCart\Models\Traits\HasDates; | |
| 6 | -use SureCart\Support\TimeDate; | |
| 5 | +use SureCart\Support\Encryption; | |
| 7 | 6 | |
| 8 | 7 | /** |
| 9 | - * Webhook Model. | |
| 8 | + * Price model | |
| 10 | 9 | */ |
| 11 | 10 | class Webhook extends Model { |
| 12 | - use HasDates; | |
| 13 | - | |
| 14 | 11 | /** |
| 15 | 12 | * Rest API endpoint |
| 16 | 13 | * |
| 17 | 14 | * @var string |
| @@ -25,26 +22,51 @@ | ||
| 25 | 22 | */ |
| 26 | 23 | protected $object_name = 'webhook_endpoint'; |
| 27 | 24 | |
| 28 | 25 | /** |
| 29 | - * Is this cachable? | |
| 26 | + * Get the listener url. | |
| 30 | 27 | * |
| 31 | - * @var boolean | |
| 28 | + * @return string | |
| 32 | 29 | */ |
| 33 | - protected $cachable = true; | |
| 30 | + protected function getListenerUrl() { | |
| 31 | + return get_site_url( null, '/surecart/webhooks', is_ssl() ? 'https' : 'http' ); | |
| 32 | + } | |
| 34 | 33 | |
| 35 | 34 | /** |
| 36 | - * Clear cache when webhook endpoints are updated. | |
| 35 | + * Register webhook for this site | |
| 37 | 36 | * |
| 38 | - * @var string | |
| 37 | + * @return $this|false | |
| 39 | 38 | */ |
| 40 | - protected $cache_key = 'webhook_endpoints'; | |
| 39 | + protected function register() { | |
| 40 | + $existing = $this->findExisting(); | |
| 41 | 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 | + | |
| 42 | 56 | /** |
| 43 | - * Get the erroring grace period ends at date time attribute. | |
| 57 | + * Find existing webhook with the same listner url. | |
| 44 | 58 | * |
| 45 | - * @return string | |
| 59 | + * @return \SureCart\Models\Webhook|false | |
| 46 | 60 | */ |
| 47 | - public function getErroringGracePeriodEndsAtDateTimeAttribute() { | |
| 48 | - return ! empty( $this->erroring_grace_period_ends_at ) ? TimeDate::formatDateAndTime( $this->erroring_grace_period_ends_at ) : ''; | |
| 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; | |
| 49 | 71 | } |
| 50 | 72 | } |