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");
19 /// Keep out casual intruders
20 if (empty($_POST) or !empty($_GET)) {
21 error("Sorry, you can not use the script that way.");
24 /// Read all the data from PayPal and get it ready for later;
25 /// we expect only valid UTF-8 encoding, it is the responsibility
26 /// of user to set it up properly in PayPal business acount,
27 /// it is documented in docs wiki.
29 $req = 'cmd=_notify-validate';
33 foreach ($_POST as $key => $value) {
34 $value = stripslashes($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 = get_record("user", "id", $data->userid
) ) {
50 email_paypal_error_to_admin("Not a valid user id", $data);
54 if (! $course = get_record("course", "id", $data->courseid
) ) {
55 email_paypal_error_to_admin("Not a valid course id", $data);
59 if (! $context = get_context_instance(CONTEXT_COURSE
, $course->id
)) {
60 email_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 email_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(0, $data->userid
, 0, $context->id
);
97 // force accessinfo refresh for users visiting this context...
98 mark_context_dirty($context->path
);
99 email_paypal_error_to_admin("Status not completed or pending. User unenrolled from course", $data);
103 // If status is pending and reason is other than echeck then we are on hold until further notice
104 // Email user to let them know. Email admin.
106 if ($data->payment_status
== "Pending" and $data->pending_reason
!= "echeck") {
107 email_to_user($user, get_admin(), "Moodle: PayPal payment", "Your PayPal payment is pending.");
108 email_paypal_error_to_admin("Payment pending", $data);
112 // If our status is not completed or not pending on an echeck clearance then ignore and die
113 // This check is redundant at present but may be useful if paypal extend the return codes in the future
115 if (! ( $data->payment_status
== "Completed" or
116 ($data->payment_status
== "Pending" and $data->pending_reason
== "echeck") ) ) {
120 // At this point we only proceed with a status of completed or pending with a reason of echeck
124 if ($existing = get_record("enrol_paypal", "txn_id", addslashes($data->txn_id
))) { // Make sure this transaction doesn't exist already
125 email_paypal_error_to_admin("Transaction $data->txn_id is being repeated!", $data);
130 if ($data->business
!= $CFG->enrol_paypalbusiness
) { // Check that the email is the one we want it to be
131 email_paypal_error_to_admin("Business email is $data->business (not $CFG->enrol_paypalbusiness)", $data);
136 if (!$user = get_record('user', 'id', $data->userid
)) { // Check that user exists
137 email_paypal_error_to_admin("User $data->userid doesn't exist", $data);
141 if (!$course = get_record('course', 'id', $data->courseid
)) { // Check that course exists
142 email_paypal_error_to_admin("Course $data->courseid doesn't exist", $data);;
146 // Check that amount paid is the correct amount
147 if ( (float) $course->cost
< 0 ) {
148 $cost = (float) $CFG->enrol_cost
;
150 $cost = (float) $course->cost
;
153 if ($data->payment_gross
< $cost) {
154 $cost = format_float($cost, 2);
155 email_paypal_error_to_admin("Amount paid is not enough ($data->payment_gross < $cost))", $data);
162 if (!insert_record("enrol_paypal", addslashes_object($data))) { // Insert a transaction record
163 email_paypal_error_to_admin("Error while trying to insert valid transaction", $data);
166 if (!enrol_into_course($course, $user, 'paypal')) {
167 email_paypal_error_to_admin("Error while trying to enrol ".fullname($user)." in '$course->fullname'", $data);
170 $teacher = get_teacher($course->id
);
172 if (!empty($CFG->enrol_mailstudents
)) {
173 $a->coursename
= $course->fullname
;
174 $a->profileurl
= "$CFG->wwwroot/user/view.php?id=$user->id";
175 email_to_user($user, $teacher, get_string("enrolmentnew", '', $course->shortname
),
176 get_string('welcometocoursetext', '', $a));
179 if (!empty($CFG->enrol_mailteachers
)) {
180 $a->course
= $course->fullname
;
181 $a->user
= fullname($user);
182 email_to_user($teacher, $user, get_string("enrolmentnew", '', $course->shortname
),
183 get_string('enrolmentnewuser', '', $a));
186 if (!empty($CFG->enrol_mailadmins
)) {
187 $a->course
= $course->fullname
;
188 $a->user
= fullname($user);
189 $admins = get_admins();
190 foreach ($admins as $admin) {
191 email_to_user($admin, $user, get_string("enrolmentnew", '', $course->shortname
),
192 get_string('enrolmentnewuser', '', $a));
199 } else if (strcmp ($result, "INVALID") == 0) { // ERROR
200 insert_record("enrol_paypal", addslashes_object($data), false);
201 email_paypal_error_to_admin("Received an invalid payment notification!! (Fake payment?)", $data);
210 /// FUNCTIONS //////////////////////////////////////////////////////////////////
213 function email_paypal_error_to_admin($subject, $data) {
214 $admin = get_admin();
217 $message = "$site->fullname: Transaction failed.\n\n$subject\n\n";
219 foreach ($data as $key => $value) {
220 $message .= "$key => $value\n";
223 email_to_user($admin, $admin, "PAYPAL ERROR: ".$subject, $message);