Subscriptions-PayPal.php 13 KB

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