Drip_API.class.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. <?php
  2. /**
  3. * Drip API
  4. * @author Svetoslav Marinov (SLAVI)
  5. */
  6. Class Drip_Api {
  7. private $version = "2";
  8. private $api_token = '';
  9. private $error_code = '';
  10. private $error_message = '';
  11. private $user_agent = "Drip API PHP Wrapper (getdrip.com)";
  12. private $api_end_point = 'https://api.getdrip.com/v2/';
  13. //private $api_end_point = 'http://localhost/echo/'; // dbg only
  14. private $recent_req_info = array(); // holds dbg info from a recent request
  15. private $timeout = 30;
  16. private $connect_timeout = 30;
  17. private $debug = false; // Requests headers and other info to be fetched from the request. Command-line windows will show info in STDERR
  18. const GET = 1;
  19. const POST = 2;
  20. const DELETE = 3;
  21. const PUT = 4;
  22. /**
  23. * Accepts the token and saves it internally.
  24. *
  25. * @param string $api_token e.g. qsor48ughrjufyu2dadraasfa1212424
  26. * @throws Exception
  27. */
  28. public function __construct($api_token) {
  29. $api_token = trim($api_token);
  30. if (empty($api_token) || !preg_match('#^[\w-]+$#si', $api_token)) {
  31. throw new Exception("Missing or invalid Drip API token.");
  32. }
  33. $this->api_token = $api_token;
  34. }
  35. /**
  36. * Requests the campaigns for the given account.
  37. * @param array
  38. * @return array
  39. */
  40. public function get_campaigns($params) {
  41. if (empty($params['account_id'])) {
  42. throw new Exception("Account ID not specified");
  43. }
  44. $account_id = $params['account_id'];
  45. unset($params['account_id']); // clear it from the params
  46. if (isset($params['status'])) {
  47. if (!in_array($params['status'], array('active', 'draft', 'paused', 'all'))) {
  48. throw new Exception("Invalid campaign status.");
  49. }
  50. } elseif (0) {
  51. $params['status'] = 'active'; // api defaults to all but we want active ones
  52. }
  53. $url = $this->api_end_point . "$account_id/campaigns";
  54. $res = $this->make_request($url, $params);
  55. if (!empty($res['buffer'])) {
  56. $raw_json = json_decode($res['buffer'], true);
  57. }
  58. // here we distinguish errors from no campaigns.
  59. // when there's no json that's an error
  60. $campaigns = empty($raw_json)
  61. ? false
  62. : empty($raw_json['campaigns'])
  63. ? array()
  64. : $raw_json['campaigns'];
  65. return $campaigns;
  66. }
  67. /**
  68. * Fetch a campaign for the given account based on it's ID.
  69. * @param array (account_id, campaign_id)
  70. * @return array
  71. */
  72. public function fetch_campaign($params) {
  73. if (empty($params['account_id'])) {
  74. throw new Exception("Account ID not specified");
  75. }
  76. $account_id = $params['account_id'];
  77. unset($params['account_id']); // clear it from the params
  78. if (!empty($params['campaign_id'])) {
  79. $campaign_id = $params['campaign_id'];
  80. unset($params['campaign_id']); // clear it from the params
  81. } else {
  82. throw new Exception("Campaign ID was not specified. You must specify a Campaign ID");
  83. }
  84. $url = $this->api_end_point . "$account_id/campaigns/$campaign_id";
  85. $res = $this->make_request($url, $params);
  86. if (!empty($res['buffer'])) {
  87. $raw_json = json_decode($res['buffer'], true);
  88. }
  89. // here we distinguish errors from no campaign
  90. // when there's no json that's an error
  91. $campaigns = empty($raw_json)
  92. ? false
  93. : empty($raw_json['campaigns'])
  94. ? array()
  95. : $raw_json['campaigns'];
  96. return $campaigns;
  97. }
  98. /**
  99. * Requests the accounts for the given account.
  100. * Parses the response JSON and returns an array which contains: id, name, created_at etc
  101. * @param void
  102. * @return bool/array
  103. */
  104. public function get_accounts() {
  105. $url = $this->api_end_point . 'accounts';
  106. $res = $this->make_request($url);
  107. if (!empty($res['buffer'])) {
  108. $raw_json = json_decode($res['buffer'], true);
  109. }
  110. $data = empty($raw_json)
  111. ? false
  112. : empty($raw_json['accounts'])
  113. ? array()
  114. : $raw_json['accounts'];
  115. return $data;
  116. }
  117. /**
  118. * Get a specific account provided by the user
  119. * Parses the response JSON and returns an array which contains: id, name, created_at etc
  120. * @param integer $account_id
  121. * @return bool/array
  122. */
  123. public function fetch_account($account_id) {
  124. if (empty($account_id)) {
  125. throw new Exception("Account ID not specified");
  126. }
  127. $url = $this->api_end_point . "accounts/{$account_id}";
  128. $res = $this->make_request($url);
  129. if (!empty($res['buffer'])) {
  130. $raw_json = json_decode($res['buffer'], true);
  131. }
  132. $data = empty($raw_json)
  133. ? false
  134. : empty($raw_json['accounts'])
  135. ? array()
  136. : $raw_json['accounts'];
  137. return $data;
  138. }
  139. /**
  140. * Sends a request to add a subscriber and returns its record or false
  141. *
  142. * @param array $params
  143. * @param array/bool $account
  144. */
  145. public function create_or_update_subscriber($params) {
  146. if (empty($params['account_id'])) {
  147. throw new Exception("Account ID not specified");
  148. }
  149. $account_id = $params['account_id'];
  150. unset($params['account_id']); // clear it from the params
  151. $api_action = "/$account_id/subscribers";
  152. $url = $this->api_end_point . $api_action;
  153. // The API wants the params to be JSON encoded
  154. $req_params = array('subscribers' => array($params));
  155. $res = $this->make_request($url, $req_params, self::POST);
  156. if (!empty($res['buffer'])) {
  157. $raw_json = json_decode($res['buffer'], true);
  158. }
  159. $data = empty($raw_json)
  160. ? false
  161. : empty($raw_json['subscribers'])
  162. ? array()
  163. : $raw_json['subscribers'][0];
  164. return $data;
  165. }
  166. /**
  167. *
  168. * @param array $params
  169. * @param array $params
  170. */
  171. public function fetch_subscriber($params) {
  172. if (empty($params['account_id'])) {
  173. throw new Exception("Account ID not specified");
  174. }
  175. $account_id = $params['account_id'];
  176. unset($params['account_id']); // clear it from the params
  177. if (!empty($params['subscriber_id'])) {
  178. $subscriber_id = $params['subscriber_id'];
  179. unset($params['subscriber_id']); // clear it from the params
  180. } elseif (!empty($params['email'])) {
  181. $subscriber_id = $params['email'];
  182. unset($params['email']); // clear it from the params
  183. } else {
  184. throw new Exception("Subscriber ID or Email was not specified. You must specify either Subscriber ID or Email.");
  185. }
  186. $subscriber_id = urlencode($subscriber_id);
  187. $api_action = "$account_id/subscribers/$subscriber_id";
  188. $url = $this->api_end_point . $api_action;
  189. $res = $this->make_request($url);
  190. if (!empty($res['buffer'])) {
  191. $raw_json = json_decode($res['buffer'], true);
  192. }
  193. $data = empty($raw_json)
  194. ? false
  195. : empty($raw_json['subscribers'])
  196. ? array()
  197. : $raw_json['subscribers'][0];
  198. return $data;
  199. }
  200. /**
  201. * Subscribes a user to a given campaign for a given account.
  202. *
  203. * @param array $params
  204. * @param array $accounts
  205. */
  206. public function subscribe_subscriber($params) {
  207. if (empty($params['account_id'])) {
  208. throw new Exception("Account ID not specified");
  209. }
  210. $account_id = $params['account_id'];
  211. unset($params['account_id']); // clear it from the params
  212. if (empty($params['campaign_id'])) {
  213. throw new Exception("Campaign ID not specified");
  214. }
  215. $campaign_id = $params['campaign_id'];
  216. unset($params['campaign_id']); // clear it from the params
  217. if (empty($params['email'])) {
  218. throw new Exception("Email not specified");
  219. }
  220. if (!isset($params['double_optin'])) {
  221. $params['double_optin'] = true;
  222. }
  223. $api_action = "$account_id/campaigns/$campaign_id/subscribers";
  224. $url = $this->api_end_point . $api_action;
  225. // The API wants the params to be JSON encoded
  226. $req_params = array('subscribers' => array($params));
  227. $res = $this->make_request($url, $req_params, self::POST);
  228. if (!empty($res['buffer'])) {
  229. $raw_json = json_decode($res['buffer'], true);
  230. }
  231. $data = empty($raw_json)
  232. ? false
  233. : empty($raw_json['subscribers'])
  234. ? array()
  235. : $raw_json['subscribers'][0];
  236. return $data;
  237. }
  238. /**
  239. *
  240. * Some keys are removed from the params so they don't get send with the other data to Drip.
  241. *
  242. * @param array $params
  243. * @param array $params
  244. */
  245. public function unsubscribe_subscriber($params) {
  246. if (empty($params['account_id'])) {
  247. throw new Exception("Account ID not specified");
  248. }
  249. $account_id = $params['account_id'];
  250. unset($params['account_id']); // clear it from the params
  251. if (!empty($params['subscriber_id'])) {
  252. $subscriber_id = $params['subscriber_id'];
  253. unset($params['subscriber_id']); // clear it from the params
  254. } elseif (!empty($params['email'])) {
  255. $subscriber_id = $params['email'];
  256. unset($params['email']); // clear it from the params
  257. } else {
  258. throw new Exception("Subscriber ID or Email was not specified. You must specify either Subscriber ID or Email.");
  259. }
  260. $subscriber_id = urlencode($subscriber_id);
  261. $api_action = "$account_id/subscribers/$subscriber_id/unsubscribe";
  262. $url = $this->api_end_point . $api_action;
  263. $req_params = $params;
  264. $res = $this->make_request($url, $req_params, self::POST);
  265. if (!empty($res['buffer'])) {
  266. $raw_json = json_decode($res['buffer'], true);
  267. }
  268. $data = empty($raw_json)
  269. ? false
  270. : empty($raw_json['subscribers'])
  271. ? array()
  272. : $raw_json['subscribers'][0];
  273. return $data;
  274. }
  275. /**
  276. *
  277. * This calls POST /:account_id/tags to add the tag. It just returns some status code no content
  278. *
  279. * @param array $params
  280. * @param bool $status
  281. */
  282. public function tag_subscriber($params) {
  283. $status = false;
  284. if (empty($params['account_id'])) {
  285. throw new Exception("Account ID not specified");
  286. }
  287. $account_id = $params['account_id'];
  288. unset($params['account_id']); // clear it from the params
  289. if (empty($params['email'])) {
  290. throw new Exception("Email was not specified");
  291. }
  292. if (empty($params['tag'])) {
  293. throw new Exception("Tag was not specified");
  294. }
  295. $api_action = "$account_id/tags";
  296. $url = $this->api_end_point . $api_action;
  297. // The API wants the params to be JSON encoded
  298. $req_params = array('tags' => array($params));
  299. $res = $this->make_request($url, $req_params, self::POST);
  300. if ($res['http_code'] == 201) {
  301. $status = true;
  302. }
  303. return $status;
  304. }
  305. /**
  306. *
  307. * This calls DELETE /:account_id/tags to remove the tags. It just returns some status code no content
  308. *
  309. * @param array $params
  310. * @param bool $status success or failure
  311. */
  312. public function untag_subscriber($params) {
  313. $status = false;
  314. if (empty($params['account_id'])) {
  315. throw new Exception("Account ID not specified");
  316. }
  317. $account_id = $params['account_id'];
  318. unset($params['account_id']); // clear it from the params
  319. if (empty($params['email'])) {
  320. throw new Exception("Email was not specified");
  321. }
  322. if (empty($params['tag'])) {
  323. throw new Exception("Tag was not specified");
  324. }
  325. $api_action = "$account_id/tags";
  326. $url = $this->api_end_point . $api_action;
  327. // The API wants the params to be JSON encoded
  328. $req_params = array('tags' => array($params));
  329. $res = $this->make_request($url, $req_params, self::DELETE);
  330. if ($res['http_code'] == 204) {
  331. $status = true;
  332. }
  333. return $status;
  334. }
  335. /**
  336. *
  337. * Posts an event specified by the user.
  338. *
  339. * @param array $params
  340. * @param bool
  341. */
  342. public function record_event($params) {
  343. $status = false;
  344. if (empty($params['account_id'])) {
  345. throw new Exception("Account ID not specified");
  346. }
  347. if (empty($params['action'])) {
  348. throw new Exception("Action was not specified");
  349. }
  350. $account_id = $params['account_id'];
  351. unset($params['account_id']); // clear it from the params
  352. $api_action = "$account_id/events";
  353. $url = $this->api_end_point . $api_action;
  354. // The API wants the params to be JSON encoded
  355. $req_params = array('events' => array($params));
  356. $res = $this->make_request($url, $req_params, self::POST);
  357. if ($res['http_code'] == 204) {
  358. $status = true;
  359. }
  360. return $status;
  361. }
  362. /**
  363. *
  364. * @param string $url
  365. * @param array $params
  366. * @param int $req_method
  367. * @return type
  368. * @throws Exception
  369. */
  370. public function make_request($url, $params = array(), $req_method = self::GET) {
  371. if (!function_exists('curl_init')) {
  372. throw new Exception("Cannot find cURL php extension or it's not loaded.");
  373. }
  374. $ch = curl_init();
  375. if ($this->debug) {
  376. //curl_setopt($ch, CURLOPT_HEADER, true);
  377. // TRUE to output verbose information. Writes output to STDERR, or the file specified using CURLOPT_STDERR.
  378. curl_setopt($ch, CURLOPT_VERBOSE, true);
  379. }
  380. curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
  381. curl_setopt($ch, CURLOPT_FORBID_REUSE, true);
  382. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  383. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  384. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  385. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  386. curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
  387. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connect_timeout);
  388. curl_setopt($ch, CURLOPT_USERPWD, $this->api_token . ":" . ''); // no pwd
  389. curl_setopt($ch, CURLOPT_USERAGENT, empty($params['user_agent']) ? $this->user_agent : $params['user_agent']);
  390. if ($req_method == self::POST) { // We want post but no params to supply. Probably we have a nice link structure which includes all the info.
  391. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  392. } elseif ($req_method == self::DELETE) {
  393. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
  394. } elseif ($req_method == self::PUT) {
  395. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  396. }
  397. if (!empty($params)) {
  398. if ((isset($params['__req']) && strtolower($params['__req']) == 'get')
  399. || $req_method == self::GET) {
  400. unset($params['__req']);
  401. $url .= '?' . http_build_query($params);
  402. } elseif ($req_method == self::POST || $req_method == self::DELETE) {
  403. $params_str = is_array($params) ? json_encode($params) : $params;
  404. curl_setopt($ch, CURLOPT_POSTFIELDS, $params_str);
  405. }
  406. }
  407. curl_setopt($ch, CURLOPT_URL, $url);
  408. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  409. 'Accept:application/json, text/javascript, */*; q=0.01',
  410. 'Content-Type: application/vnd.api+json',
  411. ));
  412. $buffer = curl_exec($ch);
  413. $status = !empty($buffer);
  414. $data = array(
  415. 'url' => $url,
  416. 'params' => $params,
  417. 'status' => $status,
  418. 'error' => empty($buffer) ? curl_error($ch) : '',
  419. 'error_no' => empty($buffer) ? curl_errno($ch) : '',
  420. 'http_code' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
  421. 'debug' => $this->debug ? curl_getinfo($ch) : '',
  422. );
  423. curl_close($ch);
  424. // remove some weird headers HTTP/1.1 100 Continue or HTTP/1.1 200 OK
  425. $buffer = preg_replace('#HTTP/[\d.]+\s+\d+\s+\w+[\r\n]+#si', '', $buffer);
  426. $buffer = trim($buffer);
  427. $data['buffer'] = $buffer;
  428. $this->_parse_error($data);
  429. $this->recent_req_info = $data;
  430. return $data;
  431. }
  432. /**
  433. * This returns the RAW data from the each request that has been sent (if any).
  434. * @return arraay of arrays
  435. */
  436. public function get_request_info() {
  437. return $this->recent_req_info;
  438. }
  439. /**
  440. * Retruns whatever was accumultaed in error_message
  441. * @param string
  442. */
  443. public function get_error_message() {
  444. return $this->error_message;
  445. }
  446. /**
  447. * Retruns whatever was accumultaed in error_code
  448. * @return string
  449. */
  450. public function get_error_code() {
  451. return $this->error_code;
  452. }
  453. /**
  454. * Some keys are removed from the params so they don't get send with the other data to Drip.
  455. *
  456. * @param array $params
  457. * @param array
  458. */
  459. public function _parse_error($res) {
  460. if (empty($res['http_code']) || $res['http_code'] >= 200 && $res['http_code'] <= 299) {
  461. return true;
  462. }
  463. if (empty($res['buffer'])) {
  464. $this->error_message = "Response from the server.";
  465. $this->error_code = $res['http_code'];
  466. } elseif (!empty($res['buffer'])) {
  467. $json_arr = json_decode($res['buffer'], true);
  468. // The JSON error response looks like this.
  469. /*
  470. {
  471. "errors": [{
  472. "code": "authorization_error",
  473. "message": "You are not authorized to access this resource"
  474. }]
  475. }
  476. */
  477. if (!empty($json_arr['errors'])) { // JSON
  478. $messages = $error_codes = array();
  479. foreach ($json_arr['errors'] as $rec) {
  480. $messages[] = $rec['message'];
  481. $error_codes[] = $rec['code'];
  482. }
  483. $this->error_code = join(", ", $error_codes);
  484. $this->error_message = join("\n", $messages);
  485. } else { // There's no JSON in the reply so we'll extract the message from the HTML page by removing the HTML.
  486. $msg = $res['buffer'];
  487. $msg = preg_replace('#.*?<body[^>]*>#si', '', $msg);
  488. $msg = preg_replace('#</body[^>]*>.*#si', '', $msg);
  489. $msg = strip_tags($msg);
  490. $msg = preg_replace('#[\r\n]#si', '', $msg);
  491. $msg = preg_replace('#\s+#si', ' ', $msg);
  492. $msg = trim($msg);
  493. $msg = substr($msg, 0, 256);
  494. $this->error_code = $res['http_code'];
  495. $this->error_message = $msg;
  496. }
  497. } elseif ($res['http_code'] >= 400 || $res['http_code'] <= 499) {
  498. $this->error_message = "Not authorized.";
  499. $this->error_code = $res['http_code'];
  500. } elseif ($res['http_code'] >= 500 || $res['http_code'] <= 599) {
  501. $this->error_message = "Internal Server Error.";
  502. $this->error_code = $res['http_code'];
  503. }
  504. }
  505. // tmp
  506. public function __call($method, $args) {
  507. return array();
  508. }
  509. }