Subscriptions-PayPal.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2014 Simple Machines and individual contributors
  8. * @license http://www.simplemachines.org/about/smf/license.php BSD
  9. *
  10. * @version 2.1 Alpha 1
  11. */
  12. // This won't be dedicated without this - this must exist in each gateway!
  13. // SMF Payment Gateway: paypal
  14. if (!defined('SMF'))
  15. die('No direct access...');
  16. /**
  17. * Class for returning available form data for this gateway
  18. */
  19. class paypal_display
  20. {
  21. /**
  22. * Name of this payment gateway
  23. */
  24. public $title = 'PayPal';
  25. /**
  26. * Return the admin settings for this gateway
  27. *
  28. * @return array
  29. */
  30. public function getGatewaySettings()
  31. {
  32. global $txt;
  33. $setting_data = array(
  34. array(
  35. 'email', 'paypal_email',
  36. 'subtext' => $txt['paypal_email_desc']
  37. ),
  38. array(
  39. 'email', 'paypal_sandbox_email',
  40. 'subtext' => $txt['paypal_sandbox_email_desc']
  41. ),
  42. );
  43. return $setting_data;
  44. }
  45. /**
  46. * Is this enabled for new payments?
  47. *
  48. * @return boolean
  49. */
  50. public function gatewayEnabled()
  51. {
  52. global $modSettings;
  53. return !empty($modSettings['paypal_email']);
  54. }
  55. /**
  56. * What do we want?
  57. *
  58. * Called from Profile-Actions.php to return a unique set of fields for the given gateway
  59. * plus all the standard ones for the subscription form
  60. *
  61. * @param type $unique_id
  62. * @param type $sub_data
  63. * @param type $value
  64. * @param type $period
  65. * @param type $return_url
  66. * @return string
  67. */
  68. public function fetchGatewayFields($unique_id, $sub_data, $value, $period, $return_url)
  69. {
  70. global $modSettings, $txt, $boardurl;
  71. $return_data = array(
  72. 'form' => 'https://www.' . (!empty($modSettings['paidsubs_test']) ? 'sandbox.' : '') . 'paypal.com/cgi-bin/webscr',
  73. 'id' => 'paypal',
  74. 'hidden' => array(),
  75. 'title' => $txt['paypal'],
  76. 'desc' => $txt['paid_confirm_paypal'],
  77. 'submit' => $txt['paid_paypal_order'],
  78. 'javascript' => '',
  79. );
  80. // All the standard bits.
  81. $return_data['hidden']['business'] = $modSettings['paypal_email'];
  82. $return_data['hidden']['item_name'] = $sub_data['name'] . ' ' . $txt['subscription'];
  83. $return_data['hidden']['item_number'] = $unique_id;
  84. $return_data['hidden']['currency_code'] = strtoupper($modSettings['paid_currency_code']);
  85. $return_data['hidden']['no_shipping'] = 1;
  86. $return_data['hidden']['no_note'] = 1;
  87. $return_data['hidden']['amount'] = $value;
  88. $return_data['hidden']['cmd'] = !$sub_data['repeatable'] ? '_xclick' : '_xclick-subscriptions';
  89. $return_data['hidden']['return'] = $return_url;
  90. $return_data['hidden']['a3'] = $value;
  91. $return_data['hidden']['src'] = 1;
  92. $return_data['hidden']['notify_url'] = $boardurl . '/subscriptions.php';
  93. // If possible let's use the language we know we need.
  94. $return_data['hidden']['lc'] = !empty($txt['lang_paypal']) ? $txt['lang_paypal'] : 'US';
  95. // Now stuff dependant on what we're doing.
  96. if ($sub_data['flexible'])
  97. {
  98. $return_data['hidden']['p3'] = 1;
  99. $return_data['hidden']['t3'] = strtoupper(substr($period, 0, 1));
  100. }
  101. else
  102. {
  103. preg_match('~(\d*)(\w)~', $sub_data['real_length'], $match);
  104. $unit = $match[1];
  105. $period = $match[2];
  106. $return_data['hidden']['p3'] = $unit;
  107. $return_data['hidden']['t3'] = $period;
  108. }
  109. // If it's repeatable do some javascript to respect this idea.
  110. if (!empty($sub_data['repeatable']))
  111. $return_data['javascript'] = '
  112. document.write(\'<label for="do_paypal_recur"><input type="checkbox" name="do_paypal_recur" id="do_paypal_recur" checked onclick="switchPaypalRecur();" class="input_check">' . $txt['paid_make_recurring'] . '</label><br>\');
  113. function switchPaypalRecur()
  114. {
  115. document.getElementById("paypal_cmd").value = document.getElementById("do_paypal_recur").checked ? "_xclick-subscriptions" : "_xclick";
  116. }';
  117. return $return_data;
  118. }
  119. }
  120. /**
  121. * Class of functions to validate a IPN response and provide details of the payment
  122. */
  123. class paypal_payment
  124. {
  125. private $return_data;
  126. /**
  127. * This function returns true/false for whether this gateway thinks the data is intended for it.
  128. *
  129. * @return boolean
  130. */
  131. public function isValid()
  132. {
  133. global $modSettings;
  134. // Has the user set up an email address?
  135. if ((empty($modSettings['paidsubs_test']) && empty($modSettings['paypal_email'])) || empty($modSettings['paypal_sandbox_email']))
  136. return false;
  137. // Check the correct transaction types are even here.
  138. if ((!isset($_POST['txn_type']) && !isset($_POST['payment_status'])) || (!isset($_POST['business']) && !isset($_POST['receiver_email'])))
  139. return false;
  140. // Correct email address?
  141. if (!isset($_POST['business']))
  142. $_POST['business'] = $_POST['receiver_email'];
  143. // Are we testing?
  144. if (!empty($modSettings['paidsubs_test']) && $modSettings['paypal_sandbox_email'] !== $_POST['business'] && (empty($modSettings['paypal_additional_emails']) || !in_array($_POST['business'], explode(',', $modSettings['paypal_additional_emails']))))
  145. return false;
  146. elseif ($modSettings['paypal_email'] !== $_POST['business'] && (empty($modSettings['paypal_additional_emails']) || !in_array($_POST['business'], explode(',', $modSettings['paypal_additional_emails']))))
  147. return false;
  148. return true;
  149. }
  150. /**
  151. * Post the IPN data received back to paypal for validaion
  152. * Sends the complete unaltered message back to PayPal. The message must contain the same fields
  153. * in the same order and be encoded in the same way as the original message
  154. * PayPal will respond back with a single word, which is either VERIFIED if the message originated with PayPal or INVALID
  155. *
  156. * If valid returns the subscription and member IDs we are going to process if it passes
  157. *
  158. * @return string
  159. */
  160. public function precheck()
  161. {
  162. global $modSettings, $txt;
  163. // Put this to some default value.
  164. if (!isset($_POST['txn_type']))
  165. $_POST['txn_type'] = '';
  166. // Build the request string - starting with the minimum requirement.
  167. $requestString = 'cmd=_notify-validate';
  168. // Now my dear, add all the posted bits in the order we got them
  169. foreach ($_POST as $k => $v)
  170. $requestString .= '&' . $k . '=' . urlencode($v);
  171. // Can we use curl?
  172. if (function_exists('curl_init') && $curl = curl_init((!empty($modSettings['paidsubs_test']) ? 'https://www.sandbox.' : 'http://www.') . 'paypal.com/cgi-bin/webscr'))
  173. {
  174. // Set the post data.
  175. curl_setopt($curl, CURLOPT_POST, true);
  176. curl_setopt($curl, CURLOPT_POSTFIELDSIZE, 0);
  177. curl_setopt($curl, CURLOPT_POSTFIELDS, $requestString);
  178. // Set up the headers so paypal will accept the post
  179. curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  180. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
  181. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
  182. curl_setopt($curl, CURLOPT_FORBID_REUSE, 1);
  183. curl_setopt($curl, CURLOPT_HTTPHEADER, array(
  184. 'Host: www.' . (!empty($modSettings['paidsubs_test']) ? 'sandbox.' : '') . 'paypal.com',
  185. 'Connection: close'
  186. ));
  187. // Fetch the data returned as a string.
  188. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  189. // Fetch the data.
  190. $this->return_data = curl_exec($curl);
  191. // Close the session.
  192. curl_close($curl);
  193. }
  194. // Otherwise good old HTTP.
  195. else
  196. {
  197. // Setup the headers.
  198. $header = 'POST /cgi-bin/webscr HTTP/1.1' . "\r\n";
  199. $header .= 'Content-Type: application/x-www-form-urlencoded' . "\r\n";
  200. $header .= 'Host: www.' . (!empty($modSettings['paidsubs_test']) ? 'sandbox.' : '') . 'paypal.com' . "\r\n";
  201. $header .= 'Content-Length: ' . strlen ($requestString) . "\r\n";
  202. $header .= 'Connection: close' . "\r\n\r\n";
  203. // Open the connection.
  204. if (!empty($modSettings['paidsubs_test']))
  205. $fp = fsockopen('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
  206. else
  207. $fp = fsockopen('www.paypal.com', 80, $errno, $errstr, 30);
  208. // Did it work?
  209. if (!$fp)
  210. generateSubscriptionError($txt['paypal_could_not_connect']);
  211. // Put the data to the port.
  212. fputs($fp, $header . $requestString);
  213. // Get the data back...
  214. while (!feof($fp))
  215. {
  216. $this->return_data = fgets($fp, 1024);
  217. if (strcmp(trim($this->return_data), 'VERIFIED') === 0)
  218. break;
  219. }
  220. // Clean up.
  221. fclose($fp);
  222. }
  223. // If this isn't verified then give up...
  224. if (strcmp(trim($this->return_data), 'VERIFIED') !== 0)
  225. exit;
  226. // Check that this is intended for us.
  227. if ($modSettings['paypal_email'] !== $_POST['business'] && (empty($modSettings['paypal_additional_emails']) || !in_array($_POST['business'], explode(',', $modSettings['paypal_additional_emails']))))
  228. exit;
  229. // Is this a subscription - and if so is it a secondary payment that we need to process?
  230. // If so, make sure we get it in the expected format. Seems PayPal sometimes sends it without urlencoding.
  231. if (!empty($_POST['item_number']) && strpos($_POST['item_number'], ' ') !== false)
  232. $_POST['item_number'] = str_replace(' ', '+', $_POST['item_number']);
  233. if ($this->isSubscription() && (empty($_POST['item_number']) || strpos($_POST['item_number'], '+') === false))
  234. // Calculate the subscription it relates to!
  235. $this->_findSubscription();
  236. // Verify the currency!
  237. if (strtolower($_POST['mc_currency']) !== strtolower($modSettings['paid_currency_code']))
  238. exit;
  239. // Can't exist if it doesn't contain anything.
  240. if (empty($_POST['item_number']))
  241. exit;
  242. // Return the id_sub and id_member
  243. return explode('+', $_POST['item_number']);
  244. }
  245. /**
  246. * Is this a refund?
  247. *
  248. * @return boolean
  249. */
  250. public function isRefund()
  251. {
  252. if ($_POST['payment_status'] === 'Refunded' || $_POST['payment_status'] === 'Reversed' || $_POST['txn_type'] === 'Refunded' || ($_POST['txn_type'] === 'reversal' && $_POST['payment_status'] === 'Completed'))
  253. return true;
  254. else
  255. return false;
  256. }
  257. /**
  258. * Is this a subscription?
  259. *
  260. * @return boolean
  261. */
  262. public function isSubscription()
  263. {
  264. if (substr($_POST['txn_type'], 0, 14) === 'subscr_payment' && $_POST['payment_status'] === 'Completed')
  265. return true;
  266. else
  267. return false;
  268. }
  269. /**
  270. * Is this a normal payment?
  271. *
  272. * @return boolean
  273. */
  274. public function isPayment()
  275. {
  276. if ($_POST['payment_status'] === 'Completed' && $_POST['txn_type'] === 'web_accept')
  277. return true;
  278. else
  279. return false;
  280. }
  281. /**
  282. * Is this a cancellation?
  283. *
  284. * @return boolean
  285. */
  286. public function isCancellation()
  287. {
  288. // subscr_cancel is sent when the user cancels, subscr_eot is sent when the subscription reaches final payment
  289. // Neither require us to *do* anything as per performCancel().
  290. // subscr_eot, if sent, indicates an end of payments term.
  291. if (substr($_POST['txn_type'], 0, 13) === 'subscr_cancel' || substr($_POST['txn_type'], 0, 10) === 'subscr_eot')
  292. return true;
  293. else
  294. return false;
  295. }
  296. /**
  297. * Things to do in the event of a cancellation
  298. *
  299. * @return void
  300. */
  301. public function performCancel($subscription_id, $member_id, $subscription_info)
  302. {
  303. // PayPal doesn't require SMF to notify it every time the subscription is up for renewal.
  304. // A cancellation should not cause the user to be immediately dropped from their subscription, but
  305. // let it expire normally. Some systems require taking action in the database to deal with this, but
  306. // PayPal does not, so we actually just do nothing. But this is a nice prototype/example just in case.
  307. }
  308. /**
  309. * How much was paid?
  310. *
  311. * @return float
  312. */
  313. public function getCost()
  314. {
  315. return (isset($_POST['tax']) ? $_POST['tax'] : 0) + $_POST['mc_gross'];
  316. }
  317. /**
  318. * Record the transaction reference and exit
  319. *
  320. */
  321. public function close()
  322. {
  323. global $smcFunc, $subscription_id;
  324. // If it's a subscription record the reference.
  325. if ($_POST['txn_type'] == 'subscr_payment' && !empty($_POST['subscr_id']))
  326. {
  327. $_POST['subscr_id'] = $_POST['subscr_id'];
  328. $smcFunc['db_query']('', '
  329. UPDATE {db_prefix}log_subscribed
  330. SET vendor_ref = {string:vendor_ref}
  331. WHERE id_sublog = {int:current_subscription}',
  332. array(
  333. 'current_subscription' => $subscription_id,
  334. 'vendor_ref' => $_POST['subscr_id'],
  335. )
  336. );
  337. }
  338. exit();
  339. }
  340. /**
  341. * A private function to find out the subscription details.
  342. *
  343. * @return boolean
  344. */
  345. private function _findSubscription()
  346. {
  347. global $smcFunc;
  348. // Assume we have this?
  349. if (empty($_POST['subscr_id']))
  350. return false;
  351. // Do we have this in the database?
  352. $request = $smcFunc['db_query']('', '
  353. SELECT id_member, id_subscribe
  354. FROM {db_prefix}log_subscribed
  355. WHERE vendor_ref = {string:vendor_ref}
  356. LIMIT 1',
  357. array(
  358. 'vendor_ref' => $_POST['subscr_id'],
  359. )
  360. );
  361. // No joy?
  362. if ($smcFunc['db_num_rows']($request) == 0)
  363. {
  364. // Can we identify them by email?
  365. if (!empty($_POST['payer_email']))
  366. {
  367. $smcFunc['db_free_result']($request);
  368. $request = $smcFunc['db_query']('', '
  369. SELECT ls.id_member, ls.id_subscribe
  370. FROM {db_prefix}log_subscribed AS ls
  371. INNER JOIN {db_prefix}members AS mem ON (mem.id_member = ls.id_member)
  372. WHERE mem.email_address = {string:payer_email}
  373. LIMIT 1',
  374. array(
  375. 'payer_email' => $_POST['payer_email'],
  376. )
  377. );
  378. if ($smcFunc['db_num_rows']($request) === 0)
  379. return false;
  380. }
  381. else
  382. return false;
  383. }
  384. list ($member_id, $subscription_id) = $smcFunc['db_fetch_row']($request);
  385. $_POST['item_number'] = $member_id . '+' . $subscription_id;
  386. $smcFunc['db_free_result']($request);
  387. }
  388. }
  389. ?>