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 * Listens for Instant Payment Notification from PayPal
20 * This script waits for Payment notification from PayPal,
21 * then double checks that data by sending it back to PayPal.
22 * If PayPal verifies this then it sets up the enrolment for that
25 * @package enrol_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
31 // Disable moodle specific debug messages and any errors in output,
32 // comment out when debugging or better look into error log!
33 define('NO_DEBUG_DISPLAY', true);
35 require("../../config.php");
36 require_once("lib.php");
37 require_once($CFG->libdir
.'/eventslib.php');
38 require_once($CFG->libdir
.'/enrollib.php');
39 require_once($CFG->libdir
. '/filelib.php');
41 // PayPal does not like when we return error messages here,
42 // the custom handler just logs exceptions and stops.
43 set_exception_handler('enrol_paypal_ipn_exception_handler');
45 /// Keep out casual intruders
46 if (empty($_POST) or !empty($_GET)) {
47 print_error("Sorry, you can not use the script that way.");
50 /// Read all the data from PayPal and get it ready for later;
51 /// we expect only valid UTF-8 encoding, it is the responsibility
52 /// of user to set it up properly in PayPal business account,
53 /// it is documented in docs wiki.
55 $req = 'cmd=_notify-validate';
57 $data = new stdClass();
59 foreach ($_POST as $key => $value) {
60 $req .= "&$key=".urlencode($value);
64 $custom = explode('-', $data->custom
);
65 $data->userid
= (int)$custom[0];
66 $data->courseid
= (int)$custom[1];
67 $data->instanceid
= (int)$custom[2];
68 $data->payment_gross
= $data->mc_gross
;
69 $data->payment_currency
= $data->mc_currency
;
70 $data->timeupdated
= time();
73 /// get the user and course records
75 if (! $user = $DB->get_record("user", array("id"=>$data->userid
))) {
76 message_paypal_error_to_admin("Not a valid user id", $data);
80 if (! $course = $DB->get_record("course", array("id"=>$data->courseid
))) {
81 message_paypal_error_to_admin("Not a valid course id", $data);
85 if (! $context = context_course
::instance($course->id
, IGNORE_MISSING
)) {
86 message_paypal_error_to_admin("Not a valid context id", $data);
90 if (! $plugin_instance = $DB->get_record("enrol", array("id"=>$data->instanceid
, "status"=>0))) {
91 message_paypal_error_to_admin("Not a valid instance id", $data);
95 $plugin = enrol_get_plugin('paypal');
97 /// Open a connection back to PayPal to validate the data
98 $paypaladdr = empty($CFG->usepaypalsandbox
) ?
'www.paypal.com' : 'www.sandbox.paypal.com';
101 'returntransfer' => true,
102 'httpheader' => array('application/x-www-form-urlencoded', "Host: $paypaladdr"),
104 'CURLOPT_HTTP_VERSION' => CURL_HTTP_VERSION_1_1
,
106 $location = "https://$paypaladdr/cgi-bin/webscr";
107 $result = $c->post($location, $req, $options);
109 if (!$result) { /// Could not connect to PayPal - FAIL
110 echo "<p>Error: could not access paypal.com</p>";
111 message_paypal_error_to_admin("Could not access paypal.com to verify payment", $data);
115 /// Connection is OK, so now we post the data to validate it
117 /// Now read the response and check if everything is OK.
119 if (strlen($result) > 0) {
120 if (strcmp($result, "VERIFIED") == 0) { // VALID PAYMENT!
123 // check the payment_status and payment_reason
125 // If status is not completed or pending then unenrol the student if already enrolled
128 if ($data->payment_status
!= "Completed" and $data->payment_status
!= "Pending") {
129 $plugin->unenrol_user($plugin_instance, $data->userid
);
130 message_paypal_error_to_admin("Status not completed or pending. User unenrolled from course", $data);
134 // If currency is incorrectly set then someone maybe trying to cheat the system
136 if ($data->mc_currency
!= $plugin_instance->currency
) {
137 message_paypal_error_to_admin("Currency does not match course settings, received: ".$data->mc_currency
, $data);
141 // If status is pending and reason is other than echeck then we are on hold until further notice
142 // Email user to let them know. Email admin.
144 if ($data->payment_status
== "Pending" and $data->pending_reason
!= "echeck") {
145 $eventdata = new stdClass();
146 $eventdata->modulename
= 'moodle';
147 $eventdata->component
= 'enrol_paypal';
148 $eventdata->name
= 'paypal_enrolment';
149 $eventdata->userfrom
= get_admin();
150 $eventdata->userto
= $user;
151 $eventdata->subject
= "Moodle: PayPal payment";
152 $eventdata->fullmessage
= "Your PayPal payment is pending.";
153 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
154 $eventdata->fullmessagehtml
= '';
155 $eventdata->smallmessage
= '';
156 message_send($eventdata);
158 message_paypal_error_to_admin("Payment pending", $data);
162 // If our status is not completed or not pending on an echeck clearance then ignore and die
163 // This check is redundant at present but may be useful if paypal extend the return codes in the future
165 if (! ( $data->payment_status
== "Completed" or
166 ($data->payment_status
== "Pending" and $data->pending_reason
== "echeck") ) ) {
170 // At this point we only proceed with a status of completed or pending with a reason of echeck
174 if ($existing = $DB->get_record("enrol_paypal", array("txn_id"=>$data->txn_id
))) { // Make sure this transaction doesn't exist already
175 message_paypal_error_to_admin("Transaction $data->txn_id is being repeated!", $data);
180 if (core_text
::strtolower($data->business
) !== core_text
::strtolower($plugin->get_config('paypalbusiness'))) { // Check that the email is the one we want it to be
181 message_paypal_error_to_admin("Business email is {$data->business} (not ".
182 $plugin->get_config('paypalbusiness').")", $data);
187 if (!$user = $DB->get_record('user', array('id'=>$data->userid
))) { // Check that user exists
188 message_paypal_error_to_admin("User $data->userid doesn't exist", $data);
192 if (!$course = $DB->get_record('course', array('id'=>$data->courseid
))) { // Check that course exists
193 message_paypal_error_to_admin("Course $data->courseid doesn't exist", $data);
197 $coursecontext = context_course
::instance($course->id
, IGNORE_MISSING
);
199 // Check that amount paid is the correct amount
200 if ( (float) $plugin_instance->cost
<= 0 ) {
201 $cost = (float) $plugin->get_config('cost');
203 $cost = (float) $plugin_instance->cost
;
206 // Use the same rounding of floats as on the enrol form.
207 $cost = format_float($cost, 2, false);
209 if ($data->payment_gross
< $cost) {
210 message_paypal_error_to_admin("Amount paid is not enough ($data->payment_gross < $cost))", $data);
217 $DB->insert_record("enrol_paypal", $data);
219 if ($plugin_instance->enrolperiod
) {
221 $timeend = $timestart +
$plugin_instance->enrolperiod
;
228 $plugin->enrol_user($plugin_instance, $user->id
, $plugin_instance->roleid
, $timestart, $timeend);
230 // Pass $view=true to filter hidden caps if the user cannot see them
231 if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC',
232 '', '', '', '', false, true)) {
233 $users = sort_by_roleassignment_authority($users, $context);
234 $teacher = array_shift($users);
239 $mailstudents = $plugin->get_config('mailstudents');
240 $mailteachers = $plugin->get_config('mailteachers');
241 $mailadmins = $plugin->get_config('mailadmins');
242 $shortname = format_string($course->shortname
, true, array('context' => $context));
245 if (!empty($mailstudents)) {
247 $a->coursename
= format_string($course->fullname
, true, array('context' => $coursecontext));
248 $a->profileurl
= "$CFG->wwwroot/user/view.php?id=$user->id";
250 $eventdata = new stdClass();
251 $eventdata->modulename
= 'moodle';
252 $eventdata->component
= 'enrol_paypal';
253 $eventdata->name
= 'paypal_enrolment';
254 $eventdata->userfrom
= empty($teacher) ?
get_admin() : $teacher;
255 $eventdata->userto
= $user;
256 $eventdata->subject
= get_string("enrolmentnew", 'enrol', $shortname);
257 $eventdata->fullmessage
= get_string('welcometocoursetext', '', $a);
258 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
259 $eventdata->fullmessagehtml
= '';
260 $eventdata->smallmessage
= '';
261 message_send($eventdata);
265 if (!empty($mailteachers) && !empty($teacher)) {
266 $a->course
= format_string($course->fullname
, true, array('context' => $coursecontext));
267 $a->user
= fullname($user);
269 $eventdata = new stdClass();
270 $eventdata->modulename
= 'moodle';
271 $eventdata->component
= 'enrol_paypal';
272 $eventdata->name
= 'paypal_enrolment';
273 $eventdata->userfrom
= $user;
274 $eventdata->userto
= $teacher;
275 $eventdata->subject
= get_string("enrolmentnew", 'enrol', $shortname);
276 $eventdata->fullmessage
= get_string('enrolmentnewuser', 'enrol', $a);
277 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
278 $eventdata->fullmessagehtml
= '';
279 $eventdata->smallmessage
= '';
280 message_send($eventdata);
283 if (!empty($mailadmins)) {
284 $a->course
= format_string($course->fullname
, true, array('context' => $coursecontext));
285 $a->user
= fullname($user);
286 $admins = get_admins();
287 foreach ($admins as $admin) {
288 $eventdata = new stdClass();
289 $eventdata->modulename
= 'moodle';
290 $eventdata->component
= 'enrol_paypal';
291 $eventdata->name
= 'paypal_enrolment';
292 $eventdata->userfrom
= $user;
293 $eventdata->userto
= $admin;
294 $eventdata->subject
= get_string("enrolmentnew", 'enrol', $shortname);
295 $eventdata->fullmessage
= get_string('enrolmentnewuser', 'enrol', $a);
296 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
297 $eventdata->fullmessagehtml
= '';
298 $eventdata->smallmessage
= '';
299 message_send($eventdata);
303 } else if (strcmp ($result, "INVALID") == 0) { // ERROR
304 $DB->insert_record("enrol_paypal", $data, false);
305 message_paypal_error_to_admin("Received an invalid payment notification!! (Fake payment?)", $data);
312 //--- HELPER FUNCTIONS --------------------------------------------------------------------------------------
315 function message_paypal_error_to_admin($subject, $data) {
317 $admin = get_admin();
320 $message = "$site->fullname: Transaction failed.\n\n$subject\n\n";
322 foreach ($data as $key => $value) {
323 $message .= "$key => $value\n";
326 $eventdata = new stdClass();
327 $eventdata->modulename
= 'moodle';
328 $eventdata->component
= 'enrol_paypal';
329 $eventdata->name
= 'paypal_enrolment';
330 $eventdata->userfrom
= $admin;
331 $eventdata->userto
= $admin;
332 $eventdata->subject
= "PAYPAL ERROR: ".$subject;
333 $eventdata->fullmessage
= $message;
334 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
335 $eventdata->fullmessagehtml
= '';
336 $eventdata->smallmessage
= '';
337 message_send($eventdata);
341 * Silent exception handler.
343 * @param Exception $ex
344 * @return void - does not return. Terminates execution!
346 function enrol_paypal_ipn_exception_handler($ex) {
347 $info = get_exception_info($ex);
349 $logerrmsg = "enrol_paypal IPN exception handler: ".$info->message
;
350 if (debugging('', DEBUG_NORMAL
)) {
351 $logerrmsg .= ' Debug: '.$info->debuginfo
."\n".format_backtrace($info->backtrace
, true);
353 error_log($logerrmsg);