Subscriptions-PayPal.php 12 KB

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