1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
|
<?php
include_once('swpm_handle_subsc_ipn.php');
class swpm_paypal_ipn_handler {
var $last_error; // holds the last error encountered var $ipn_log = false; // bool: log IPN results to text file? var $ipn_log_file; // filename of the IPN log var $ipn_response; // holds the IPN response from paypal var $ipn_data = array(); // array contains the POST values for IPN var $fields = array(); // array holds the fields to submit to paypal var $sandbox_mode = false;
function __construct() { $this->paypal_url = 'https://www.paypal.com/cgi-bin/webscr'; $this->last_error = ''; $this->ipn_log_file = 'ipn_handle_debug_swpm.log'; $this->ipn_response = ''; }
function swpm_validate_and_create_membership() { // Check Product Name , Price , Currency , Receivers email , $error_msg = "";
// Read the IPN and validate $gross_total = $this->ipn_data['mc_gross']; $transaction_type = $this->ipn_data['txn_type']; $txn_id = $this->ipn_data['txn_id']; $payment_status = $this->ipn_data['payment_status']; //Check payment status if (!empty($payment_status)) { if ($payment_status == "Denied") { $this->debug_log("Payment status for this transaction is DENIED. You denied the transaction... most likely a cancellation of an eCheque. Nothing to do here.", false); return false; } if ($payment_status == "Canceled_Reversal") { $this->debug_log("This is a dispute closed notification in your favour. The plugin will not do anyting.", false); return true; } if ($payment_status != "Completed" && $payment_status != "Processed" && $payment_status != "Refunded" && $payment_status != "Reversed") { $error_msg .= 'Funds have not been cleared yet. Transaction will be processed when the funds clear!'; $this->debug_log($error_msg,false); return false; } }
//Check txn type if ($transaction_type == "new_case") { $this->debug_log('This is a dispute case. Nothing to do here.', true); return true; } $custom = urldecode($this->ipn_data['custom']); $this->ipn_data['custom'] = $custom; $customvariables = SwpmTransactions::parse_custom_var($custom); //Handle refunds if ($gross_total < 0) { // This is a refund or reversal $this->debug_log('This is a refund notification. Refund amount: '.$gross_total,true); swpm_handle_subsc_cancel_stand_alone($this->ipn_data,true); return true; } if (isset($this->ipn_data['reason_code']) && $this->ipn_data['reason_code'] == 'refund'){ $this->debug_log('This is a refund notification. Refund amount: '.$gross_total,true); swpm_handle_subsc_cancel_stand_alone($this->ipn_data,true); return true; }
if (($transaction_type == "subscr_signup")) { $this->debug_log('Subscription signup IPN received... (handled by the subscription IPN handler)',true); // Code to handle the signup IPN for subscription $subsc_ref = $customvariables['subsc_ref'];
if (!empty($subsc_ref)) { $this->debug_log('Found a membership level ID. Creating member account...',true); $swpm_id = $customvariables['swpm_id']; swpm_handle_subsc_signup_stand_alone($this->ipn_data,$subsc_ref,$this->ipn_data['subscr_id'],$swpm_id); //Handle customized subscription signup } return true; } else if (($transaction_type == "subscr_cancel") || ($transaction_type == "subscr_eot") || ($transaction_type == "subscr_failed")) { // Code to handle the IPN for subscription cancellation $this->debug_log('Subscription cancellation IPN received... (handled by the subscription IPN handler)',true); swpm_handle_subsc_cancel_stand_alone($this->ipn_data); return true; } else { $cart_items = array(); $this->debug_log('Transaction Type: Buy Now/Subscribe',true); $item_number = $this->ipn_data['item_number']; $item_name = $this->ipn_data['item_name']; $quantity = $this->ipn_data['quantity']; $mc_gross = $this->ipn_data['mc_gross']; $mc_currency = $this->ipn_data['mc_currency'];
$current_item = array( 'item_number' => $item_number, 'item_name' => $item_name, 'quantity' => $quantity, 'mc_gross' => $mc_gross, 'mc_currency' => $mc_currency, );
array_push($cart_items, $current_item); }
$counter = 0; foreach ($cart_items as $current_cart_item) { $cart_item_data_num = $current_cart_item['item_number']; $cart_item_data_name = trim($current_cart_item['item_name']); $cart_item_data_quantity = $current_cart_item['quantity']; $cart_item_data_total = $current_cart_item['mc_gross']; $cart_item_data_currency = $current_cart_item['mc_currency']; if(empty($cart_item_data_quantity)){ $cart_item_data_quantity = 1; } $this->debug_log('Item Number: '.$cart_item_data_num,true); $this->debug_log('Item Name: '.$cart_item_data_name,true); $this->debug_log('Item Quantity: '.$cart_item_data_quantity,true); $this->debug_log('Item Total: '.$cart_item_data_total,true); $this->debug_log('Item Currency: '.$cart_item_data_currency,true);
//Get the button id $pp_hosted_button = false; $button_id = $cart_item_data_num;//Button id is the item number. $membership_level_id = get_post_meta($button_id, 'membership_level_id', true); if(!SwpmUtils::membership_level_id_exists($membership_level_id)){ $this->debug_log('This payment button was not created in the plugin. This is a paypal hosted button.', true); $pp_hosted_button = true; } //Price check $check_price = true; $msg = ""; $msg = apply_filters('swpm_before_price_check_filter', $msg, $current_cart_item); if (!empty($msg) && $msg == "price-check-override") {//This filter allows an extension to do a customized version of price check (if needed) $check_price = false; $this->debug_log('Price and currency check has been overridden by an addon/extension.', true); } if ($check_price && !$pp_hosted_button) { //Check according to buy now payment or subscription payment. $button_type = get_post_meta($button_id, 'button_type', true); if ( $button_type == 'pp_buy_now'){//This is a PayPal buy now type button $expected_amount = (get_post_meta($button_id, 'payment_amount', true)) * $cart_item_data_quantity; $expected_amount = round($expected_amount, 2); $received_amount = $cart_item_data_total; } else if ($button_type == 'pp_subscription'){//This is a PayPal subscription type button //Trial payment or recurring payment? //TODO - is_recurring_payment() check to determine if it is a recurring payment $trial_billing_amount = get_post_meta($button_id, 'trial_billing_amount', true); $billing_amount = get_post_meta($button_id, 'billing_amount', true); $expected_amount = 0; $received_amount = $cart_item_data_total; } else { $this->debug_log('Error! Unexpected button type: '.$button_type, false); return false; }
if ($received_amount < $expected_amount) { //Error! amount received is less than expected. This is invalid. $this->debug_log('Expected amount: '.$expected_amount, true); $this->debug_log('Received amount: '.$received_amount, true); $this->debug_log('Price check failed. Amount received is less than the amount expected. This payment will not be processed.', false); return false; }
} //*** Handle Membership Payment *** //-------------------------------------------------------------------------------------- // ========= Need to find the (level ID) in the custom variable ============ $subsc_ref = $customvariables['subsc_ref'];//Membership level ID $this->debug_log('Membership payment paid for membership level ID: '.$subsc_ref,true); if (!empty($subsc_ref)) { $swpm_id = ""; if(isset($customvariables['swpm_id'])){ $swpm_id = $customvariables['swpm_id']; } if ($transaction_type == "web_accept") { $this->debug_log('Transaction type: web_accept. Creating member account...',true); swpm_handle_subsc_signup_stand_alone($this->ipn_data,$subsc_ref,$this->ipn_data['txn_id'],$swpm_id); } else if($transaction_type == "subscr_payment"){ $this->debug_log('Transaction type: subscr_payment. Checking if the member profile needed to be updated',true); swpm_update_member_subscription_start_date_if_applicable($this->ipn_data); } } else { $this->debug_log('Membership level ID is missing in the payment notification! Cannot process this notification.',false); } //== End of Membership payment handling == $counter++; }
/*** Do Post payment operation and cleanup ***/ //Save the transaction data $this->debug_log('Saving transaction data to the database table.', true); $this->ipn_data['gateway'] = 'paypal'; $this->ipn_data['status'] = $this->ipn_data['payment_status']; SwpmTransactions::save_txn_record($this->ipn_data, $cart_items); $this->debug_log('Transaction data saved.', true); //Trigger the PayPal IPN processed action hook (so other plugins can can listen for this event). do_action('swpm_paypal_ipn_processed', $this->ipn_data); do_action('swpm_payment_ipn_processed', $this->ipn_data); return true; }
function swpm_validate_ipn() { //Generate the post string from the _POST vars aswell as load the _POST vars into an arry $post_string = ''; foreach ($_POST as $field=>$value) { $this->ipn_data["$field"] = $value; $post_string .= $field.'='.urlencode(stripslashes($value)).'&'; }
$this->post_string = $post_string; $this->debug_log('Post string : '. $this->post_string,true);
//IPN validation check if($this->validate_ipn_using_remote_post()){ //We can also use an alternative validation using the validate_ipn_using_curl() function return true; } else { return false; } }
function validate_ipn_using_remote_post(){ $this->debug_log( 'Checking if PayPal IPN response is valid', true); // Get received values from post data $validate_ipn = array( 'cmd' => '_notify-validate' ); $validate_ipn += wp_unslash( $_POST );
// Send back post vars to paypal $params = array( 'body' => $validate_ipn, 'timeout' => 60, 'httpversion' => '1.1', 'compress' => false, 'decompress' => false, 'user-agent' => 'Simple Membership Plugin', );
// Post back to get a response. $connection_url = $this->sandbox_mode ? 'https://www.sandbox.paypal.com/cgi-bin/webscr' : 'https://www.paypal.com/cgi-bin/webscr'; $this->debug_log('Connecting to: ' . $connection_url, true); $response = wp_safe_remote_post( $connection_url, $params );
//The following two lines can be used for debugging //$this->debug_log( 'IPN Request: ' . print_r( $params, true ) , true); //$this->debug_log( 'IPN Response: ' . print_r( $response, true ), true);
// Check to see if the request was valid. if ( ! is_wp_error( $response ) && strstr( $response['body'], 'VERIFIED' ) ) { $this->debug_log('IPN successfully verified.', true); return true; }
// Invalid IPN transaction. Check the log for details. $this->debug_log('IPN validation failed.', false); if ( is_wp_error( $response ) ) { $this->debug_log('Error response: ' . $response->get_error_message(), false); } return false; } function debug_log($message,$success,$end=false) { SwpmLog::log_simple_debug($message, $success, $end); } }
// Start of IPN handling (script execution)
$ipn_handler_instance = new swpm_paypal_ipn_handler();
$settings = SwpmSettings::get_instance(); $debug_enabled = $settings->get_value('enable-debug'); if(!empty($debug_enabled))//debug is enabled in the system { $debug_log = "log.txt"; // Debug log file name echo 'Debug logging is enabled. Check the '.$debug_log.' file for debug output.'; $ipn_handler_instance->ipn_log = true; $ipn_handler_instance->ipn_log_file = $debug_log; if(empty($_POST)) { $ipn_handler_instance->debug_log('This debug line was generated because you entered the URL of the ipn handling script in the browser.',true,true); exit; } }
$sandbox_enabled = $settings->get_value('enable-sandbox-testing'); if(!empty($sandbox_enabled)) // Sandbox testing enabled { $ipn_handler_instance->paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr'; $ipn_handler_instance->sandbox_mode = true; }
$ipn_handler_instance->debug_log('Paypal Class Initiated by '.$_SERVER['REMOTE_ADDR'],true);
// Validate the IPN if ($ipn_handler_instance->swpm_validate_ipn()) { $ipn_handler_instance->debug_log('Creating product Information to send.',true);
if(!$ipn_handler_instance->swpm_validate_and_create_membership()){ $ipn_handler_instance->debug_log('IPN product validation failed.',false); } } $ipn_handler_instance->debug_log('Paypal class finished.',true,true);
|