MDL-61392 enrol_paypal: Improve the IPN notifications handling
[moodle.git] / enrol / paypal / ipn.php
blobb3cde16be30334bd517d602ddf13cac3b22e0d10
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.
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/>.
17 /**
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
23 * user.
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 // @codingStandardsIgnoreLine This script does not require login.
36 require("../../config.php");
37 require_once("lib.php");
38 require_once($CFG->libdir.'/eventslib.php');
39 require_once($CFG->libdir.'/enrollib.php');
40 require_once($CFG->libdir . '/filelib.php');
42 // PayPal does not like when we return error messages here,
43 // the custom handler just logs exceptions and stops.
44 set_exception_handler(\enrol_paypal\util::get_exception_handler());
46 // Make sure we are enabled in the first place.
47 if (!enrol_is_enabled('paypal')) {
48 http_response_code(503);
49 throw new moodle_exception('errdisabled', 'enrol_paypal');
52 /// Keep out casual intruders
53 if (empty($_POST) or !empty($_GET)) {
54 http_response_code(400);
55 throw new moodle_exception('invalidrequest', 'core_error');
58 /// Read all the data from PayPal and get it ready for later;
59 /// we expect only valid UTF-8 encoding, it is the responsibility
60 /// of user to set it up properly in PayPal business account,
61 /// it is documented in docs wiki.
63 $req = 'cmd=_notify-validate';
65 $data = new stdClass();
67 foreach ($_POST as $key => $value) {
68 $req .= "&$key=".urlencode($value);
69 $data->$key = fix_utf8($value);
72 $custom = explode('-', $data->custom);
73 $data->userid = (int)$custom[0];
74 $data->courseid = (int)$custom[1];
75 $data->instanceid = (int)$custom[2];
76 $data->payment_gross = $data->mc_gross;
77 $data->payment_currency = $data->mc_currency;
78 $data->timeupdated = time();
80 $user = $DB->get_record("user", array("id" => $data->userid), "*", MUST_EXIST);
81 $course = $DB->get_record("course", array("id" => $data->courseid), "*", MUST_EXIST);
82 $context = context_course::instance($course->id, MUST_EXIST);
84 $PAGE->set_context($context);
86 $plugin_instance = $DB->get_record("enrol", array("id" => $data->instanceid, "enrol" => "paypal", "status" => 0), "*", MUST_EXIST);
87 $plugin = enrol_get_plugin('paypal');
89 /// Open a connection back to PayPal to validate the data
90 $paypaladdr = empty($CFG->usepaypalsandbox) ? 'www.paypal.com' : 'www.sandbox.paypal.com';
91 $c = new curl();
92 $options = array(
93 'returntransfer' => true,
94 'httpheader' => array('application/x-www-form-urlencoded', "Host: $paypaladdr"),
95 'timeout' => 30,
96 'CURLOPT_HTTP_VERSION' => CURL_HTTP_VERSION_1_1,
98 $location = "https://$paypaladdr/cgi-bin/webscr";
99 $result = $c->post($location, $req, $options);
101 if ($c->get_errno()) {
102 throw new moodle_exception('errpaypalconnect', 'enrol_paypal', '', array('url' => $paypaladdr, 'result' => $result),
103 json_encode($data));
106 /// Connection is OK, so now we post the data to validate it
108 /// Now read the response and check if everything is OK.
110 if (strlen($result) > 0) {
111 if (strcmp($result, "VERIFIED") == 0) { // VALID PAYMENT!
114 // check the payment_status and payment_reason
116 // If status is not completed or pending then unenrol the student if already enrolled
117 // and notify admin
119 if ($data->payment_status != "Completed" and $data->payment_status != "Pending") {
120 $plugin->unenrol_user($plugin_instance, $data->userid);
121 \enrol_paypal\util::message_paypal_error_to_admin("Status not completed or pending. User unenrolled from course",
122 $data);
123 die;
126 // If currency is incorrectly set then someone maybe trying to cheat the system
128 if ($data->mc_currency != $plugin_instance->currency) {
129 \enrol_paypal\util::message_paypal_error_to_admin(
130 "Currency does not match course settings, received: ".$data->mc_currency,
131 $data);
132 die;
135 // If status is pending and reason is other than echeck then we are on hold until further notice
136 // Email user to let them know. Email admin.
138 if ($data->payment_status == "Pending" and $data->pending_reason != "echeck") {
139 $eventdata = new \core\message\message();
140 $eventdata->courseid = empty($data->courseid) ? SITEID : $data->courseid;
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 \enrol_paypal\util::message_paypal_error_to_admin("Payment pending", $data);
154 die;
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") ) ) {
162 die;
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 \enrol_paypal\util::message_paypal_error_to_admin("Transaction $data->txn_id is being repeated!", $data);
171 die;
175 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
176 \enrol_paypal\util::message_paypal_error_to_admin("Business email is {$data->business} (not ".
177 $plugin->get_config('paypalbusiness').")", $data);
178 die;
182 if (!$user = $DB->get_record('user', array('id'=>$data->userid))) { // Check that user exists
183 \enrol_paypal\util::message_paypal_error_to_admin("User $data->userid doesn't exist", $data);
184 die;
187 if (!$course = $DB->get_record('course', array('id'=>$data->courseid))) { // Check that course exists
188 \enrol_paypal\util::message_paypal_error_to_admin("Course $data->courseid doesn't exist", $data);
189 die;
192 $coursecontext = context_course::instance($course->id, IGNORE_MISSING);
194 // Check that amount paid is the correct amount
195 if ( (float) $plugin_instance->cost <= 0 ) {
196 $cost = (float) $plugin->get_config('cost');
197 } else {
198 $cost = (float) $plugin_instance->cost;
201 // Use the same rounding of floats as on the enrol form.
202 $cost = format_float($cost, 2, false);
204 if ($data->payment_gross < $cost) {
205 \enrol_paypal\util::message_paypal_error_to_admin("Amount paid is not enough ($data->payment_gross < $cost))", $data);
206 die;
209 // Use the queried course's full name for the item_name field.
210 $data->item_name = $course->fullname;
212 // ALL CLEAR !
214 $DB->insert_record("enrol_paypal", $data);
216 if ($plugin_instance->enrolperiod) {
217 $timestart = time();
218 $timeend = $timestart + $plugin_instance->enrolperiod;
219 } else {
220 $timestart = 0;
221 $timeend = 0;
224 // Enrol user
225 $plugin->enrol_user($plugin_instance, $user->id, $plugin_instance->roleid, $timestart, $timeend);
227 // Pass $view=true to filter hidden caps if the user cannot see them
228 if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC',
229 '', '', '', '', false, true)) {
230 $users = sort_by_roleassignment_authority($users, $context);
231 $teacher = array_shift($users);
232 } else {
233 $teacher = false;
236 $mailstudents = $plugin->get_config('mailstudents');
237 $mailteachers = $plugin->get_config('mailteachers');
238 $mailadmins = $plugin->get_config('mailadmins');
239 $shortname = format_string($course->shortname, true, array('context' => $context));
242 if (!empty($mailstudents)) {
243 $a = new stdClass();
244 $a->coursename = format_string($course->fullname, true, array('context' => $coursecontext));
245 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id";
247 $eventdata = new \core\message\message();
248 $eventdata->courseid = $course->id;
249 $eventdata->modulename = 'moodle';
250 $eventdata->component = 'enrol_paypal';
251 $eventdata->name = 'paypal_enrolment';
252 $eventdata->userfrom = empty($teacher) ? core_user::get_noreply_user() : $teacher;
253 $eventdata->userto = $user;
254 $eventdata->subject = get_string("enrolmentnew", 'enrol', $shortname);
255 $eventdata->fullmessage = get_string('welcometocoursetext', '', $a);
256 $eventdata->fullmessageformat = FORMAT_PLAIN;
257 $eventdata->fullmessagehtml = '';
258 $eventdata->smallmessage = '';
259 message_send($eventdata);
263 if (!empty($mailteachers) && !empty($teacher)) {
264 $a->course = format_string($course->fullname, true, array('context' => $coursecontext));
265 $a->user = fullname($user);
267 $eventdata = new \core\message\message();
268 $eventdata->courseid = $course->id;
269 $eventdata->modulename = 'moodle';
270 $eventdata->component = 'enrol_paypal';
271 $eventdata->name = 'paypal_enrolment';
272 $eventdata->userfrom = $user;
273 $eventdata->userto = $teacher;
274 $eventdata->subject = get_string("enrolmentnew", 'enrol', $shortname);
275 $eventdata->fullmessage = get_string('enrolmentnewuser', 'enrol', $a);
276 $eventdata->fullmessageformat = FORMAT_PLAIN;
277 $eventdata->fullmessagehtml = '';
278 $eventdata->smallmessage = '';
279 message_send($eventdata);
282 if (!empty($mailadmins)) {
283 $a->course = format_string($course->fullname, true, array('context' => $coursecontext));
284 $a->user = fullname($user);
285 $admins = get_admins();
286 foreach ($admins as $admin) {
287 $eventdata = new \core\message\message();
288 $eventdata->courseid = $course->id;
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 throw new moodle_exception('erripninvalid', 'enrol_paypal', '', null, json_encode($data));