4 * Listens for Instant Payment Notification from PayPal
6 * This script waits for Payment notification from PayPal,
7 * then double checks that data by sending it back to PayPal.
8 * If PayPal verifies this then it sets up the enrolment for that
10 * Set the $user->timeaccess course array
12 * @param user referenced object, must contain $user->id already set
16 require("../../config.php");
18 require_once($CFG->libdir.'/eventslib.php');
20 /// Keep out casual intruders
21 if (empty($_POST) or !empty($_GET)) {
22 print_error("Sorry, you can not use the script that way.");
25 /// Read all the data from PayPal and get it ready for later;
26 /// we expect only valid UTF-8 encoding, it is the responsibility
27 /// of user to set it up properly in PayPal business acount,
28 /// it is documented in docs wiki.
30 $req = 'cmd=_notify-validate';
34 foreach ($_POST as $key => $value) {
35 $req .= "&$key=".urlencode($value);
39 $custom = explode('-', $data->custom);
40 $data->userid = (int)$custom[0];
41 $data->courseid = (int)$custom[1];
42 $data->payment_gross = $data->mc_gross;
43 $data->payment_currency = $data->mc_currency;
44 $data->timeupdated = time();
47 /// get the user and course records
49 if (! $user = $DB->get_record("user", array("id"=>$data->userid))) {
50 message_paypal_error_to_admin("Not a valid user id", $data);
54 if (! $course = $DB->get_record("course", array("id"=>$data->courseid))) {
55 message_paypal_error_to_admin("Not a valid course id", $data);
59 if (! $context = get_context_instance(CONTEXT_COURSE, $course->id)) {
60 message_paypal_error_to_admin("Not a valid context id", $data);
64 /// Open a connection back to PayPal to validate the data
67 $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
68 $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
69 $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
70 $paypaladdr = empty($CFG->usepaypalsandbox) ? 'www.paypal.com' : 'www.sandbox.paypal.com';
71 $fp = fsockopen ($paypaladdr, 80, $errno, $errstr, 30);
73 if (!$fp) { /// Could not open a socket to PayPal - FAIL
74 echo "<p>Error: could not access paypal.com</p>";
75 message_paypal_error_to_admin("Could not access paypal.com to verify payment", $data);
79 /// Connection is OK, so now we post the data to validate it
81 fputs ($fp, $header.$req);
83 /// Now read the response and check if everything is OK.
86 $result = fgets($fp, 1024);
87 if (strcmp($result, "VERIFIED") == 0) { // VALID PAYMENT!
90 // check the payment_status and payment_reason
92 // If status is not completed or pending then unenrol the student if already enrolled
95 if ($data->payment_status != "Completed" and $data->payment_status != "Pending") {
96 role_unassign_all(array('userid'=>$data->userid, 'contextid'=>$context->id, 'component'=>'enrol_paypal'), true, true);
97 message_paypal_error_to_admin("Status not completed or pending. User unenrolled from course", $data);
101 // If currency is incorrectly set then someone maybe trying to cheat the system
103 if ($data->mc_currency != $course->currency) {
104 email_paypal_error_to_admin("Currency does not match course settings, received: ".addslashes($data->mc_currency), $data);
108 // If status is pending and reason is other than echeck then we are on hold until further notice
109 // Email user to let them know. Email admin.
111 if ($data->payment_status == "Pending" and $data->pending_reason != "echeck") {
112 $eventdata = new object();
113 $eventdata->modulename = 'moodle';
114 $eventdata->userfrom = get_admin();
115 $eventdata->userto = $user;
116 $eventdata->subject = "Moodle: PayPal payment";
117 $eventdata->fullmessage = "Your PayPal payment is pending.";
118 $eventdata->fullmessageformat = FORMAT_PLAIN;
119 $eventdata->fullmessagehtml = '';
120 $eventdata->smallmessage = '';
121 message_send($eventdata);
123 message_paypal_error_to_admin("Payment pending", $data);
127 // If our status is not completed or not pending on an echeck clearance then ignore and die
128 // This check is redundant at present but may be useful if paypal extend the return codes in the future
130 if (! ( $data->payment_status == "Completed" or
131 ($data->payment_status == "Pending" and $data->pending_reason == "echeck") ) ) {
135 // At this point we only proceed with a status of completed or pending with a reason of echeck
139 if ($existing = $DB->get_record("enrol_paypal", array("txn_id"=>$data->txn_id))) { // Make sure this transaction doesn't exist already
140 message_paypal_error_to_admin("Transaction $data->txn_id is being repeated!", $data);
145 if ($data->business != $CFG->enrol_paypalbusiness) { // Check that the email is the one we want it to be
146 message_paypal_error_to_admin("Business email is $data->business (not $CFG->enrol_paypalbusiness)", $data);
151 if (!$user = $DB->get_record('user', array('id'=>$data->userid))) { // Check that user exists
152 message_paypal_error_to_admin("User $data->userid doesn't exist", $data);
156 if (!$course = $DB->get_record('course', array('id'=>$data->courseid))) { // Check that course exists
157 message_paypal_error_to_admin("Course $data->courseid doesn't exist", $data);;
161 // Check that amount paid is the correct amount
162 if ( (float) $course->cost < 0 ) {
163 $cost = (float) $CFG->enrol_cost;
165 $cost = (float) $course->cost;
168 if ($data->payment_gross < $cost) {
169 $cost = format_float($cost, 2);
170 message_paypal_error_to_admin("Amount paid is not enough ($data->payment_gross < $cost))", $data);
177 $DB->insert_record("enrol_paypal", $data);
179 if (!enrol_into_course($course, $user, 'paypal')) {
180 message_paypal_error_to_admin("Error while trying to enrol ".fullname($user)." in '$course->fullname'", $data);
183 // Pass $view=true to filter hidden caps if the user cannot see them
184 if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC',
185 '', '', '', '', false, true)) {
186 $users = sort_by_roleassignment_authority($users, $context);
187 $teacher = array_shift($users);
193 if (!empty($CFG->enrol_mailstudents)) {
194 $a->coursename = $course->fullname;
195 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id";
197 $eventdata = new object();
198 $eventdata->modulename = 'moodle';
199 $eventdata->userfrom = $teacher;
200 $eventdata->userto = $user;
201 $eventdata->subject = get_string("enrolmentnew", '', $course->shortname);
202 $eventdata->fullmessage = get_string('welcometocoursetext', '', $a);
203 $eventdata->fullmessageformat = FORMAT_PLAIN;
204 $eventdata->fullmessagehtml = '';
205 $eventdata->smallmessage = '';
206 message_send($eventdata);
210 if (!empty($CFG->enrol_mailteachers)) {
211 $a->course = $course->fullname;
212 $a->user = fullname($user);
214 $eventdata = new object();
215 $eventdata->modulename = 'moodle';
216 $eventdata->userfrom = $user;
217 $eventdata->userto = $teacher;
218 $eventdata->subject = get_string("enrolmentnew", '', $course->shortname);
219 $eventdata->fullmessage = get_string('enrolmentnewuser', '', $a);
220 $eventdata->fullmessageformat = FORMAT_PLAIN;
221 $eventdata->fullmessagehtml = '';
222 $eventdata->smallmessage = '';
223 message_send($eventdata);
226 if (!empty($CFG->enrol_mailadmins)) {
227 $a->course = $course->fullname;
228 $a->user = fullname($user);
229 $admins = get_admins();
230 foreach ($admins as $admin) {
231 $eventdata = new object();
232 $eventdata->modulename = 'moodle';
233 $eventdata->userfrom = $user;
234 $eventdata->userto = $admin;
235 $eventdata->subject = get_string("enrolmentnew", '', $course->shortname);
236 $eventdata->fullmessage = get_string('enrolmentnewuser', '', $a);
237 $eventdata->fullmessageformat = FORMAT_PLAIN;
238 $eventdata->fullmessagehtml = '';
239 $eventdata->smallmessage = '';
240 message_send($eventdata);
247 } else if (strcmp ($result, "INVALID") == 0) { // ERROR
248 $DB->insert_record("enrol_paypal", $data, false);
249 message_paypal_error_to_admin("Received an invalid payment notification!! (Fake payment?)", $data);
258 /// FUNCTIONS //////////////////////////////////////////////////////////////////
261 function message_paypal_error_to_admin($subject, $data) {
262 $admin = get_admin();
265 $message = "$site->fullname: Transaction failed.\n\n$subject\n\n";
267 foreach ($data as $key => $value) {
268 $message .= "$key => $value\n";
271 $eventdata = new object();
272 $eventdata->modulename = 'moodle';
273 $eventdata->userfrom = $admin;
274 $eventdata->userto = $admin;
275 $eventdata->subject = "PAYPAL ERROR: ".$subject;
276 $eventdata->fullmessage = $message;
277 $eventdata->fullmessageformat = FORMAT_PLAIN;
278 $eventdata->fullmessagehtml = '';
279 $eventdata->smallmessage = '';
280 message_send($eventdata);