2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * @package enrol_paypal
19 * @copyright 2010 Eugene Venter
20 * @author Eugene Venter - based on code by others
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 * Listens for Instant Payment Notification from PayPal
27 * This script waits for Payment notification from PayPal,
28 * then double checks that data by sending it back to PayPal.
29 * If PayPal verifies this then it sets up the enrolment for that
35 require("../../config.php");
37 require_once($CFG->libdir.'/eventslib.php');
38 require_once($CFG->libdir.'/enrollib.php');
41 /// Keep out casual intruders
42 if (empty($_POST) or !empty($_GET)) {
43 print_error("Sorry, you can not use the script that way.");
46 /// Read all the data from PayPal and get it ready for later;
47 /// we expect only valid UTF-8 encoding, it is the responsibility
48 /// of user to set it up properly in PayPal business account,
49 /// it is documented in docs wiki.
51 $req = 'cmd=_notify-validate';
55 foreach ($_POST as $key => $value) {
56 $req .= "&$key=".urlencode($value);
60 $custom = explode('-', $data->custom);
61 $data->userid = (int)$custom[0];
62 $data->courseid = (int)$custom[1];
63 $data->instanceid = (int)$custom[2];
64 $data->payment_gross = $data->mc_gross;
65 $data->payment_currency = $data->mc_currency;
66 $data->timeupdated = time();
69 /// get the user and course records
71 if (! $user = $DB->get_record("user", array("id"=>$data->userid))) {
72 message_paypal_error_to_admin("Not a valid user id", $data);
76 if (! $course = $DB->get_record("course", array("id"=>$data->courseid))) {
77 message_paypal_error_to_admin("Not a valid course id", $data);
81 if (! $context = get_context_instance(CONTEXT_COURSE, $course->id)) {
82 message_paypal_error_to_admin("Not a valid context id", $data);
86 if (! $plugin_instance = $DB->get_record("enrol", array("id"=>$data->instanceid, "status"=>0))) {
87 message_paypal_error_to_admin("Not a valid instance id", $data);
91 $plugin = enrol_get_plugin('paypal');
93 /// Open a connection back to PayPal to validate the data
95 $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
96 $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
97 $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
98 $paypaladdr = empty($CFG->usepaypalsandbox) ? 'www.paypal.com' : 'www.sandbox.paypal.com';
99 $fp = fsockopen ($paypaladdr, 80, $errno, $errstr, 30);
101 if (!$fp) { /// Could not open a socket to PayPal - FAIL
102 echo "<p>Error: could not access paypal.com</p>";
103 message_paypal_error_to_admin("Could not access paypal.com to verify payment", $data);
107 /// Connection is OK, so now we post the data to validate it
109 fputs ($fp, $header.$req);
111 /// Now read the response and check if everything is OK.
114 $result = fgets($fp, 1024);
115 if (strcmp($result, "VERIFIED") == 0) { // VALID PAYMENT!
118 // check the payment_status and payment_reason
120 // If status is not completed or pending then unenrol the student if already enrolled
123 if ($data->payment_status != "Completed" and $data->payment_status != "Pending") {
124 $plugin->unenrol_user($plugin_instance, $data->userid);
125 message_paypal_error_to_admin("Status not completed or pending. User unenrolled from course", $data);
129 // If currency is incorrectly set then someone maybe trying to cheat the system
131 if ($data->mc_currency != $plugin_instance->currency) {
132 message_paypal_error_to_admin("Currency does not match course settings, received: ".addslashes($data->mc_currency), $data);
136 // If status is pending and reason is other than echeck then we are on hold until further notice
137 // Email user to let them know. Email admin.
139 if ($data->payment_status == "Pending" and $data->pending_reason != "echeck") {
140 $eventdata = new object();
141 $eventdata->modulename = 'moodle';
142 $eventdata->component = 'enrol_paypal';
143 $eventdata->name = 'paypal_enrolment';
144 $eventdata->userfrom = get_admin();
145 $eventdata->userto = $user;
146 $eventdata->subject = "Moodle: PayPal payment";
147 $eventdata->fullmessage = "Your PayPal payment is pending.";
148 $eventdata->fullmessageformat = FORMAT_PLAIN;
149 $eventdata->fullmessagehtml = '';
150 $eventdata->smallmessage = '';
151 message_send($eventdata);
153 message_paypal_error_to_admin("Payment pending", $data);
157 // If our status is not completed or not pending on an echeck clearance then ignore and die
158 // This check is redundant at present but may be useful if paypal extend the return codes in the future
160 if (! ( $data->payment_status == "Completed" or
161 ($data->payment_status == "Pending" and $data->pending_reason == "echeck") ) ) {
165 // At this point we only proceed with a status of completed or pending with a reason of echeck
169 if ($existing = $DB->get_record("enrol_paypal", array("txn_id"=>$data->txn_id))) { // Make sure this transaction doesn't exist already
170 message_paypal_error_to_admin("Transaction $data->txn_id is being repeated!", $data);
175 if ($data->business != $plugin->get_config('paypalbusiness')) { // Check that the email is the one we want it to be
176 message_paypal_error_to_admin("Business email is {$data->business} (not ".
177 $plugin->get_config('paypalbusiness').")", $data);
182 if (!$user = $DB->get_record('user', array('id'=>$data->userid))) { // Check that user exists
183 message_paypal_error_to_admin("User $data->userid doesn't exist", $data);
187 if (!$course = $DB->get_record('course', array('id'=>$data->courseid))) { // Check that course exists
188 message_paypal_error_to_admin("Course $data->courseid doesn't exist", $data);;
192 // Check that amount paid is the correct amount
193 if ( (float) $plugin_instance->cost <= 0 ) {
194 $cost = (float) $plugin->get_config('cost');
196 $cost = (float) $plugin_instance->cost;
199 if ($data->payment_gross < $cost) {
200 $cost = format_float($cost, 2);
201 message_paypal_error_to_admin("Amount paid is not enough ($data->payment_gross < $cost))", $data);
208 $DB->insert_record("enrol_paypal", $data);
210 if ($plugin_instance->enrolperiod) {
212 $timeend = $timestart + $plugin_instance->enrolperiod;
219 $plugin->enrol_user($plugin_instance, $user->id, $plugin_instance->roleid, $timestart, $timeend);
221 // Pass $view=true to filter hidden caps if the user cannot see them
222 if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC',
223 '', '', '', '', false, true)) {
224 $users = sort_by_roleassignment_authority($users, $context);
225 $teacher = array_shift($users);
230 $mailstudents = $plugin->get_config('mailstudents');
231 $mailteachers = $plugin->get_config('mailteachers');
232 $mailadmins = $plugin->get_config('mailadmins');
234 if (!empty($mailstudents)) {
235 $a->coursename = $course->fullname;
236 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id";
238 $eventdata = new object();
239 $eventdata->modulename = 'moodle';
240 $eventdata->component = 'enrol_paypal';
241 $eventdata->name = 'paypal_enrolment';
242 $eventdata->userfrom = $teacher;
243 $eventdata->userto = $user;
244 $eventdata->subject = get_string("enrolmentnew", '', $course->shortname);
245 $eventdata->fullmessage = get_string('welcometocoursetext', '', $a);
246 $eventdata->fullmessageformat = FORMAT_PLAIN;
247 $eventdata->fullmessagehtml = '';
248 $eventdata->smallmessage = '';
249 message_send($eventdata);
253 if (!empty($mailteachers)) {
254 $a->course = $course->fullname;
255 $a->user = fullname($user);
257 $eventdata = new object();
258 $eventdata->modulename = 'moodle';
259 $eventdata->component = 'enrol_paypal';
260 $eventdata->name = 'paypal_enrolment';
261 $eventdata->userfrom = $user;
262 $eventdata->userto = $teacher;
263 $eventdata->subject = get_string("enrolmentnew", '', $course->shortname);
264 $eventdata->fullmessage = get_string('enrolmentnewuser', '', $a);
265 $eventdata->fullmessageformat = FORMAT_PLAIN;
266 $eventdata->fullmessagehtml = '';
267 $eventdata->smallmessage = '';
268 message_send($eventdata);
271 if (!empty($mailadmins)) {
272 $a->course = $course->fullname;
273 $a->user = fullname($user);
274 $admins = get_admins();
275 foreach ($admins as $admin) {
276 $eventdata = new object();
277 $eventdata->modulename = 'moodle';
278 $eventdata->component = 'enrol_paypal';
279 $eventdata->name = 'paypal_enrolment';
280 $eventdata->userfrom = $user;
281 $eventdata->userto = $admin;
282 $eventdata->subject = get_string("enrolmentnew", '', $course->shortname);
283 $eventdata->fullmessage = get_string('enrolmentnewuser', '', $a);
284 $eventdata->fullmessageformat = FORMAT_PLAIN;
285 $eventdata->fullmessagehtml = '';
286 $eventdata->smallmessage = '';
287 message_send($eventdata);
291 } else if (strcmp ($result, "INVALID") == 0) { // ERROR
292 $DB->insert_record("enrol_paypal", $data, false);
293 message_paypal_error_to_admin("Received an invalid payment notification!! (Fake payment?)", $data);
301 //--- HELPER FUNCTIONS --------------------------------------------------------------------------------------
304 function message_paypal_error_to_admin($subject, $data) {
306 $admin = get_admin();
309 $message = "$site->fullname: Transaction failed.\n\n$subject\n\n";
311 foreach ($data as $key => $value) {
312 $message .= "$key => $value\n";
315 $eventdata = new object();
316 $eventdata->modulename = 'moodle';
317 $eventdata->component = 'enrol_paypal';
318 $eventdata->name = 'paypal_enrolment';
319 $eventdata->userfrom = $admin;
320 $eventdata->userto = $admin;
321 $eventdata->subject = "PAYPAL ERROR: ".$subject;
322 $eventdata->fullmessage = $message;
323 $eventdata->fullmessageformat = FORMAT_PLAIN;
324 $eventdata->fullmessagehtml = '';
325 $eventdata->smallmessage = '';
326 message_send($eventdata);