WJ_Bridge

The MailPoet Newsletters WJ Bridge class.

Defined (1)

The class is defined in the following location(s).

/classes/WJ_Bridge.php  
  1. class WJ_Bridge { 
  2. public $error; 
  3. private $api_key = ''; 
  4. public function __construct($api_key) { 
  5. $this->api_key = $api_key; 
  6.  
  7. public function send_mail(& $object) 
  8. $replyToKey = key($object->ReplyTo); 
  9.  
  10. $msg = array( 
  11. 'to' => array( 
  12. 'name' => '' ,  
  13. 'address' => $object->to[0][0] ),  
  14. 'reply_to'=> array( 
  15. 'name' => '' ,  
  16. 'address' => $object->ReplyTo[$replyToKey][0] 
  17. ),  
  18. 'from' => array( 
  19. 'name' => $object->FromName ,  
  20. 'address' => $object->From ),  
  21. ); 
  22.  
  23. // set the subject 
  24. if (!empty ($object->Subject)) $msg['subject']= $object->Subject; 
  25.  
  26. // set the body 
  27. if (!empty ($object->sendHTML) || !empty($object->AltBody)) { 
  28. $msg['html']= $object->Body; 
  29. if (!empty ($object->AltBody)) $msg['text']=$object->AltBody; 
  30. }else{ 
  31. $msg['text']=$object->Body; 
  32.  
  33. if(!empty($object->to[0][1])) $msg['to']['name'] = $object->to[0][1]; 
  34.  
  35. if(!empty($object->ReplyTo[0][1])) $msg['reply_to']['name']= $object->ReplyTo[0][1]; 
  36.  
  37. $url = 'https://bridge.mailpoet.com/api/messages'; 
  38.  
  39. $args = array( $msg ); 
  40.  
  41. return $this->run( $url, $args); 
  42.  
  43.  
  44. protected function run($url, $args) 
  45. $return = null; 
  46. $data = json_encode($args); 
  47.  
  48. $params = array( 
  49. 'headers' => array( 
  50. 'Content-Type: application/json',  
  51. 'Authorization' => 'Basic ' . base64_encode('api:' . $this->api_key ) 
  52. ),  
  53. 'body' => $data 
  54. ); 
  55.  
  56. $result = null; 
  57. $result = wp_remote_post($url, $params); 
  58. try { 
  59. if (!is_wp_error($result) && in_array( (int)$result['response']['code'], array( 201, 400, 401) ) ) 
  60. switch( $result['response']['code'] ) { 
  61. case 201: 
  62. $return = true; 
  63. break; 
  64. case 400: 
  65. $this->error = 'Bad input'; 
  66. break; 
  67. case 401: 
  68. $this->error = 'Not Authorized'; 
  69. break; 
  70. else if (is_wp_error($result)) { 
  71. $this->error = $result->get_error_messages(); 
  72. } catch(Exception $e) { 
  73. $this->error = 'Unexpected error: '.$e->getMessage() . ' ['.var_export($result, true).']';// do nothing 
  74.  
  75. return $return; 
  76.