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
27 * @copyright 2010 Eugene Venter
28 * @author Eugene Venter - based on code by others
29 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33 require("../../config.php");
34 require_once("lib.php");
35 require_once($CFG->libdir
.'/eventslib.php');
36 require_once($CFG->libdir
.'/enrollib.php');
39 /// Keep out casual intruders
40 if (empty($_POST) or !empty($_GET)) {
41 print_error("Sorry, you can not use the script that way.");
44 /// Read all the data from PayPal and get it ready for later;
45 /// we expect only valid UTF-8 encoding, it is the responsibility
46 /// of user to set it up properly in PayPal business account,
47 /// it is documented in docs wiki.
49 $req = 'cmd=_notify-validate';
51 $data = new stdClass();
53 foreach ($_POST as $key => $value) {
54 $req .= "&$key=".urlencode($value);
58 $custom = explode('-', $data->custom
);
59 $data->userid
= (int)$custom[0];
60 $data->courseid
= (int)$custom[1];
61 $data->instanceid
= (int)$custom[2];
62 $data->payment_gross
= $data->mc_gross
;
63 $data->payment_currency
= $data->mc_currency
;
64 $data->timeupdated
= time();
67 /// get the user and course records
69 if (! $user = $DB->get_record("user", array("id"=>$data->userid
))) {
70 message_paypal_error_to_admin("Not a valid user id", $data);
74 if (! $course = $DB->get_record("course", array("id"=>$data->courseid
))) {
75 message_paypal_error_to_admin("Not a valid course id", $data);
79 if (! $context = get_context_instance(CONTEXT_COURSE
, $course->id
)) {
80 message_paypal_error_to_admin("Not a valid context id", $data);
84 if (! $plugin_instance = $DB->get_record("enrol", array("id"=>$data->instanceid
, "status"=>0))) {
85 message_paypal_error_to_admin("Not a valid instance id", $data);
89 $plugin = enrol_get_plugin('paypal');
91 /// Open a connection back to PayPal to validate the data
93 $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
94 $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
95 $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
96 $paypaladdr = empty($CFG->usepaypalsandbox
) ?
'www.paypal.com' : 'www.sandbox.paypal.com';
97 $fp = fsockopen ($paypaladdr, 80, $errno, $errstr, 30);
99 if (!$fp) { /// Could not open a socket to PayPal - FAIL
100 echo "<p>Error: could not access paypal.com</p>";
101 message_paypal_error_to_admin("Could not access paypal.com to verify payment", $data);
105 /// Connection is OK, so now we post the data to validate it
107 fputs ($fp, $header.$req);
109 /// Now read the response and check if everything is OK.
112 $result = fgets($fp, 1024);
113 if (strcmp($result, "VERIFIED") == 0) { // VALID PAYMENT!
116 // check the payment_status and payment_reason
118 // If status is not completed or pending then unenrol the student if already enrolled
121 if ($data->payment_status
!= "Completed" and $data->payment_status
!= "Pending") {
122 $plugin->unenrol_user($plugin_instance, $data->userid
);
123 message_paypal_error_to_admin("Status not completed or pending. User unenrolled from course", $data);
127 // If currency is incorrectly set then someone maybe trying to cheat the system
129 if ($data->mc_currency
!= $plugin_instance->currency
) {
130 message_paypal_error_to_admin("Currency does not match course settings, received: ".$data->mc_currency
, $data);
134 // If status is pending and reason is other than echeck then we are on hold until further notice
135 // Email user to let them know. Email admin.
137 if ($data->payment_status
== "Pending" and $data->pending_reason
!= "echeck") {
138 $eventdata = new stdClass();
139 $eventdata->modulename
= 'moodle';
140 $eventdata->component
= 'enrol_paypal';
141 $eventdata->name
= 'paypal_enrolment';
142 $eventdata->userfrom
= get_admin();
143 $eventdata->userto
= $user;
144 $eventdata->subject
= "Moodle: PayPal payment";
145 $eventdata->fullmessage
= "Your PayPal payment is pending.";
146 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
147 $eventdata->fullmessagehtml
= '';
148 $eventdata->smallmessage
= '';
149 message_send($eventdata);
151 message_paypal_error_to_admin("Payment pending", $data);
155 // If our status is not completed or not pending on an echeck clearance then ignore and die
156 // This check is redundant at present but may be useful if paypal extend the return codes in the future
158 if (! ( $data->payment_status
== "Completed" or
159 ($data->payment_status
== "Pending" and $data->pending_reason
== "echeck") ) ) {
163 // At this point we only proceed with a status of completed or pending with a reason of echeck
167 if ($existing = $DB->get_record("enrol_paypal", array("txn_id"=>$data->txn_id
))) { // Make sure this transaction doesn't exist already
168 message_paypal_error_to_admin("Transaction $data->txn_id is being repeated!", $data);
173 if ($data->business
!= $plugin->get_config('paypalbusiness')) { // Check that the email is the one we want it to be
174 message_paypal_error_to_admin("Business email is {$data->business} (not ".
175 $plugin->get_config('paypalbusiness').")", $data);
180 if (!$user = $DB->get_record('user', array('id'=>$data->userid
))) { // Check that user exists
181 message_paypal_error_to_admin("User $data->userid doesn't exist", $data);
185 if (!$course = $DB->get_record('course', array('id'=>$data->courseid
))) { // Check that course exists
186 message_paypal_error_to_admin("Course $data->courseid doesn't exist", $data);;
190 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
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');
233 $shortname = format_string($course->shortname
, true, array('context' => $context));
236 if (!empty($mailstudents)) {
237 $a->coursename
= format_string($course->fullname
, true, array('context' => $coursecontext));
238 $a->profileurl
= "$CFG->wwwroot/user/view.php?id=$user->id";
240 $eventdata = new stdClass();
241 $eventdata->modulename
= 'moodle';
242 $eventdata->component
= 'enrol_paypal';
243 $eventdata->name
= 'paypal_enrolment';
244 $eventdata->userfrom
= $teacher;
245 $eventdata->userto
= $user;
246 $eventdata->subject
= get_string("enrolmentnew", 'enrol', $shortname);
247 $eventdata->fullmessage
= get_string('welcometocoursetext', '', $a);
248 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
249 $eventdata->fullmessagehtml
= '';
250 $eventdata->smallmessage
= '';
251 message_send($eventdata);
255 if (!empty($mailteachers)) {
256 $a->course
= format_string($course->fullname
, true, array('context' => $coursecontext));
257 $a->user
= fullname($user);
259 $eventdata = new stdClass();
260 $eventdata->modulename
= 'moodle';
261 $eventdata->component
= 'enrol_paypal';
262 $eventdata->name
= 'paypal_enrolment';
263 $eventdata->userfrom
= $user;
264 $eventdata->userto
= $teacher;
265 $eventdata->subject
= get_string("enrolmentnew", 'enrol', $shortname);
266 $eventdata->fullmessage
= get_string('enrolmentnewuser', 'enrol', $a);
267 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
268 $eventdata->fullmessagehtml
= '';
269 $eventdata->smallmessage
= '';
270 message_send($eventdata);
273 if (!empty($mailadmins)) {
274 $a->course
= format_string($course->fullname
, true, array('context' => $coursecontext));
275 $a->user
= fullname($user);
276 $admins = get_admins();
277 foreach ($admins as $admin) {
278 $eventdata = new stdClass();
279 $eventdata->modulename
= 'moodle';
280 $eventdata->component
= 'enrol_paypal';
281 $eventdata->name
= 'paypal_enrolment';
282 $eventdata->userfrom
= $user;
283 $eventdata->userto
= $admin;
284 $eventdata->subject
= get_string("enrolmentnew", 'enrol', $shortname);
285 $eventdata->fullmessage
= get_string('enrolmentnewuser', 'enrol', $a);
286 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
287 $eventdata->fullmessagehtml
= '';
288 $eventdata->smallmessage
= '';
289 message_send($eventdata);
293 } else if (strcmp ($result, "INVALID") == 0) { // ERROR
294 $DB->insert_record("enrol_paypal", $data, false);
295 message_paypal_error_to_admin("Received an invalid payment notification!! (Fake payment?)", $data);
303 //--- HELPER FUNCTIONS --------------------------------------------------------------------------------------
306 function message_paypal_error_to_admin($subject, $data) {
308 $admin = get_admin();
311 $message = "$site->fullname: Transaction failed.\n\n$subject\n\n";
313 foreach ($data as $key => $value) {
314 $message .= "$key => $value\n";
317 $eventdata = new stdClass();
318 $eventdata->modulename
= 'moodle';
319 $eventdata->component
= 'enrol_paypal';
320 $eventdata->name
= 'paypal_enrolment';
321 $eventdata->userfrom
= $admin;
322 $eventdata->userto
= $admin;
323 $eventdata->subject
= "PAYPAL ERROR: ".$subject;
324 $eventdata->fullmessage
= $message;
325 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
326 $eventdata->fullmessagehtml
= '';
327 $eventdata->smallmessage
= '';
328 message_send($eventdata);