PageRenderTime 27ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/enrol/paypal/ipn.php

https://github.com/nadavkav/MoodleTAO
PHP | 232 lines | 138 code | 62 blank | 32 comment | 38 complexity | 0997165ee4ec814c1afdcd7bdb7c0ab5 MD5 | raw file
  1. <?php // $Id$
  2. /**
  3. * Listens for Instant Payment Notification from PayPal
  4. *
  5. * This script waits for Payment notification from PayPal,
  6. * then double checks that data by sending it back to PayPal.
  7. * If PayPal verifies this then it sets up the enrolment for that
  8. *
  9. * Set the $user->timeaccess course array
  10. *
  11. * @param user referenced object, must contain $user->id already set
  12. */
  13. require("../../config.php");
  14. require("enrol.php");
  15. /// Keep out casual intruders
  16. if (empty($_POST) or !empty($_GET)) {
  17. error("Sorry, you can not use the script that way.");
  18. }
  19. /// Read all the data from PayPal and get it ready for later;
  20. /// we expect only valid UTF-8 encoding, it is the responsibility
  21. /// of user to set it up properly in PayPal business acount,
  22. /// it is documented in docs wiki.
  23. $req = 'cmd=_notify-validate';
  24. $data = new object();
  25. foreach ($_POST as $key => $value) {
  26. $value = stripslashes($value);
  27. $req .= "&$key=".urlencode($value);
  28. $data->$key = $value;
  29. }
  30. $custom = explode('-', $data->custom);
  31. $data->userid = (int)$custom[0];
  32. $data->courseid = (int)$custom[1];
  33. $data->payment_gross = $data->mc_gross;
  34. $data->payment_currency = $data->mc_currency;
  35. $data->timeupdated = time();
  36. /// get the user and course records
  37. if (! $user = get_record("user", "id", $data->userid) ) {
  38. email_paypal_error_to_admin("Not a valid user id", $data);
  39. die;
  40. }
  41. if (! $course = get_record("course", "id", $data->courseid) ) {
  42. email_paypal_error_to_admin("Not a valid course id", $data);
  43. die;
  44. }
  45. if (! $context = get_context_instance(CONTEXT_COURSE, $course->id)) {
  46. email_paypal_error_to_admin("Not a valid context id", $data);
  47. die;
  48. }
  49. /// Open a connection back to PayPal to validate the data
  50. $header = '';
  51. $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
  52. $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
  53. $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
  54. $paypaladdr = empty($CFG->usepaypalsandbox) ? 'www.paypal.com' : 'www.sandbox.paypal.com';
  55. $fp = fsockopen ($paypaladdr, 80, $errno, $errstr, 30);
  56. if (!$fp) { /// Could not open a socket to PayPal - FAIL
  57. echo "<p>Error: could not access paypal.com</p>";
  58. email_paypal_error_to_admin("Could not access paypal.com to verify payment", $data);
  59. die;
  60. }
  61. /// Connection is OK, so now we post the data to validate it
  62. fputs ($fp, $header.$req);
  63. /// Now read the response and check if everything is OK.
  64. while (!feof($fp)) {
  65. $result = fgets($fp, 1024);
  66. if (strcmp($result, "VERIFIED") == 0) { // VALID PAYMENT!
  67. // check the payment_status and payment_reason
  68. // If status is not completed or pending then unenrol the student if already enrolled
  69. // and notify admin
  70. if ($data->payment_status != "Completed" and $data->payment_status != "Pending") {
  71. role_unassign(0, $data->userid, 0, $context->id);
  72. email_paypal_error_to_admin("Status not completed or pending. User unenrolled from course", $data);
  73. die;
  74. }
  75. // If currency is incorrectly set then someone maybe trying to cheat the system
  76. if ($data->mc_currency != $course->currency) {
  77. email_paypal_error_to_admin("Currency does not match course settings, received: ".addslashes($data->mc_currency), $data);
  78. die;
  79. }
  80. // If status is pending and reason is other than echeck then we are on hold until further notice
  81. // Email user to let them know. Email admin.
  82. if ($data->payment_status == "Pending" and $data->pending_reason != "echeck") {
  83. email_to_user($user, get_admin(), "Moodle: PayPal payment", "Your PayPal payment is pending.");
  84. email_paypal_error_to_admin("Payment pending", $data);
  85. die;
  86. }
  87. // If our status is not completed or not pending on an echeck clearance then ignore and die
  88. // This check is redundant at present but may be useful if paypal extend the return codes in the future
  89. if (! ( $data->payment_status == "Completed" or
  90. ($data->payment_status == "Pending" and $data->pending_reason == "echeck") ) ) {
  91. die;
  92. }
  93. // At this point we only proceed with a status of completed or pending with a reason of echeck
  94. if ($existing = get_record("enrol_paypal", "txn_id", addslashes($data->txn_id))) { // Make sure this transaction doesn't exist already
  95. email_paypal_error_to_admin("Transaction $data->txn_id is being repeated!", $data);
  96. die;
  97. }
  98. if ($data->business != $CFG->enrol_paypalbusiness) { // Check that the email is the one we want it to be
  99. email_paypal_error_to_admin("Business email is $data->business (not $CFG->enrol_paypalbusiness)", $data);
  100. die;
  101. }
  102. if (!$user = get_record('user', 'id', $data->userid)) { // Check that user exists
  103. email_paypal_error_to_admin("User $data->userid doesn't exist", $data);
  104. die;
  105. }
  106. if (!$course = get_record('course', 'id', $data->courseid)) { // Check that course exists
  107. email_paypal_error_to_admin("Course $data->courseid doesn't exist", $data);;
  108. die;
  109. }
  110. // Check that amount paid is the correct amount
  111. if ( (float) $course->cost < 0 ) {
  112. $cost = (float) $CFG->enrol_cost;
  113. } else {
  114. $cost = (float) $course->cost;
  115. }
  116. if ($data->payment_gross < $cost) {
  117. $cost = format_float($cost, 2);
  118. email_paypal_error_to_admin("Amount paid is not enough ($data->payment_gross < $cost))", $data);
  119. die;
  120. }
  121. // ALL CLEAR !
  122. if (!insert_record("enrol_paypal", addslashes_object($data))) { // Insert a transaction record
  123. email_paypal_error_to_admin("Error while trying to insert valid transaction", $data);
  124. }
  125. if (!enrol_into_course($course, $user, 'paypal')) {
  126. email_paypal_error_to_admin("Error while trying to enrol ".fullname($user)." in '$course->fullname'", $data);
  127. die;
  128. } else {
  129. $teacher = get_teacher($course->id);
  130. if (!empty($CFG->enrol_mailstudents)) {
  131. $a->coursename = $course->fullname;
  132. $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id";
  133. email_to_user($user, $teacher, get_string("enrolmentnew", '', $course->shortname),
  134. get_string('welcometocoursetext', '', $a));
  135. }
  136. if (!empty($CFG->enrol_mailteachers)) {
  137. $a->course = $course->fullname;
  138. $a->user = fullname($user);
  139. email_to_user($teacher, $user, get_string("enrolmentnew", '', $course->shortname),
  140. get_string('enrolmentnewuser', '', $a));
  141. }
  142. if (!empty($CFG->enrol_mailadmins)) {
  143. $a->course = $course->fullname;
  144. $a->user = fullname($user);
  145. $admins = get_admins();
  146. foreach ($admins as $admin) {
  147. email_to_user($admin, $user, get_string("enrolmentnew", '', $course->shortname),
  148. get_string('enrolmentnewuser', '', $a));
  149. }
  150. }
  151. }
  152. } else if (strcmp ($result, "INVALID") == 0) { // ERROR
  153. insert_record("enrol_paypal", addslashes_object($data), false);
  154. email_paypal_error_to_admin("Received an invalid payment notification!! (Fake payment?)", $data);
  155. }
  156. }
  157. fclose($fp);
  158. exit;
  159. /// FUNCTIONS //////////////////////////////////////////////////////////////////
  160. function email_paypal_error_to_admin($subject, $data) {
  161. $admin = get_admin();
  162. $site = get_site();
  163. $message = "$site->fullname: Transaction failed.\n\n$subject\n\n";
  164. foreach ($data as $key => $value) {
  165. $message .= "$key => $value\n";
  166. }
  167. email_to_user($admin, $admin, "PAYPAL ERROR: ".$subject, $message);
  168. }
  169. ?>