PageRenderTime 53ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/enrol/paypal/ipn.php

https://github.com/kpike/moodle
PHP | 327 lines | 208 code | 68 blank | 51 comment | 38 complexity | 917a53f6f661fd151ec8d70e1bc98a0e MD5 | raw file
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Listens for Instant Payment Notification from PayPal
  18. *
  19. * This script waits for Payment notification from PayPal,
  20. * then double checks that data by sending it back to PayPal.
  21. * If PayPal verifies this then it sets up the enrolment for that
  22. * user.
  23. *
  24. * @package enrol
  25. * @subpackage paypal
  26. * @copyright 2010 Eugene Venter
  27. * @author Eugene Venter - based on code by others
  28. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  29. */
  30. require("../../config.php");
  31. require_once("lib.php");
  32. require_once($CFG->libdir.'/eventslib.php');
  33. require_once($CFG->libdir.'/enrollib.php');
  34. /// Keep out casual intruders
  35. if (empty($_POST) or !empty($_GET)) {
  36. print_error("Sorry, you can not use the script that way.");
  37. }
  38. /// Read all the data from PayPal and get it ready for later;
  39. /// we expect only valid UTF-8 encoding, it is the responsibility
  40. /// of user to set it up properly in PayPal business account,
  41. /// it is documented in docs wiki.
  42. $req = 'cmd=_notify-validate';
  43. $data = new stdClass();
  44. foreach ($_POST as $key => $value) {
  45. $req .= "&$key=".urlencode($value);
  46. $data->$key = $value;
  47. }
  48. $custom = explode('-', $data->custom);
  49. $data->userid = (int)$custom[0];
  50. $data->courseid = (int)$custom[1];
  51. $data->instanceid = (int)$custom[2];
  52. $data->payment_gross = $data->mc_gross;
  53. $data->payment_currency = $data->mc_currency;
  54. $data->timeupdated = time();
  55. /// get the user and course records
  56. if (! $user = $DB->get_record("user", array("id"=>$data->userid))) {
  57. message_paypal_error_to_admin("Not a valid user id", $data);
  58. die;
  59. }
  60. if (! $course = $DB->get_record("course", array("id"=>$data->courseid))) {
  61. message_paypal_error_to_admin("Not a valid course id", $data);
  62. die;
  63. }
  64. if (! $context = get_context_instance(CONTEXT_COURSE, $course->id)) {
  65. message_paypal_error_to_admin("Not a valid context id", $data);
  66. die;
  67. }
  68. if (! $plugin_instance = $DB->get_record("enrol", array("id"=>$data->instanceid, "status"=>0))) {
  69. message_paypal_error_to_admin("Not a valid instance id", $data);
  70. die;
  71. }
  72. $plugin = enrol_get_plugin('paypal');
  73. /// Open a connection back to PayPal to validate the data
  74. $header = '';
  75. $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
  76. $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
  77. $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
  78. $paypaladdr = empty($CFG->usepaypalsandbox) ? 'www.paypal.com' : 'www.sandbox.paypal.com';
  79. $fp = fsockopen ($paypaladdr, 80, $errno, $errstr, 30);
  80. if (!$fp) { /// Could not open a socket to PayPal - FAIL
  81. echo "<p>Error: could not access paypal.com</p>";
  82. message_paypal_error_to_admin("Could not access paypal.com to verify payment", $data);
  83. die;
  84. }
  85. /// Connection is OK, so now we post the data to validate it
  86. fputs ($fp, $header.$req);
  87. /// Now read the response and check if everything is OK.
  88. while (!feof($fp)) {
  89. $result = fgets($fp, 1024);
  90. if (strcmp($result, "VERIFIED") == 0) { // VALID PAYMENT!
  91. // check the payment_status and payment_reason
  92. // If status is not completed or pending then unenrol the student if already enrolled
  93. // and notify admin
  94. if ($data->payment_status != "Completed" and $data->payment_status != "Pending") {
  95. $plugin->unenrol_user($plugin_instance, $data->userid);
  96. message_paypal_error_to_admin("Status not completed or pending. User unenrolled from course", $data);
  97. die;
  98. }
  99. // If currency is incorrectly set then someone maybe trying to cheat the system
  100. if ($data->mc_currency != $plugin_instance->currency) {
  101. message_paypal_error_to_admin("Currency does not match course settings, received: ".$data->mc_currency, $data);
  102. die;
  103. }
  104. // If status is pending and reason is other than echeck then we are on hold until further notice
  105. // Email user to let them know. Email admin.
  106. if ($data->payment_status == "Pending" and $data->pending_reason != "echeck") {
  107. $eventdata = new stdClass();
  108. $eventdata->modulename = 'moodle';
  109. $eventdata->component = 'enrol_paypal';
  110. $eventdata->name = 'paypal_enrolment';
  111. $eventdata->userfrom = get_admin();
  112. $eventdata->userto = $user;
  113. $eventdata->subject = "Moodle: PayPal payment";
  114. $eventdata->fullmessage = "Your PayPal payment is pending.";
  115. $eventdata->fullmessageformat = FORMAT_PLAIN;
  116. $eventdata->fullmessagehtml = '';
  117. $eventdata->smallmessage = '';
  118. message_send($eventdata);
  119. message_paypal_error_to_admin("Payment pending", $data);
  120. die;
  121. }
  122. // If our status is not completed or not pending on an echeck clearance then ignore and die
  123. // This check is redundant at present but may be useful if paypal extend the return codes in the future
  124. if (! ( $data->payment_status == "Completed" or
  125. ($data->payment_status == "Pending" and $data->pending_reason == "echeck") ) ) {
  126. die;
  127. }
  128. // At this point we only proceed with a status of completed or pending with a reason of echeck
  129. if ($existing = $DB->get_record("enrol_paypal", array("txn_id"=>$data->txn_id))) { // Make sure this transaction doesn't exist already
  130. message_paypal_error_to_admin("Transaction $data->txn_id is being repeated!", $data);
  131. die;
  132. }
  133. if ($data->business != $plugin->get_config('paypalbusiness')) { // Check that the email is the one we want it to be
  134. message_paypal_error_to_admin("Business email is {$data->business} (not ".
  135. $plugin->get_config('paypalbusiness').")", $data);
  136. die;
  137. }
  138. if (!$user = $DB->get_record('user', array('id'=>$data->userid))) { // Check that user exists
  139. message_paypal_error_to_admin("User $data->userid doesn't exist", $data);
  140. die;
  141. }
  142. if (!$course = $DB->get_record('course', array('id'=>$data->courseid))) { // Check that course exists
  143. message_paypal_error_to_admin("Course $data->courseid doesn't exist", $data);;
  144. die;
  145. }
  146. // Check that amount paid is the correct amount
  147. if ( (float) $plugin_instance->cost <= 0 ) {
  148. $cost = (float) $plugin->get_config('cost');
  149. } else {
  150. $cost = (float) $plugin_instance->cost;
  151. }
  152. if ($data->payment_gross < $cost) {
  153. $cost = format_float($cost, 2);
  154. message_paypal_error_to_admin("Amount paid is not enough ($data->payment_gross < $cost))", $data);
  155. die;
  156. }
  157. // ALL CLEAR !
  158. $DB->insert_record("enrol_paypal", $data);
  159. if ($plugin_instance->enrolperiod) {
  160. $timestart = time();
  161. $timeend = $timestart + $plugin_instance->enrolperiod;
  162. } else {
  163. $timestart = 0;
  164. $timeend = 0;
  165. }
  166. // Enrol user
  167. $plugin->enrol_user($plugin_instance, $user->id, $plugin_instance->roleid, $timestart, $timeend);
  168. // Pass $view=true to filter hidden caps if the user cannot see them
  169. if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC',
  170. '', '', '', '', false, true)) {
  171. $users = sort_by_roleassignment_authority($users, $context);
  172. $teacher = array_shift($users);
  173. } else {
  174. $teacher = false;
  175. }
  176. $mailstudents = $plugin->get_config('mailstudents');
  177. $mailteachers = $plugin->get_config('mailteachers');
  178. $mailadmins = $plugin->get_config('mailadmins');
  179. if (!empty($mailstudents)) {
  180. $a->coursename = $course->fullname;
  181. $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id";
  182. $eventdata = new stdClass();
  183. $eventdata->modulename = 'moodle';
  184. $eventdata->component = 'enrol_paypal';
  185. $eventdata->name = 'paypal_enrolment';
  186. $eventdata->userfrom = $teacher;
  187. $eventdata->userto = $user;
  188. $eventdata->subject = get_string("enrolmentnew", '', $course->shortname);
  189. $eventdata->fullmessage = get_string('welcometocoursetext', '', $a);
  190. $eventdata->fullmessageformat = FORMAT_PLAIN;
  191. $eventdata->fullmessagehtml = '';
  192. $eventdata->smallmessage = '';
  193. message_send($eventdata);
  194. }
  195. if (!empty($mailteachers)) {
  196. $a->course = $course->fullname;
  197. $a->user = fullname($user);
  198. $eventdata = new stdClass();
  199. $eventdata->modulename = 'moodle';
  200. $eventdata->component = 'enrol_paypal';
  201. $eventdata->name = 'paypal_enrolment';
  202. $eventdata->userfrom = $user;
  203. $eventdata->userto = $teacher;
  204. $eventdata->subject = get_string("enrolmentnew", '', $course->shortname);
  205. $eventdata->fullmessage = get_string('enrolmentnewuser', '', $a);
  206. $eventdata->fullmessageformat = FORMAT_PLAIN;
  207. $eventdata->fullmessagehtml = '';
  208. $eventdata->smallmessage = '';
  209. message_send($eventdata);
  210. }
  211. if (!empty($mailadmins)) {
  212. $a->course = $course->fullname;
  213. $a->user = fullname($user);
  214. $admins = get_admins();
  215. foreach ($admins as $admin) {
  216. $eventdata = new stdClass();
  217. $eventdata->modulename = 'moodle';
  218. $eventdata->component = 'enrol_paypal';
  219. $eventdata->name = 'paypal_enrolment';
  220. $eventdata->userfrom = $user;
  221. $eventdata->userto = $admin;
  222. $eventdata->subject = get_string("enrolmentnew", '', $course->shortname);
  223. $eventdata->fullmessage = get_string('enrolmentnewuser', '', $a);
  224. $eventdata->fullmessageformat = FORMAT_PLAIN;
  225. $eventdata->fullmessagehtml = '';
  226. $eventdata->smallmessage = '';
  227. message_send($eventdata);
  228. }
  229. }
  230. } else if (strcmp ($result, "INVALID") == 0) { // ERROR
  231. $DB->insert_record("enrol_paypal", $data, false);
  232. message_paypal_error_to_admin("Received an invalid payment notification!! (Fake payment?)", $data);
  233. }
  234. }
  235. fclose($fp);
  236. exit;
  237. //--- HELPER FUNCTIONS --------------------------------------------------------------------------------------
  238. function message_paypal_error_to_admin($subject, $data) {
  239. echo $subject;
  240. $admin = get_admin();
  241. $site = get_site();
  242. $message = "$site->fullname: Transaction failed.\n\n$subject\n\n";
  243. foreach ($data as $key => $value) {
  244. $message .= "$key => $value\n";
  245. }
  246. $eventdata = new stdClass();
  247. $eventdata->modulename = 'moodle';
  248. $eventdata->component = 'enrol_paypal';
  249. $eventdata->name = 'paypal_enrolment';
  250. $eventdata->userfrom = $admin;
  251. $eventdata->userto = $admin;
  252. $eventdata->subject = "PAYPAL ERROR: ".$subject;
  253. $eventdata->fullmessage = $message;
  254. $eventdata->fullmessageformat = FORMAT_PLAIN;
  255. $eventdata->fullmessagehtml = '';
  256. $eventdata->smallmessage = '';
  257. message_send($eventdata);
  258. }