Subscriptions-PayPal.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2013 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="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 ($this->isSubscription() && (empty($_POST['item_number']) || strpos($_POST['item_number'], '+') === false))
  222. // Calculate the subscription it relates to!
  223. $this->_findSubscription();
  224. // Verify the currency!
  225. if (strtolower($_POST['mc_currency']) !== $modSettings['paid_currency_code'])
  226. exit;
  227. // Can't exist if it doesn't contain anything.
  228. if (empty($_POST['item_number']))
  229. exit;
  230. // Return the id_sub and id_member
  231. return explode('+', $_POST['item_number']);
  232. }
  233. /**
  234. * Is this a refund?
  235. *
  236. * @return boolean
  237. */
  238. public function isRefund()
  239. {
  240. if ($_POST['payment_status'] === 'Refunded' || $_POST['payment_status'] === 'Reversed' || $_POST['txn_type'] === 'Refunded' || ($_POST['txn_type'] === 'reversal' && $_POST['payment_status'] === 'Completed'))
  241. return true;
  242. else
  243. return false;
  244. }
  245. /**
  246. * Is this a subscription?
  247. *
  248. * @return boolean
  249. */
  250. public function isSubscription()
  251. {
  252. if (substr($_POST['txn_type'], 0, 14) === 'subscr_payment' && $_POST['payment_status'] === 'Completed')
  253. return true;
  254. else
  255. return false;
  256. }
  257. /**
  258. * Is this a normal payment?
  259. *
  260. * @return boolean
  261. */
  262. public function isPayment()
  263. {
  264. if ($_POST['payment_status'] === 'Completed' && $_POST['txn_type'] === 'web_accept')
  265. return true;
  266. else
  267. return false;
  268. }
  269. /**
  270. * How much was paid?
  271. *
  272. * @return float
  273. */
  274. public function getCost()
  275. {
  276. return (isset($_POST['tax']) ? $_POST['tax'] : 0) + $_POST['mc_gross'];
  277. }
  278. /**
  279. * Record the transaction reference and exit
  280. *
  281. */
  282. public function close()
  283. {
  284. global $smcFunc, $subscription_id;
  285. // If it's a subscription record the reference.
  286. if ($_POST['txn_type'] == 'subscr_payment' && !empty($_POST['subscr_id']))
  287. {
  288. $_POST['subscr_id'] = $_POST['subscr_id'];
  289. $smcFunc['db_query']('', '
  290. UPDATE {db_prefix}log_subscribed
  291. SET vendor_ref = {string:vendor_ref}
  292. WHERE id_sublog = {int:current_subscription}',
  293. array(
  294. 'current_subscription' => $subscription_id,
  295. 'vendor_ref' => $_POST['subscr_id'],
  296. )
  297. );
  298. }
  299. exit();
  300. }
  301. /**
  302. * A private function to find out the subscription details.
  303. *
  304. * @return boolean
  305. */
  306. private function _findSubscription()
  307. {
  308. global $smcFunc;
  309. // Assume we have this?
  310. if (empty($_POST['subscr_id']))
  311. return false;
  312. // Do we have this in the database?
  313. $request = $smcFunc['db_query']('', '
  314. SELECT id_member, id_subscribe
  315. FROM {db_prefix}log_subscribed
  316. WHERE vendor_ref = {string:vendor_ref}
  317. LIMIT 1',
  318. array(
  319. 'vendor_ref' => $_POST['subscr_id'],
  320. )
  321. );
  322. // No joy?
  323. if ($smcFunc['db_num_rows']($request) == 0)
  324. {
  325. // Can we identify them by email?
  326. if (!empty($_POST['payer_email']))
  327. {
  328. $smcFunc['db_free_result']($request);
  329. $request = $smcFunc['db_query']('', '
  330. SELECT ls.id_member, ls.id_subscribe
  331. FROM {db_prefix}log_subscribed AS ls
  332. INNER JOIN {db_prefix}members AS mem ON (mem.id_member = ls.id_member)
  333. WHERE mem.email_address = {string:payer_email}
  334. LIMIT 1',
  335. array(
  336. 'payer_email' => $_POST['payer_email'],
  337. )
  338. );
  339. if ($smcFunc['db_num_rows']($request) === 0)
  340. return false;
  341. }
  342. else
  343. return false;
  344. }
  345. list ($member_id, $subscription_id) = $smcFunc['db_fetch_row']($request);
  346. $_POST['item_number'] = $member_id . '+' . $subscription_id;
  347. $smcFunc['db_free_result']($request);
  348. }
  349. }
  350. ?>