public static function isValid() { $verified = 0; require 'ipnlistener.php'; $listener = new IpnListener(); $is_paypal_sandbox = Yii::app()->params['is_paypal_sandbox']; if ($is_paypal_sandbox) { $listener->use_sandbox = true; } else { $listener->use_sandbox = false; } try { $listener->requirePostMethod(); $verified = $listener->processIpn(); } catch (Exception $e) { echo $e->getMessage(); exit(0); } if ($verified) { $verified = 1; // echo $listener->getTextReport(); } else { $verified = 0; // echo $listener->getTextReport(); } return $verified; }
public function post_process() { Log::write('PayPal', 'Trying to process IPN'); Bundle::start('paypal-ipn'); $listener = new IpnListener(); // $listener->use_sandbox = true; try { $listener->requirePostMethod(); $verified = $listener->processIpn(); } catch (Exception $e) { Log::info($e->getMessage()); } if ($verified) { Log::write('PayPal', 'IPN payment looks verified'); $data = Input::get(); $settings = IniHandle::readini(); if (!in_array($data['payment_status'], array('Completed', 'COMPLETED', 'completed'))) { Log::write('PayPal', 'payment not completed'); return View::make('msg.error')->with('error', 'PayPal: payment not completed'); } if (strtolower($data['receiver_email']) != strtolower($settings['ppemail'])) { Log::write('PayPal', 'receive email not same as set in settings. Settings: ' . $settings['ppemail'] . ' ||| PayPal email: ' . $data['receiver_email']); return View::make('msg.error')->with('error', 'PayPal: receive email not same as set in settings'); } if (Payment::where('transaction_id', '=', $data['txn_id'])->count() != 0) { Log::write('PayPal', 'transaction ID already exists'); return View::make('msg.error')->with('error', 'PayPal: transaction ID already exists'); } if (strtolower($data['mc_currency']) != strtolower($settings['ppcurrency'])) { Log::write('PayPal', 'Currencies do not match'); return View::make('msg.error')->with('error', 'PayPal: currencies do not match'); } Log::write('PayPal', 'Got past all PLAN controller checks now going into CUSTOM'); if (strtolower($data['custom']) == 'plan') { $result = Payment::verifyPlan($data); if (!$result) { return $result; } } elseif (strtolower($data['custom']) == 'blacklist_skype' || strtolower($data['custom']) == 'blacklist_ip') { $result = Payment::verifyBlacklist($data); if (!$result) { return $result; } } else { Log::write('PayPal', 'Custom not found, can\'t verify anything'); return View::make('msg.error')->with('error', 'Fraudulent payment?'); } Log::write('PayPal', 'Now trying to add Payment info to DB'); $payment = Payment::create(array('user_id' => $data['option_selection1'], 'token' => $data['ipn_track_id'], 'date' => date('Y-m-d H:i:s', time()), 'ack' => $data['payment_status'], 'transaction_id' => $data['txn_id'], 'amount' => $data['mc_gross'], 'paypal_fee' => $data['mc_fee'], 'status' => $data['payment_status'], 'description' => $data['custom'])); Log::write('PayPal', 'Successful payment, DB id: ' . $payment->id); } else { Log::write('PayPal', 'IPN listener returns false on check'); } return 'handled'; }
function inc_ipnlistener_recuperer_post_https($datas = '') { /** * PHP-PayPal-IPN Example * * This shows a basic example of how to use the IpnListener() PHP class to * implement a PayPal Instant Payment Notification (IPN) listener script. * * For a more in depth tutorial, see my blog post: * http://www.micahcarrick.com/paypal-ipn-with-php.html * * This code is available at github: * https://github.com/Quixotix/PHP-PayPal-IPN * * @package PHP-PayPal-IPN * @author Micah Carrick * @copyright (c) 2011 - Micah Carrick * @license http://opensource.org/licenses/gpl-3.0.html */ // instantiate the IpnListener class include_spip('lib/ipnlistener'); $erreur = false; $listener = new IpnListener(); /* When you are testing your IPN script you should be using a PayPal "Sandbox" account: https://developer.paypal.com When you are ready to go live change use_sandbox to false. */ $listener->use_sandbox = false; try { $listener->requirePostMethod(); $verified = $listener->processIpn($datas); } catch (Exception $e) { $erreur = true; $erreur_msg = $e->getMessage(); spip_log("erreur exception " . $erreur_message, "paypal"); } spip_log("valeur verifie " . $verified, "paypal"); if ($verified) { $response = 'VERIFIED'; } else { $response = 'INVALID'; } return array($response, $erreur, $erreur ? $erreur_msg : ''); }
/** * Class constructor. * * @param bool $use_curl Use curl. * @param bool $force_ssl_v3 Force SSL encoding. * @param bool $follow_location Follow location. * @param bool $use_ssl Use SSl. * @param bool $use_sandbox Sandbox mode. * @param int $timeout Default timeout. */ public function __construct($use_curl = true, $force_ssl_v3 = true, $follow_location = false, $use_ssl = false, $use_sandbox = false, $timeout = 30) { self::$use_curl = $use_curl; self::$force_ssl_v3 = $force_ssl_v3; self::$follow_location = $follow_location; self::$use_ssl = $use_ssl; self::$use_sandbox = $use_sandbox; self::$timeout = $timeout; }
function subtest() { require_once "application/libraries/ipnlistener.php"; $listener = new IpnListener(); file_put_contents('text.txt', $_POST['custom'] . ' - subtest - = ' . json_encode($_POST) . "\r\n---\r\n" . json_encode($_GET) . "\r\n-----------\r\n", FILE_APPEND); //$_POST = $_REQUEST = json_decode('{"amount1":"0.00","amount3":"9.99","address_status":"confirmed","subscr_date":"10:17:00 Jun 05, 2015 PDT","payer_id":"MJG88EHUTHY5L","address_street":"5003 Ritchie Highway","mc_amount1":"0.00","mc_amount3":"9.99","charset":"windows-1252","address_zip":"21225","first_name":"Ajay","reattempt":"1","address_country_code":"US","address_name":"Ajay Khanna","notify_version":"3.8","subscr_id":"I-XGM0L72MHP9T","custom":"30","payer_status":"verified","business":"*****@*****.**","address_country":"United States","address_city":"Brooklyn","verify_sign":"A2UvLyyTiDSSYReNtyr0qyDet6JRAqXVObnLGzMd3VldD5dfiZbg4cnr","payer_email":"*****@*****.**","btn_id":"96274524","last_name":"Khanna","address_state":"MD","receiver_email":"*****@*****.**","recurring":"1","txn_type":"subscr_signup","item_name":"FREE Trial for 90 Days Then $9.99 a month","mc_currency":"USD","item_number":"Free90Monthly","residence_country":"US","period1":"3 M","period3":"1 M","ipn_track_id":"90f4f2bdc1315"}', true); try { $listener->requirePostMethod(); $verified = $listener->processIpn(); } catch (Exception $e) { error_log($e->getMessage()); // //echo $e->getMessage(); exit(0); } //echo $listener->getResponse(); //var_dump($verified); // echo $_POST['custom']." = ". $_POST['subscr_id']." ".$type; if ($verified) { //file_put_contents('text.txt', "Verified\r\n====\r\n", FILE_APPEND); if ($_POST['txn_type'] == 'subscr_signup') { if (@$_POST['amount3'] == '99.99') { $type = 1; } else { $type = 2; } $this->userM->subscribe($_POST['custom'], $_POST['subscr_id'], $type); } if ($_POST['txn_type'] == 'subscr_cancel') { $this->userM->unsubscribe($_POST['subscr_id']); } } /* else file_put_contents('text.txt', "Failed\r\n====\r\n", FILE_APPEND); */ }
function makelog() { $listener = new IpnListener(); // tell the IPN listener to use the PayPal test sandbox $listener->use_sandbox = true; // try to process the IPN POST try { $listener->requirePostMethod(); $verified = $listener->processIpn(); } catch (Exception $e) { error_log($e->getMessage()); exit(0); } if ($verified) { $this->log($listener->getTextReport()); mail('*****@*****.**', 'Valid IPN', $listener->getTextReport()); return $listener->getTextReport(); } else { return $listener->getTextReport(); } }
error_reporting(E_ALL); if (!isset($_GET['page']) && isset($_GET['ref'])) { $_SESSION['ref'] = $_GET['ref']; header("Location: /"); } define("WEBSITE_URL", "ViewGrab.com"); define("PAYPAL_URL", "www.paypal.com"); define("PAYPAL_EMAIL", "*****@*****.**"); define("INDEX", "from_index"); require "classes/Main.php"; date_default_timezone_set("America/Chicago"); ob_start(); //$mysqli = new mysqli("localhost", "chiller", "mainSystemischill@19", "grabviews"); if (isset($_GET['paypal']) && strpos($_GET['paypal'], "paypal_ipn") !== false) { require_once "classes/ipnListener.php"; $ipnListener = new IpnListener($mysqli); switch ($_GET['paypal']) { case "paypal_ipn_buy": $result = $ipnListener->processBuyIpn(); break; case "paypal_ipn_sub": $result = $ipnListener->processSubIpn(); break; } exit; } $mainSystem = new Main(); $pageData = $mainSystem->getPageData(); $isOnlineViewer = $pageData['title'] == "Online Viewer"; if ($isOnlineViewer) { require "classes/onlineViewer.php";
* @license http://opensource.org/licenses/gpl-3.0.html */ /* Since this script is executed on the back end between the PayPal server and this script, you will want to log errors to a file or email. Do not try to use echo or print--it will not work! Here I am turning on PHP error logging to a file called "ipn_errors.log". Make sure your web server has permissions to write to that file. In a production environment it is better to have that log file outside of the web root. */ ini_set('log_errors', true); ini_set('error_log', dirname(__FILE__) . '/ipn_errors.log'); // instantiate the IpnListener class include '../ipnlistener.php'; $listener = new IpnListener(); /* When you are testing your IPN script you should be using a PayPal "Sandbox" account: https://developer.paypal.com When you are ready to go live change use_sandbox to false. */ $listener->use_sandbox = true; /* By default the IpnListener object is going going to post the data back to PayPal using cURL over a secure SSL connection. This is the recommended way to post the data back, however, some people may have connections problems using this method. To post over standard HTTP connection, use: $listener->use_ssl = false;
<?php ini_set('log_errors', true); ini_set('error_log', dirname(__FILE__) . '/ipn_errors.log'); // intantiate the IPN listener include 'ipnlistener.php'; $listener = new IpnListener(); $listener->use_sandbox = false; // try to process the IPN POST try { $listener->requirePostMethod(); $verified = $listener->processIpn(); } catch (Exception $e) { error_log($e->getMessage()); exit(0); } if ($verified) { $req = 'cmd=_notify-validate&' . file_get_contents("php://input"); $raw_post = file_get_contents("php://input"); $post_array = $listener->decodePayPalIPN($raw_post); $fields = array('payment_date', 'last_name', 'first_name', 'payer_business_name', 'payer_email', 'payer_id', 'os0', 'mc_gross', 'payment_status', 'payment_type', 'address_name', 'address_street', 'address_city', 'address_state', 'address_zip', 'contact_phone'); $new_array = array(); for ($i = 0; $i < count($fields); $i++) { $new_array[$fields[$i]] = str_replace(array("\r", "\n", ","), '', $post_array[$fields[$i]]); } if (isset($post_array['custom'])) { $custom_array = str_replace(',', '', $post_array['custom']); $custom_array = explode('|', $custom_array); $new_array['is_gift'] = $custom_array[0]; $new_array['age'] = $custom_array[1]; $new_array['gender'] = $custom_array[2];
<?php include 'setup.php'; include 'Logger.php'; include 'TxnType.php'; include 'PayPalIPNRequest.php'; $paypalEmailAddress = '*****@*****.**'; //PayPal user email // tell PHP to log errors to ipn_errors.log in this directory ini_set('log_errors', true); ini_set('error_log', dirname(__FILE__) . '/ipn_errors.log'); // intantiate the IPN listener include 'ipnlistener.php'; $listener = new IpnListener(); // tell the IPN listener to use the PayPal test sandbox $listener->use_sandbox = true; $listener->use_curl = false; // try to process the IPN POST try { $listener->requirePostMethod(); $verified = $listener->processIpn(); } catch (Exception $e) { error_log($e->getMessage()); exit(0); } $res = new PayPalIPNRequest($mysqli, $listener, $mail, $verified, $paypalEmailAddress);
<?php ini_set('display_errors', 1); error_reporting(E_ALL); require "init.php"; import("models.database"); import("models.settings"); import("models.external.paypalipn"); $listener = new IpnListener(); $listener->use_sandbox = true; try { $verified = $listener->processIpn(); } catch (Exception $e) { // fatal error trying to process IPN. exit(0); } if ($verified) { // IPN response was "VERIFIED" } else { // IPN response was "INVALID" }
<?php ini_set('log_errors', true); ini_set('error_log', dirname(__FILE__) . '/ipn-error.log'); include "cleanConfig.php"; include 'ipnFiles/ipnlistener.php'; $listener = new IpnListener(); //SANDBOX??? $sandbox = false; $listener->use_sandbox = $sandbox; $listener->force_ssl_v3 = false; $site_email = $sandbox ? "*****@*****.**" : $site["paypal"]; try { $listener->requirePostMethod(); $verified = $listener->processIpn(); } catch (Exception $e) { error_log($e->getMessage()); exit(0); } if ($verified) { $item_name = $_POST['item_name']; $item_number = $_POST['item_number']; $payment_status = $_POST['payment_status']; $payment_amount = $_POST['mc_gross']; $mc_currency = $_POST['mc_currency']; $txn_id = $_POST['txn_id']; $receiver_email = $_POST['receiver_email']; $payer_email = $_POST['payer_email']; $sale = false; if (count(explode("-", $_POST['custom'])) == 1) { $userid = $_POST['custom'];
/** * Check Paypal notification */ protected function checkNotificationPaypal() { // load JInput $jinput = JFactory::getApplication()->input; // check ipn vars $payment_status = $jinput->post->get('payment_status'); if (!$payment_status) { return [0, false]; } // require helper require_once JPATH_COMPONENT . '/vendor/PHP-PayPal-IPN/ipnlistener.php'; $listener = new IpnListener(); // process IPN try { $verified = $listener->processIpn(); } catch (Exception $e) { CHLib::log(json_encode(['CHClientModelNotify::checkNotificationPaypal - processIpn Exception', CHLib::input()->get->getArray(), CHLib::input()->post->getArray(), $e], JSON_PRETTY_PRINT), 'warning', 'com_chclient'); return [0, false]; } if (!$verified) { CHLib::log(json_encode(['CHClientModelNotify::checkNotificationPaypal - processIpn not verified', CHLib::input()->get->getArray(), CHLib::input()->post->getArray()], JSON_PRETTY_PRINT), 'warning', 'com_chclient'); return [0, false]; } // check status if ($payment_status != 'Completed') { CHLib::log(json_encode(['CHClientModelNotify::checkNotificationPaypal - payment_status not Completed', CHLib::input()->get->getArray(), CHLib::input()->post->getArray()], JSON_PRETTY_PRINT), 'warning', 'com_chclient'); return [0, false]; } // retrieve custom field $custom = explode(';', $jinput->post->get('custom', '', 'post')); if (count($custom) != 2) { CHLib::log(json_encode(['CHClientModelNotify::checkNotificationPaypal - custom field invalid', CHLib::input()->get->getArray(), CHLib::input()->post->getArray()], JSON_PRETTY_PRINT), 'warning', 'com_chclient'); return [0, false]; } // check sign $booking_id = (int) $custom[0]; $notification_sign = $custom[1]; $sign = hash('sha256', $this->config->data_source_app_secret . $this->config->confirm_paypal_business . $booking_id); if ($sign != $notification_sign) { CHLib::log(json_encode(['CHClientModelNotify::checkNotificationPaypal - sign does not match', CHLib::input()->get->getArray(), CHLib::input()->post->getArray()], JSON_PRETTY_PRINT), 'warning', 'com_chclient'); return [0, false]; } // return notification object return [$booking_id, CHLib::input()->post->getArray()]; }
public function __construct() { $config = Config::getInstance()->getConfig('paypal'); return parent::__construct($config['use_curl'], $config['force_ssl_v3'], $config['follow_location'], $config['use_ssl'], $config['use_sandbox'], $config['timeout']); }
function bizz_check_ipn_response() { if (isset($_GET['paypalListener']) && $_GET['paypalListener'] == 'paypal_standard_IPN') { // variables $listener = new IpnListener(); $listener->use_sandbox = TEST_MODE; $listener->use_ssl = true; $listener->use_curl = false; try { $listener->requirePostMethod(); $verified = $listener->processIpn(); } catch (Exception $e) { error_log($e->getMessage(), 3, 'error_log'); exit(0); } if ($verified) { // Get transaction details $posted = $listener->getPostData(); // Post ID $order_id = $posted['custom']; $order_key = $posted['invoice']; // Save details $r = ''; foreach ($posted as $key => $value) { $r .= str_pad($key, 25) . "{$value}<br/>"; } $transaction_details = get_post_meta($order_id, 'bizzthemes_booking_paypal_details', 1); $transaction_details = !empty($transaction_details) ? $transaction_details . '<br/><hr/><br/>' . $r : $r; update_post_meta($order_id, 'bizzthemes_booking_paypal_details', $transaction_details); // get booking meta $booking_custom = get_post_custom($order_id); foreach ($booking_custom as $key => $value) { $bookopts[$key] = $value[0]; } // Lowercase $posted['payment_status'] = strtolower($posted['payment_status']); $posted['txn_type'] = strtolower($posted['txn_type']); // Sandbox fix if ($posted['test_ipn'] == 1 && $posted['payment_status'] == 'pending') { $posted['payment_status'] = 'completed'; } // We are here so lets check status and do actions switch ($posted['payment_status']) { case 'completed': // Check valid txn_type $accepted_types = array('cart', 'instant', 'express_checkout', 'web_accept', 'masspay', 'send_money'); if (!in_array($posted['txn_type'], $accepted_types)) { if (DEBUG_MODE) { error_log('Invalid type:' . $posted['txn_type'], 3, 'error_log'); } exit; } // Saved booking $deposit_amount = get_post_meta($order_id, 'bizzthemes_car_pay_deposit', 1); $total_amount = get_post_meta($order_id, 'bizzthemes_car_pay_total', 1); // Validate Amount if (round($deposit_amount, 2) != $posted['mc_gross']) { if (DEBUG_MODE) { error_log('Payment error: Amounts do not match (gross ' . $posted['mc_gross'] . ', saved ' . round($deposit_amount, 2) . ')', 3, 'error_log'); } exit; } // Store PP Details if (!empty($posted['payer_email'])) { update_post_meta($order_id, 'bizzthemes_bookings_email', $posted['payer_email']); } if (!empty($posted['txn_id'])) { update_post_meta($order_id, 'bizzthemes_car_transaction_id', $posted['txn_id']); } if (!empty($posted['first_name'])) { update_post_meta($order_id, 'bizzthemes_bookings_fname', $posted['first_name']); } if (!empty($posted['last_name'])) { update_post_meta($order_id, 'bizzthemes_bookings_lname', $posted['last_name']); } // Paid update_post_meta($order_id, 'bizzthemes_car_pay_paid', round($posted['mc_gross'], 2)); // Completed? if (round($total_amount, 2) == $posted['mc_gross']) { update_post_meta($order_id, 'bizzthemes_bookings_status', 'approved'); } break; case 'denied': case 'expired': case 'failed': case 'voided': // Only handle full refunds, not partial update_post_meta($order_id, 'bizzthemes_bookings_status', 'cancelled'); break; case "refunded": // Only handle full refunds, not partial update_post_meta($order_id, 'bizzthemes_bookings_status', 'refunded'); update_post_meta($order_id, 'bizzthemes_car_pay_paid', '0'); booking_send_notification('refunded', $bookopts); break; case "reversed": case "chargeback": // Mark order as refunded update_post_meta($order_id, 'bizzthemes_bookings_status', 'refunded'); update_post_meta($order_id, 'bizzthemes_car_pay_paid', '0'); break; default: // No action break; } exit; // error_log('getPaymentData: '.$r, 3, 'error_log'); //error_log('getTextReport: '.$listener->getTextReport(), 3, 'error_log'); // mail('*****@*****.**', 'Verified IPN', $listener->getTextReport()); } else { /* zapis v bazo o napačni transakciji */ // mail('*****@*****.**', 'Invalid IPN', $listener->getTextReport()); error_log('getTextReport: ' . $listener->getTextReport(), 3, 'error_log'); } } }
function rcp_check_ipn() { global $rcp_options; if (!class_exists('IpnListener')) { // instantiate the IpnListener class include RCP_PLUGIN_DIR . 'includes/gateways/paypal/ipnlistener.php'; } $listener = new IpnListener(); if (isset($rcp_options['sandbox'])) { $listener->use_sandbox = true; } if (isset($rcp_options['ssl'])) { $listener->use_ssl = true; } else { $listener->use_ssl = false; } //To post using the fsockopen() function rather than cURL, use: if (isset($rcp_options['disable_curl'])) { $listener->use_curl = false; } try { $listener->requirePostMethod(); $verified = $listener->processIpn(); } catch (Exception $e) { //exit(0); } /* The processIpn() method returned true if the IPN was "VERIFIED" and false if it was "INVALID". */ if ($verified || isset($_POST['verification_override']) || (isset($rcp_options['sandbox']) || isset($rcp_options['disable_ipn_verify']))) { $posted = apply_filters('rcp_ipn_post', $_POST); // allow $_POST to be modified $user_id = $posted['custom']; $subscription_name = $posted['item_name']; $subscription_key = $posted['item_number']; $amount = number_format((double) $posted['mc_gross'], 2); $amount2 = number_format((double) $posted['mc_amount3'], 2); $payment_status = $posted['payment_status']; $currency_code = $posted['mc_currency']; $subscription_id = rcp_get_subscription_id($user_id); $subscription_price = number_format((double) rcp_get_subscription_price(rcp_get_subscription_id($user_id)), 2); $user_data = get_userdata($user_id); if (!$user_data || !$subscription_id) { return; } if (!rcp_get_subscription_details($subscription_id)) { return; } // setup the payment info in an array for storage $payment_data = array('date' => date('Y-m-d g:i:s', strtotime($posted['payment_date'])), 'subscription' => $posted['item_name'], 'payment_type' => $posted['txn_type'], 'subscription_key' => $subscription_key, 'amount' => $amount, 'user_id' => $user_id, 'transaction_id' => $posted['txn_id']); do_action('rcp_valid_ipn', $payment_data, $user_id, $posted); if ($posted['txn_type'] == 'web_accept' || $posted['txn_type'] == 'subscr_payment') { // only check for an existing payment if this is a payment IPD request if (rcp_check_for_existing_payment($posted['txn_type'], $posted['payment_date'], $subscription_key)) { $log_data = array('post_title' => __('Duplicate Payment', 'rcp'), 'post_content' => __('A duplicate payment was detected. The new payment was still recorded, so you may want to check into both payments.', 'rcp'), 'post_parent' => 0, 'log_type' => 'gateway_error'); $log_meta = array('user_subscription' => $posted['item_name'], 'user_id' => $user_id); $log_entry = WP_Logging::insert_log($log_data, $log_meta); return; // this IPN request has already been processed } /* do some quick checks to make sure all necessary data validates */ if ($amount < $subscription_price && $amount2 < $subscription_price) { /* // the subscription price doesn't match, so lets check to see if it matches with a discount code if( ! rcp_check_paypal_return_price_after_discount( $subscription_price, $amount, $amount2, $user_id ) ) { $log_data = array( 'post_title' => __( 'Price Mismatch', 'rcp' ), 'post_content' => sprintf( __( 'The price in an IPN request did not match the subscription price. Payment data: %s', 'rcp' ), json_encode( $payment_data ) ), 'post_parent' => 0, 'log_type' => 'gateway_error' ); $log_meta = array( 'user_subscription' => $posted['item_name'], 'user_id' => $user_id ); $log_entry = WP_Logging::insert_log( $log_data, $log_meta ); //return; } */ } if (strtolower($currency_code) != strtolower($rcp_options['currency'])) { // the currency code is invalid $log_data = array('post_title' => __('Invalid Currency Code', 'rcp'), 'post_content' => sprintf(__('The currency code in an IPN request did not match the site currency code. Payment data: %s', 'rcp'), json_encode($payment_data)), 'post_parent' => 0, 'log_type' => 'gateway_error'); $log_meta = array('user_subscription' => $posted['item_name'], 'user_id' => $user_id); $log_entry = WP_Logging::insert_log($log_data, $log_meta); return; } } if (isset($rcp_options['email_ipn_reports'])) { wp_mail(get_bloginfo('admin_email'), __('IPN report', 'rcp'), $listener->getTextReport()); } if (rcp_get_subscription_key($user_id) != $subscription_key) { // the subscription key is invalid $log_data = array('post_title' => __('Subscription Key Mismatch', 'rcp'), 'post_content' => sprintf(__('The subscription key in an IPN request did not match the subscription key recorded for the user. Payment data: %s', 'rcp'), json_encode($payment_data)), 'post_parent' => 0, 'log_type' => 'gateway_error'); $log_meta = array('user_subscription' => $posted['item_name'], 'user_id' => $user_id); $log_entry = WP_Logging::insert_log($log_data, $log_meta); return; } /* now process the kind of subscription/payment */ $rcp_payments = new RCP_Payments(); // Subscriptions switch ($posted['txn_type']) { case "subscr_signup": // when a new user signs up // store the recurring payment ID update_user_meta($user_id, 'rcp_paypal_subscriber', $posted['payer_id']); // set the user's status to active rcp_set_status($user_id, 'active'); if (!isset($rcp_options['disable_new_user_notices'])) { wp_new_user_notification($user_id); } // send welcome email rcp_email_subscription_status($user_id, 'active'); update_user_meta($user_id, 'rcp_recurring', 'yes'); do_action('rcp_ipn_subscr_signup', $user_id); break; case "subscr_payment": // when a user makes a recurring payment // record this payment in the database $rcp_payments->insert($payment_data); $subscription = rcp_get_subscription_details(rcp_get_subscription_id($user_id)); // update the user's expiration to correspond with the new payment $member_new_expiration = date('Y-m-d H:i:s', strtotime('+' . $subscription->duration . ' ' . $subscription->duration_unit . ' 23:59:59')); rcp_set_expiration_date($user_id, $member_new_expiration); update_user_meta($user_id, 'rcp_paypal_subscriber', $posted['payer_id']); // make sure the user's status is active rcp_set_status($user_id, 'active'); update_user_meta($user_id, 'rcp_recurring', 'yes'); delete_user_meta($user_id, '_rcp_expired_email_sent'); do_action('rcp_ipn_subscr_payment', $user_id); break; case "subscr_cancel": // user is marked as cancelled but retains access until end of term rcp_set_status($user_id, 'cancelled'); // set the use to no longer be recurring delete_user_meta($user_id, 'rcp_recurring'); delete_user_meta($user_id, 'rcp_paypal_subscriber'); // send sub cancelled email rcp_email_subscription_status($user_id, 'cancelled'); do_action('rcp_ipn_subscr_cancel', $user_id); break; case "subscr_failed": do_action('rcp_ipn_subscr_failed'); break; case "subscr_eot": // user's subscription has reach the end of its term // set the use to no longer be recurring delete_user_meta($user_id, 'rcp_recurring'); if ('cancelled' !== rcp_get_status($user_id)) { rcp_set_status($user_id, 'expired'); // send expired email rcp_email_subscription_status($user_id, 'expired'); } do_action('rcp_ipn_subscr_eot', $user_id); break; case "cart": return; // get out of here // get out of here case "express_checkout": return; // get out of here // get out of here case "web_accept": switch (strtolower($payment_status)) { case 'completed': if (isset($_POST['verification_override'])) { // this is a method for providing a new expiration if it doesn't exist $subscription = rcp_get_subscription_details_by_name($payment_data['subscription']); // update the user's expiration to correspond with the new payment $member_new_expiration = date('Y-m-d H:i:s', strtotime('+' . $subscription->duration . ' ' . $subscription->duration_unit . ' 23:59:59')); rcp_set_expiration_date($user_id, $member_new_expiration); } // set this user to active rcp_set_status($user_id, 'active'); $rcp_payments->insert($payment_data); rcp_email_subscription_status($user_id, 'active'); if (!isset($rcp_options['disable_new_user_notices'])) { // send welcome email here wp_new_user_notification($user_id); } delete_user_meta($user_id, '_rcp_expired_email_sent'); break; case 'denied': case 'expired': case 'failed': case 'voided': rcp_set_status($user_id, 'cancelled'); // send cancelled email here break; } break; default: break; } } else { if (isset($rcp_options['email_ipn_reports'])) { // an invalid IPN attempt was made. Send an email to the admin account to investigate wp_mail(get_bloginfo('admin_email'), __('Invalid IPN', 'rcp'), $listener->getTextReport()); } } }
/** * Validate IPN Message * PayPal provides a simple solution for notifying us when a payment has been processed; * they call it Instant Payment Notifications (IPN). In order to take advantage of IPN, * we create an IPN listener for our application (see https://github.com/Quixotix/PHP-PayPal-IPN). * See also https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNandPDTVariables/ * @return boolean whether ipn was validates */ public function validateIPN() { $listener = new IpnListener(); $listener->use_sandbox = !$this->apiLive; if ($listener->processIpn()) { if (Yii::app()->request->getPost('receiver_email') != $this->receiverEmail) { $this->errorCode = self::ERROR_PROCESS_IPN; $this->errorMessage = 'PayPal recurring payment receiver email mismatch'; return false; } else { return true; } } else { $this->errorCode = self::ERROR_VERIFY_IPN; $this->errorMessage = var_export($listener->getErrors(), true); return false; } }
/* Since this script is executed on the back end between the PayPal server and this script, you will want to log errors to a file or email. Do not try to use echo or print--it will not work! Here I am turning on PHP error logging to a file called "ipn_errors.log". Make sure your web server has permissions to write to that file. In a production environment it is better to have that log file outside of the web root. */ $paypal_params = array('email' => '*****@*****.**', 'debug' => false, 'log_error' => true); $tnx_state = 'cancel'; ini_set('log_errors', $paypal_params['log_error']); ini_set('error_log', '../../../logs/ipn_errors.log'); // instantiate the IpnListener class include '../../../lib/paypal/ipnlistener.php'; $listener = new IpnListener(); /* When you are testing your IPN script you should be using a PayPal "Sandbox" account: https://developer.paypal.com When you are ready to go live change use_sandbox to false. */ $listener->use_sandbox = $paypal_params['debug']; /* By default the IpnListener object is going going to post the data back to PayPal using cURL over a secure SSL connection. This is the recommended way to post the data back, however, some people may have connections problems using this method. To post over standard HTTP connection, use: $listener->use_ssl = false;
function checkAndvalidateIPN() { if ($this->booLogEvents) { ini_set('log_errors', true); ini_set('error_log', $this->strLogfile); } include 'PHP-PayPal-IPN/ipnlistener.php'; $listener = new IpnListener(); $listener->use_sandbox = PAYPAL_SANDBOX; $listener->use_ssl = true; $listener->use_curl = false; if (function_exists('curl_init')) { $listener->use_curl = true; } try { $listener->requirePostMethod(); $verified = $listener->processIpn(); } catch (Exception $e) { error_log($e->getMessage()); exit(0); } if ($this->booLogEvents) { error_log($listener->getTextReport()); } if ($verified) { if ($_POST['payment_status'] != 'Completed') { if ($this->booLogEvents) { error_log('FAIL - payment_status is not Completed'); } return false; } if ($_POST['receiver_email'] != $this->strPaypalAccount) { if ($this->booLogEvents) { error_log('FAIL - receiver_email is: ' . $_POST['receiver_email'] . ' expected: ' . $this->strPaypalAccount); } return false; } if ($_POST['mc_currency'] != PAYPAL_CURRENCY) { if ($this->booLogEvents) { error_log('FAIL - currency is: ' . $_POST['mc_currency'] . ' expected: ' . PAYPAL_CURRENCY); } return false; } // process payment $objPayment = new GSALES2_OBJECT_PAYMENT(); $objPayment->setPaymentProvider('paypal'); $objPayment->setAmount($_POST['mc_gross']); $objPayment->setInvoiceId($_POST['custom']); $objPayment->setTransactionId($_POST['txn_id']); if ($this->booLogEvents) { error_log('Payment object:' . print_r($objPayment, true)); } // set invoice to paid return $objPayment->checkPaidAmountAndSetInvoiceAsPaid(); } else { if ($this->booLogEvents) { error_log('!!! Invalid IPN !!! '); } } }
<?php $email = '*****@*****.**'; // tell PHP to log errors to ipn_error.log in tmp ini_set('log_errors', true); ini_set('error_log', '/tmp/ipn_error.log'); include 'IPN_lib.php'; $listener = new IpnListener(); /* When you are testing your IPN script you should be using a PayPal "Sandbox" account: https://developer.paypal.com When you are ready to go live change use_sandbox to false. */ $listener->use_sandbox = true; /* By default the IpnListener object is going going to post the data back to PayPal using cURL over a secure SSL connection. This is the recommended way to post the data back, however, some people may have connections problems using this method. To post over standard HTTP connection, use: $listener->use_ssl = false; To post using the fsockopen() function rather than cURL, use: $listener->use_curl = false; */ /* The processIpn() method will encode the POST variables sent by PayPal and then POST them back to the PayPal server. An exception will be thrown if there is a fatal error (cannot connect, your server is not configured properly, etc.). Use a try/catch block to catch these fatal errors and log to the ipn_errors.log file we setup at the top of this file. The processIpn() method will send the raw data on 'php://input' to PayPal. You
<?php require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/DB.php"; require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/define-connect.php"; $db = new DB(HOST, USER, PASSWORD, DATABASE); $db->connect(); $db2 = new DB(HOST, USER, PASSWORD, DATABASE); $db2->connect(); $db3 = new DB(HOST, USER, PASSWORD, DATABASE); $db3->connect(); include 'IpnListener.php'; $listener = new IpnListener(); $listener->use_sandbox = false; try { $verified = $listener->processIpn(); } catch (Exception $e) { // fatal error trying to process IPN. exit(0); } $emlstr = ""; foreach ($_POST as $k => $v) { $emlstr .= "{$k} = {$v} ,<br />\n"; } if ($verified) { // mail("*****@*****.**","POST",$emlstr); $errmsg = ''; // stores errors from fraud checks if ($_POST['payment_status'] != 'Completed') { // simply ignore any IPN that is not completed mail("*****@*****.**", "payment_status", "not completed"); exit(0);
/** * Process PayPal IPN * * @since 2.1 */ public function process_webhooks() { if (!isset($_GET['listener']) || strtoupper($_GET['listener']) != 'IPN') { return; } global $rcp_options; nocache_headers(); if (!class_exists('IpnListener')) { // instantiate the IpnListener class include RCP_PLUGIN_DIR . 'includes/gateways/paypal/paypal-ipnlistener.php'; } $listener = new IpnListener(); $verified = false; if ($this->test_mode) { $listener->use_sandbox = true; } /* if( isset( $rcp_options['ssl'] ) ) { $listener->use_ssl = true; } else { $listener->use_ssl = false; } */ //To post using the fsockopen() function rather than cURL, use: if (isset($rcp_options['disable_curl'])) { $listener->use_curl = false; } try { $listener->requirePostMethod(); $verified = $listener->processIpn(); } catch (Exception $e) { status_header(402); //die( 'IPN exception: ' . $e->getMessage() ); } /* The processIpn() method returned true if the IPN was "VERIFIED" and false if it was "INVALID". */ if ($verified || isset($_POST['verification_override']) || ($this->test_mode || isset($rcp_options['disable_ipn_verify']))) { status_header(200); $user_id = 0; $posted = apply_filters('rcp_ipn_post', $_POST); // allow $_POST to be modified if (!empty($posted['custom']) && is_numeric($posted['custom'])) { $user_id = absint($posted['custom']); } else { if (!empty($posted['subscr_id'])) { $user_id = rcp_get_member_id_from_profile_id($posted['subscr_id']); } else { if (!empty($posted['payer_email'])) { $user = get_user_by('email', $posted['payer_email']); $user_id = $user ? $user->ID : false; } } } $member = new RCP_Member($user_id); if (!$member || !$member->get_subscription_id()) { die('no member found'); } if (!rcp_get_subscription_details($member->get_subscription_id())) { die('no subscription level found'); } $subscription_name = $posted['item_name']; $subscription_key = $posted['item_number']; $amount = number_format((double) $posted['mc_gross'], 2); $amount2 = number_format((double) $posted['mc_amount3'], 2); $payment_status = $posted['payment_status']; $currency_code = $posted['mc_currency']; $subscription_price = number_format((double) rcp_get_subscription_price($member->get_subscription_id()), 2); // setup the payment info in an array for storage $payment_data = array('date' => date('Y-m-d g:i:s', strtotime($posted['payment_date'], current_time('timestamp'))), 'subscription' => $posted['item_name'], 'payment_type' => $posted['txn_type'], 'subscription_key' => $subscription_key, 'amount' => $amount, 'user_id' => $user_id, 'transaction_id' => $posted['txn_id']); do_action('rcp_valid_ipn', $payment_data, $user_id, $posted); if ($posted['txn_type'] == 'web_accept' || $posted['txn_type'] == 'subscr_payment') { // only check for an existing payment if this is a payment IPD request if (rcp_check_for_existing_payment($posted['txn_type'], $posted['payment_date'], $subscription_key)) { $log_data = array('post_title' => __('Duplicate Payment', 'rcp'), 'post_content' => __('A duplicate payment was detected. The new payment was still recorded, so you may want to check into both payments.', 'rcp'), 'post_parent' => 0, 'log_type' => 'gateway_error'); $log_meta = array('user_subscription' => $posted['item_name'], 'user_id' => $user_id); $log_entry = WP_Logging::insert_log($log_data, $log_meta); die('duplicate IPN detected'); } if (strtolower($currency_code) != strtolower($rcp_options['currency'])) { // the currency code is invalid $log_data = array('post_title' => __('Invalid Currency Code', 'rcp'), 'post_content' => sprintf(__('The currency code in an IPN request did not match the site currency code. Payment data: %s', 'rcp'), json_encode($payment_data)), 'post_parent' => 0, 'log_type' => 'gateway_error'); $log_meta = array('user_subscription' => $posted['item_name'], 'user_id' => $user_id); $log_entry = WP_Logging::insert_log($log_data, $log_meta); die('invalid currency code'); } } if (isset($rcp_options['email_ipn_reports'])) { wp_mail(get_bloginfo('admin_email'), __('IPN report', 'rcp'), $listener->getTextReport()); } /* now process the kind of subscription/payment */ $rcp_payments = new RCP_Payments(); // Subscriptions switch ($posted['txn_type']) { case "subscr_signup": // when a new user signs up // store the recurring payment ID update_user_meta($user_id, 'rcp_paypal_subscriber', $posted['payer_id']); $member->set_payment_profile_id($posted['subscr_id']); do_action('rcp_ipn_subscr_signup', $user_id); die('successful subscr_signup'); break; case "subscr_payment": // when a user makes a recurring payment update_user_meta($user_id, 'rcp_paypal_subscriber', $posted['payer_id']); $member->set_payment_profile_id($posted['subscr_id']); $member->renew(true); // record this payment in the database $rcp_payments->insert($payment_data); do_action('rcp_ipn_subscr_payment', $user_id); die('successful subscr_payment'); break; case "subscr_cancel": // user is marked as cancelled but retains access until end of term $member->set_status('cancelled'); // set the use to no longer be recurring delete_user_meta($user_id, 'rcp_paypal_subscriber'); do_action('rcp_ipn_subscr_cancel', $user_id); die('successful subscr_cancel'); break; case "subscr_failed": do_action('rcp_ipn_subscr_failed'); die('successful subscr_failed'); break; case "subscr_eot": // user's subscription has reached the end of its term if ('cancelled' !== $member->get_status($user_id)) { $member->set_status('expired'); } do_action('rcp_ipn_subscr_eot', $user_id); die('successful subscr_eot'); break; case "web_accept": switch (strtolower($payment_status)) { case 'completed': // set this user to active $member->renew(); $rcp_payments->insert($payment_data); break; case 'denied': case 'expired': case 'failed': case 'voided': $member->set_status('cancelled'); break; } die('successful web_accept'); break; case "cart": case "express_checkout": default: break; } } else { if (isset($rcp_options['email_ipn_reports'])) { // an invalid IPN attempt was made. Send an email to the admin account to investigate wp_mail(get_bloginfo('admin_email'), __('Invalid IPN', 'rcp'), $listener->getTextReport()); } status_header(400); die('invalid IPN'); } }
/** * Method used to handle notification from paypal server * * @return void * @since 1.0 * @author Antonio La Rocca <*****@*****.**> */ public function handle_notification() { if (empty($_GET['paypal_ipn_response'])) { return; } // include required libraries require dirname(dirname(__FILE__)) . '/third-party/IPNListener/ipnlistener.php'; // retrieve saved options from panel $stored_options = $this->get_gateway_options(); $listener = new IpnListener(); $listener->use_sandbox = !($stored_options['sandbox'] == 'no'); try { // process IPN request, require validation to PayPal server $listener->requirePostMethod(); $verified = $listener->processIpn(); } catch (Exception $e) { // fatal error trying to process IPN. die; } // if PayPal says IPN is valid, process content if ($verified) { $request_data = $_POST; if (!isset($request_data['payment_status'])) { die; } // format payment data $payment_data = array(); for ($i = 1; array_key_exists('status_' . $i, $request_data); $i++) { $data_index = array_keys($request_data); foreach ($data_index as $index) { if (strpos($index, '_' . $i) !== false) { $payment_data[$i][str_replace('_' . $i, '', $index)] = $request_data[$index]; unset($request_data[$index]); } } } $request_data['payment_data'] = $payment_data; if (!empty($payment_data)) { foreach ($payment_data as $payment) { if (!isset($payment['unique_id'])) { continue; } $args = array(); $args['unique_id'] = $payment['unique_id']; $args['gross'] = $payment['mc_gross']; $args['status'] = $payment['status']; $args['receiver_email'] = $payment['receiver_email']; $args['currency'] = $payment['mc_currency']; $args['txn_id'] = $payment['masspay_txn_id']; // call action to update request status do_action('yith_vendors_gateway_notification', $args); } } } die; }
} } else { $log_error = true; } if ($log_error) { ini_set('log_errors', true); ini_set('error_log', $log_file_path); } $temp_exploded = explode('_', $_POST['custom']); //the "custom" variable from PayPal format: xx_yy_zzzzzzzz (xx: form_id, yy: entry_id, zzz: unix_timestamp of the date_created field) $form_id = (int) $temp_exploded[0]; if (!empty($form_id)) { $form_properties = mf_get_form_properties($dbh, $form_id, array('payment_paypal_enable_test_mode')); } //start the listener $listener = new IpnListener(); if (function_exists('curl_init')) { $listener->use_curl = true; } else { $listener->use_curl = false; } if (!empty($form_properties['payment_paypal_enable_test_mode'])) { $listener->use_sandbox = true; } else { $listener->use_sandbox = false; } try { $listener->requirePostMethod(); $verified = $listener->processIpn(); } catch (Exception $e) { error_log($e->getMessage());
$parse_uri = explode('wp-content', $_SERVER['SCRIPT_FILENAME']); require_once $parse_uri[0] . 'wp-load.php'; ini_set('log_errors', true); ini_set('error_log', dirname(__FILE__) . '/ipn_errors.log'); /* Get Payments Related Theme Options */ $paypal_merchant_id = get_option('theme_paypal_merchant_id'); $enable_sandbox = get_option('theme_enable_sandbox'); /*$payment_amount = get_option('theme_payment_amount'); $currency_code = get_option('theme_currency_code');*/ $disable_ssl = get_option('theme_disable_ssl'); $valid_ipn_email = get_option('theme_valid_ipn_email'); $invalid_ipn_email = get_option('theme_invalid_ipn_email'); $publish_on_payment = get_option('theme_publish_on_payment'); // instantiate the IpnListener class include 'ipnlistener.php'; $listener = new IpnListener(); /* When you are testing your IPN script you should be using a PayPal "Sandbox" account: https://developer.paypal.com When you are ready to go live change use_sandbox to false. */ if ($enable_sandbox == "true") { $listener->use_sandbox = true; } /* By default the IpnListener object is going going to post the data back to PayPal using cURL over a secure SSL connection. This is the recommended way to post the data back, however, some people may have connections problems using this method. To post over standard HTTP connection, use:*/
} function percentage($val1, $val2, $precision) { $division = $val1 / $val2; $res = $division * 100; $res = round($res, $precision); return $res; } Route::post('/datasrpc/gt/pp/payment/ipn', function () { define("_VALID_PHP", true); define("_PIPN", true); ini_set('log_errors', true); ini_set('error_log', dirname(__FILE__) . '/ipn_errors.log'); if (isset($_POST['payment_status'])) { require_once "/opt/nginx/html/vendor/class_pp.php"; $listener = new IpnListener(); $listener->use_live = true; $listener->use_ssl = true; $listener->use_curl = false; try { $listener->requirePostMethod(); $ppver = $listener->processIpn(); } catch (exception $e) { error_log($e->getMessage()); exit(0); } $payment_status = $_POST['payment_status']; $receiver_email = $_POST['receiver_email']; list($membership_id, $user_id) = explode("_", $_POST['item_number']); $mc_gross = $_POST['mc_gross']; $txn_id = $_POST['txn_id'];
<?php include 'ipnlistener.php'; include "config.php"; if ($sqlTicketservertype = 'mysql') { $db = new PDO('mysql:host=' . $sqlTicketserver . ';dbname=' . $sqlTicketdbname, $sqlTicketusername, $sqlTicketpassword); } // tell PHP to log errors to ipn_errors.log in this directory ini_set('log_errors', true); ini_set('error_log', dirname(__FILE__) . '/ipn_errors.log'); $listener = new IpnListener(); $listener->use_sandbox = true; try { $verified = $listener->processIpn(); } catch (Exception $e) { // fatal error trying to process IPN. error_log($e->getMessage()); exit(0); } if ($verified) { // IPN response was "VERIFIED" $email = $_POST['payer_email']; $txn = $_POST['txn_id']; $firstName = $_POST['first_name']; $lastName = $_POST['last_name']; $paymentDate = $_POST['payment_date']; $query = $db->PREPARE("INSERT INTO Tickets ( email, txn, firstName, lastName, paymentDate ) VALUES ( '{$email}', '{$txn}', '{$firstName}', '{$lastName}', '{$paymentDate}' )"); $query->execute(); mail('*****@*****.**', 'Valid IPN', $listener->getTextReport()); } else { // IPN response was "INVALID"
Since this script is executed on the back end between the PayPal server and this script, you will want to log errors to a file or email. Do not try to use echo or print--it will not work! Here I am turning on PHP error logging to a file called "ipn_errors.log". Make sure your web server has permissions to write to that file. In a production environment it is better to have that log file outside of the web root. */ // Set log $options['format'] = '{DATE}\\t{TIME}\\t{LEVEL}\\t{CODE}\\t{MESSAGE}'; $options['text_file'] = 'ipn_errors.php'; $log = JLog::addLogger($options); // instantiate the IpnListener class //include('../ipnlistener.php'); require_once JPATH_COMPONENT_ADMINISTRATOR . DS . 'helpers' . DS . 'ipnlistener.php'; $listener = new IpnListener(); // Check if user logged $user = JFactory::getUser(); if (!$user->id) { JLog::add("Userid is null", JLog::CRITICAL, 'ipn.php'); //return; } /* When you are testing your IPN script you should be using a PayPal "Sandbox" account: https://developer.paypal.com When you are ready to go live change use_sandbox to false. */ $listener->use_sandbox = true; //$listener->use_ssl=false; //$listener->use_curl = false; /*
/** * @method POST */ function post() { parse_str($this->request->data, $request); $siteId = $request['custom']; // get reference to site $site = Site::GetBySiteId($siteId); $use_sandbox = false; // set whether to use a sandbox if ($site['PayPalUseSandbox'] == '1') { $use_sandbox = true; } $listener = new IpnListener(); $listener->use_curl = false; $listener->use_sandbox = $use_sandbox; $listener->use_ssl = true; try { $verified = $listener->processIpn(); } catch (Exception $e) { // fatal error trying to process IPN. exit(0); } // IPN response was "VERIFIED" if ($verified) { $processor = 'PayPal'; if ($use_sandbox == true) { $processor .= ' (sandbox)'; } $processorTransactionId = $request['txn_id']; $processorStatus = $request['payment_status']; $email = $request['payer_email']; $payerId = $request['payer_id']; $name = $request['first_name'] . ' ' . $request['last_name']; $shipping = $request['mc_handling']; $fee = $request['mc_fee']; $tax = $request['tax']; $total = $request['mc_gross']; $currency = $request['mc_currency']; $num_items = 1000; if (isset($request['num_cart_items'])) { $num_items = $request['num_cart_items']; } $items = array(); // line-items (for receipt) $line_items = ''; // set static URL $staticUrl = $site['Domain']; if (FILES_ON_S3 == true) { $bucket = $site['Bucket']; $staticUrl = str_replace('{{bucket}}', $bucket, S3_URL); $staticUrl = str_replace('{{site}}', $site['FriendlyId'], $staticUrl); } // get items for ($x = 1; $x <= $num_items; $x++) { if (isset($request['item_number' . $x])) { $item_number = $request['item_number' . $x]; $item_name = $request['item_name' . $x]; $item_number = iconv("ISO-8859-1", "UTF-8", $item_number); $item_name = iconv("ISO-8859-1", "UTF-8", $item_name); $item_quantity = $request['quantity' . $x]; $item_total = $request['mc_gross_' . $x]; $item_price = floatval($item_total) / intval($item_quantity); $item = array('ProductId' => $item_number, 'Name' => $item_name, 'Quantity' => $item_quantity, 'Price' => $item_price, 'Total' => $item_total); // get product $product = Product::GetByProductId($item_number); // get download link $download_link = ''; // check if there is a downloaded file for the product if ($product['Download'] != '' && $product['Download'] != NULL) { $download_link = '<br><a href="' . API_URL . '/transaction/download/{{transactionId}}/' . $item_number . '">Download</a>'; } // setup currency for line items $item_total = $item_total . ' ' . $currency; $item_price = $item_price . ' ' . $currency; // add $ for total and price if ($currency == 'USD') { $item_total = '$' . $item_total; $item_price = '$' . $item_price; } $line_items .= '<tr style="border-bottom: 1px solid #f0f0f0;"><td>' . $item_name . '<br><small>' . $item_number . '</small>' . $download_link . '</td><td align="right">' . $item_price . '</td><td align="right">' . $item_quantity . '</td><td align="right">' . $item_total . '</td></tr>'; array_push($items, $item); } } $items_json = json_encode($items); $data_json = json_encode($_POST); // create receipt $receipt = $line_items; // add a transaction $transaction = Transaction::Add($site['SiteId'], $processor, $processorTransactionId, $processorStatus, $email, $payerId, $name, $shipping, $fee, $tax, $total, $currency, $items_json, $data_json, $receipt); // replace {{transactionId}} in line_items $line_items = str_replace('{{transactionId}}', $transaction['TransactionId'], $line_items); $site_logo = ''; if ($site['LogoUrl'] != '' && $site['LogoUrl'] != NULL) { $site_logo = '<img src="' . $staticUrl . '/files/' . $site['LogoUrl'] . '" style="max-height:50px">'; } // setup currency for line items $shipping = $shipping . ' ' . $currency; $tax = $tax . ' ' . $currency; $total = $total . ' ' . $currency; // add $ for total and price if ($currency == 'USD') { $shipping = '$' . $shipping; $tax = '$' . $tax; $total = '$' . $total; } // send email $replace = array('{{site}}' => $site['Name'], '{{site-logo}}' => $site_logo, '{{reply-to}}' => $site['PrimaryEmail'], '{{line-items}}' => $line_items, '{{shipping}}' => $shipping, '{{tax}}' => $tax, '{{total}}' => $total); $subject = '[' . $site['Name'] . '] Receipt for your purchase from ' . $site['Name'] . ' (Transaction: ' . strtoupper($transaction['TransactionId']) . ') (Triangulate)'; $file = SITES_LOCATION . '/' . $site['FriendlyId'] . '/emails/receipt.html'; // send email $content = $site['ReceiptEmail']; // walk through and replace values in associative array foreach ($replace as $key => &$value) { $content = str_replace($key, $value, $content); $subject = str_replace($key, $value, $subject); } // send site email Utilities::SendSiteEmail($site, $email, $site['PrimaryEmail'], $site['Name'], $subject, $content); } else { // IPN response was "INVALID"\ } $response = new Tonic\Response(Tonic\Response::OK); $response->contentType = 'text/HTML'; $response->body = 'Yah!!!'; return $response; }