|
| 1 | +<?php |
| 2 | + |
| 3 | +class Kkd_Pff_Paystack_webhook{ |
| 4 | + |
| 5 | + /** |
| 6 | + * @var string Pug Bomb Headquarters |
| 7 | + */ |
| 8 | + |
| 9 | + |
| 10 | + /** Hook WordPress |
| 11 | + * @return void |
| 12 | + */ |
| 13 | + public function __construct(){ |
| 14 | + add_filter('query_vars', array($this, 'add_query_vars'), 0); |
| 15 | + add_action('parse_request', array($this, 'sniff_requests'), 0); |
| 16 | + add_action('init', array($this, 'add_endpoint'), 0); |
| 17 | + } |
| 18 | + |
| 19 | + /** Add public query vars |
| 20 | + * @param array $vars List of current public query vars |
| 21 | + * @return array $vars |
| 22 | + */ |
| 23 | + public function add_query_vars($vars){ |
| 24 | + $vars[] = '__api'; |
| 25 | + $vars[] = 'pugs'; |
| 26 | + return $vars; |
| 27 | + } |
| 28 | + |
| 29 | + /** Add API Endpoint |
| 30 | + * This is where the magic happens - brush up on your regex skillz |
| 31 | + * @return void |
| 32 | + */ |
| 33 | + public function add_endpoint(){ |
| 34 | + add_rewrite_rule('/ kkd/wpffp/webhook/','index.php?__api=1&pugs=$matches[1]','top'); |
| 35 | + } |
| 36 | + /** Sniff Requests |
| 37 | + * This is where we hijack all API requests |
| 38 | + * If $_GET['__api'] is set, we kill WP and serve up pug bomb awesomeness |
| 39 | + * @return die if API request |
| 40 | + */ |
| 41 | + public function sniff_requests(){ |
| 42 | + global $wp; |
| 43 | + if(isset($wp->query_vars['__api'])){ |
| 44 | + $this->handle_request(); |
| 45 | + exit; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + /** Handle Requests |
| 50 | + * This is where we send off for an intense pug bomb package |
| 51 | + * @return void |
| 52 | + */ |
| 53 | + protected function handle_request(){ |
| 54 | + global $wp; |
| 55 | + $pugs = $wp->query_vars['pugs']; |
| 56 | + if(!$pugs) |
| 57 | + $this->send_response('Please tell us how many pugs to send.'); |
| 58 | + |
| 59 | + $pugs = file_get_contents(get_site_url().'/kkd/wpffp/webhook/'.$pugs); |
| 60 | + if($pugs) |
| 61 | + $this->send_response('200 OK', json_decode($pugs)); |
| 62 | + else |
| 63 | + $this->send_response('Something went wrong with the pug bomb factory'); |
| 64 | + } |
| 65 | + |
| 66 | + /** Response Handler |
| 67 | + * This sends a JSON response to the browser |
| 68 | + */ |
| 69 | + protected function send_response($msg, $pugs = ''){ |
| 70 | + $response['message'] = $msg; |
| 71 | + if($pugs) |
| 72 | + $response['pugs'] = $pugs; |
| 73 | + header('content-type: application/json; charset=utf-8'); |
| 74 | + echo json_encode($response)."\n"; |
| 75 | + exit; |
| 76 | + } |
| 77 | +} |
| 78 | +new Kkd_Pff_Paystack_webhook(); |
0 commit comments