public function paypalnotifyAction()
 {
     // $str = array(2) { ["ItemNumber"]=> string(9) "EVT.12019" ["ItemPrice"]=> string(5) "19.00" }
     $PayPalCurrencyCode = 'USD';
     // Paypal Currency Code
     $PayPalReturnURL = WEBPATH . '/paypal-notify';
     // Point to process.php page
     $PayPalCancelURL = WEBPATH . '/cancelurl';
     // Cancel URL if user clicks cancel
     $postpaypal = $_POST;
     $paypalmode = PayPalMode == 'sandbox' ? '.sandbox' : '';
     if (!empty($postpaypal)) {
         // Other important variables like tax, shipping cost
         $TotalTaxAmount = 2.58;
         // Sum of tax for all items in this order.
         $HandalingCost = 2.0;
         // Handling cost for this order.
         $InsuranceCost = 1.0;
         // shipping insurance cost for this order.
         $ShippinDiscount = -3.0;
         // Shipping discount for this order. Specify this as negative number.
         $ShippinCost = 3.0;
         // Although you may change the value later, try to pass in a shipping amount that is reasonably accurate.
         $paypal_data = '';
         $ItemTotalPrice = 0;
         // $str = array(2) { ["ItemNumber"]=> string(9) "EVT.12019" ["ItemPrice"]=> string(5) "19.00" }
         $i = 0;
         // foreach($postpaypal as $key=>$itmname) {
         // $keyid = str_replace(" ","",$itmname['namepackge']);
         $postpaypal['qty'] = 1;
         $paypal_data .= '&L_PAYMENTREQUEST_0_NAME' . $i . '=' . urlencode($postpaypal['ItemNumber']);
         $paypal_data .= '&L_PAYMENTREQUEST_0_NUMBER' . $i . '=' . urlencode($postpaypal['ItemNumber']);
         $paypal_data .= '&L_PAYMENTREQUEST_0_AMT' . $i . '=' . urlencode($postpaypal['ItemPrice']);
         $paypal_data .= '&L_PAYMENTREQUEST_0_QTY' . $i . '=' . urlencode($postpaypal['qty']);
         // item price X quantity
         $subtotal = $postpaypal['ItemPrice'];
         // total price
         $ItemTotalPrice = $ItemTotalPrice + $subtotal;
         // create items for session
         $paypal_product['items'] = array('ItemNumber' => $postpaypal['ItemNumber'], 'id' => $postpaypal['ItemNumber'], 'ItemPrice' => $postpaypal['ItemPrice'], 'qty' => $postpaypal['qty'], 'oder' => $postpaypal['ItemNumber'], 'amount' => $postpaypal['amount'], 'type' => $postpaypal['type']);
         $oder_id = $postpaypal['ItemNumber'];
         // $i++;
         // }
         // Grand total including all tax, insurance, shipping cost and discount
         $GrandTotal = $ItemTotalPrice + $TotalTaxAmount + $HandalingCost + $InsuranceCost + $ShippinCost + $ShippinDiscount;
         $paypal_product['assets'] = array('oder' => $oder_id, 'tax_total' => $TotalTaxAmount, 'handaling_cost' => $HandalingCost, 'insurance_cost' => $InsuranceCost, 'shippin_discount' => $ShippinDiscount, 'shippin_cost' => $ShippinCost, 'grand_total' => $GrandTotal);
         // create session array for later use
         $session_paypal_products = new Container('paypal_products');
         $session_paypal_products->paypal_products = $paypal_product;
         // Parameters for SetExpressCheckout, which will be sent to PayPal
         $padata = '&METHOD=SetExpressCheckout' . '&RETURNURL=' . urlencode($PayPalReturnURL) . '&CANCELURL=' . urlencode($PayPalCancelURL) . '&PAYMENTREQUEST_0_PAYMENTACTION=' . urlencode("SALE") . $paypal_data . '&NOSHIPPING=0' . '&PAYMENTREQUEST_0_ITEMAMT=' . urlencode($ItemTotalPrice) . '&PAYMENTREQUEST_0_TAXAMT=' . urlencode($TotalTaxAmount) . '&PAYMENTREQUEST_0_SHIPPINGAMT=' . urlencode($ShippinCost) . '&PAYMENTREQUEST_0_HANDLINGAMT=' . urlencode($HandalingCost) . '&PAYMENTREQUEST_0_SHIPDISCAMT=' . urlencode($ShippinDiscount) . '&PAYMENTREQUEST_0_INSURANCEAMT=' . urlencode($InsuranceCost) . '&PAYMENTREQUEST_0_AMT=' . urlencode($GrandTotal) . '&PAYMENTREQUEST_0_CURRENCYCODE=' . urlencode($PayPalCurrencyCode) . '&LOCALECODE=GB' . '&LOGOIMG=' . WEBPATHURL . '/html/index/img/logo-lg4.png' . '&CARTBORDERCOLOR=FFFFFF' . '&ALLOWNOTE=1';
         // We need to execute the "SetExpressCheckOut" method to obtain paypal token
         $paypal = new MyPayPal();
         $httpParsedResponseAr = $paypal->PPHttpPost('SetExpressCheckout', $padata, PayPalApiUsername, PayPalApiPassword, PayPalApiSignature, PayPalMode);
         // Respond according to message we receive from Paypal
         if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
             // Redirect user to PayPal store with Token received.
             $paypalurl = 'https://www' . $paypalmode . '.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=' . $httpParsedResponseAr["TOKEN"] . '';
             $this->redirect()->toUrl($paypalurl);
         } else {
             echo 'There was an error occurred elephant campaign creation process, please try again with the link below';
             echo '<br/> <a href="' . WEBPATH . '">Try agian </a>';
             echo '<br/>Show error message SetExpressCheckout';
             /*
              * echo '<div style="color:red"><b>Error : </b>'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'</div>'; echo '<pre>'; print_r($httpParsedResponseAr); echo '</pre>';
              */
         }
     }
     // end post $postpaypal
     // -------------------------------------------------------------------------------------------------------------------
     $token = $this->params()->fromQuery('token');
     $payer_id = $this->params()->fromQuery('PayerID');
     // var_dump($token);die;
     // Paypal redirects back to this page using ReturnURL, We should receive TOKEN and Payer ID
     if (isset($token) && isset($payer_id)) {
         $token = $token;
         $payer_id = $payer_id;
         // var_dump($token);die;
         // get session variables
         $session_paypal_products = new Container('paypal_products');
         $paypal_productrt = $session_paypal_products->paypal_products;
         // echo 'paypal_productrt<pre>';
         // print_r($paypal_productrt);
         // echo '</pre>';
         // die;
         $paypal_datan = '';
         $ItemTotalPrice2 = 0;
         if (!empty($paypal_productrt)) {
             $j = 0;
             foreach ($paypal_productrt['items'] as $key => $p_item) {
                 $paypal_datan .= '&L_PAYMENTREQUEST_0_NAME' . $j . '=' . urlencode($p_item['ItemNumber']);
                 $paypal_datan .= '&L_PAYMENTREQUEST_0_NUMBER' . $j . '=' . urlencode($p_item['id']);
                 $paypal_datan .= '&L_PAYMENTREQUEST_0_AMT' . $j . '=' . urlencode($p_item['ItemPrice']);
                 $paypal_datan .= '&L_PAYMENTREQUEST_0_QTY' . $j . '=' . urlencode($p_item['qty']);
                 $oder_id_n = $p_item['oder'];
                 // item price X quantity
                 $subtotal2 = $p_item['ItemPrice'];
                 // total price
                 $ItemTotalPrice2 = $ItemTotalPrice2 + $subtotal2;
                 $j++;
             }
         }
         $padatan = '&TOKEN=' . urlencode($token) . '&PAYERID=' . urlencode($payer_id) . '&PAYMENTREQUEST_0_PAYMENTACTION=' . urlencode("SALE") . $paypal_datan . '&PAYMENTREQUEST_0_ITEMAMT=' . urlencode($ItemTotalPrice2) . '&PAYMENTREQUEST_0_TAXAMT=' . urlencode($paypal_productrt['assets']['tax_total']) . '&PAYMENTREQUEST_0_SHIPPINGAMT=' . urlencode($paypal_productrt['assets']['shippin_cost']) . '&PAYMENTREQUEST_0_HANDLINGAMT=' . urlencode($paypal_productrt['assets']['handaling_cost']) . '&PAYMENTREQUEST_0_SHIPDISCAMT=' . urlencode($paypal_productrt['assets']['shippin_discount']) . '&PAYMENTREQUEST_0_INSURANCEAMT=' . urlencode($paypal_productrt['assets']['insurance_cost']) . '&PAYMENTREQUEST_0_AMT=' . urlencode($paypal_productrt['assets']['grand_total']) . '&PAYMENTREQUEST_0_CURRENCYCODE=' . urlencode($PayPalCurrencyCode);
         // $oder_id_n = $paypal_productrt['oder'];
         // We need to execute the "DoExpressCheckoutPayment" at this point to Receive payment from user.
         $paypal_do = new MyPayPal();
         $httpParsedResponseAr = $paypal_do->PPHttpPost('DoExpressCheckoutPayment', $padatan, PayPalApiUsername, PayPalApiPassword, PayPalApiSignature, PayPalMode);
         // Check if everything went ok..
         if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
             if ('Completed' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) {
                 // echo '<div style="color:green">Payment Received! Your product will be sent to you very soon!</div>';
             } elseif ('Pending' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) {
                 echo '<div style="color:red">Transaction Complete, but payment is still pending! ' . 'You need to manually authorize this payment in your <a target="_new" href="http://www.paypal.com">Paypal Account</a></div>';
             }
             // we can retrive transection details using either GetTransactionDetails or GetExpressCheckoutDetails
             // GetTransactionDetails requires a Transaction ID, and GetExpressCheckoutDetails requires Token returned by SetExpressCheckOut
             $padata = '&TOKEN=' . urlencode($token);
             $paypal = new MyPayPal();
             $httpParsedResponseAr = $paypal->PPHttpPost('GetExpressCheckoutDetails', $padata, PayPalApiUsername, PayPalApiPassword, PayPalApiSignature, PayPalMode);
             if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
                 // SAVE BUYER INFORMATION IN DATABASE ###
                 $buyerName = urldecode($httpParsedResponseAr["FIRSTNAME"]) . ' ' . urldecode($httpParsedResponseAr["LASTNAME"]);
                 $buyerEmail = urldecode($httpParsedResponseAr["EMAIL"]);
                 $transactionID = $httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"];
                 $Buyerdata = array('BuyerName' => $buyerName, 'BuyerEmail' => $buyerEmail, 'TransactionID' => $transactionID, 'ItemName' => $ItemName, 'ItemNumber' => $ItemNumber, 'ItemAmount' => $ItemTotalPrice, 'ItemQTY' => $ItemQTY);
                 // active process + ads + oder
                 $str = str_replace('EVT.', '', $oder_id_n);
                 $int = (int) $str;
                 $invoice_id = $int - 12015;
                 $invoice_checkupdate = $this->getServiceLocator()->get('InvoiceTable')->Update_status_pay($invoice_id);
                 // save buyer
                 $Buyer = new Buyer();
                 $Buyer->exchangeArray($Buyerdata);
                 $insert_row = $this->getServiceLocator()->get('BuyerTable')->save($Buyer);
                 // chec
                 // echo '</br>oder_id_n</br>'.$oder_id_n;
                 // echo 'odercheckupdate :</br> '.$odercheckupdate ;
                 // echo '</br>adscheckupdate :</br> '.$adscheckupdate ;
                 // echo '</br>insert_row :</br> '.$insert_row ;
                 // die;
                 if ($insert_row != 0 and $invoice_checkupdate == 1) {
                     // print 'Success! ID of last inserted record is : ' .$insert_row .'<br />';
                     $paypalurlCSS = WEBPATH;
                     // header('Location: '.$paypalurlCSS);
                     $this->redirect()->toUrl($paypalurlCSS);
                 } else {
                     die('Error Not save buyer: ');
                 }
             } else {
                 echo '<div style="color:red"><b>GetTransactionDetails failed:</b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
                 echo '<pre>';
                 print_r($httpParsedResponseAr);
                 echo '</pre>';
             }
         } else {
             echo 'DoExpressCheckoutPayment Error';
             echo '<div style="color:red"><b>Error : </b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
             echo '<pre>';
             print_r($httpParsedResponseAr);
             echo '</pre>';
         }
     }
 }
Esempio n. 2
0
     echo '<div style="color:green">Payment Received! Your product will be sent to you very soon!</div>';
 } elseif ('Pending' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) {
     //echo '<div style="color:red">Transaction Complete, but payment is still pending! '.
     //'You need to manually authorize this payment in your <a target="_new" href="http://www.paypal.com">Paypal Account</a></div>';
     /* --- FINISH --- */
     $_SESSION['paypal']['order_number'] = $order_number;
     $_SESSION['paypal']['code'] = 201;
     $_SESSION['paypal']['email'] = 'ready';
     /* --- SUCCESS --- */
     $page = 'finish-paypal';
     safe_redirect($page);
 }
 // we can retrive transection details using either GetTransactionDetails or GetExpressCheckoutDetails
 // GetTransactionDetails requires a Transaction ID, and GetExpressCheckoutDetails requires Token returned by SetExpressCheckOut
 $padata = '&TOKEN=' . urlencode($token);
 $paypal = new MyPayPal();
 $httpParsedResponseAr = $paypal->PPHttpPost('GetExpressCheckoutDetails', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
 if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
     //echo '<br /><b>Stuff to store in database :</b><br />';
     //echo '<pre>';
     /*
     					#### SAVE BUYER INFORMATION IN DATABASE ###
     					//see (http://www.sanwebe.com/2013/03/basic-php-mysqli-usage) for mysqli usage
     					//use urldecode() to decode url encoded strings.
     $buyerName = urldecode($httpParsedResponseAr["FIRSTNAME"]).' '.urldecode($httpParsedResponseAr["LASTNAME"]);
     					$buyerEmail = urldecode($httpParsedResponseAr["EMAIL"]);
     //Open a new connection to the MySQL server
     					$mysqli = new mysqli('host','username','password','database_name');
     //Output any connection error
     					if ($mysqli->connect_error) {
     						die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
Esempio n. 3
0
 public function getData($param)
 {
     $token = $param["token"];
     $payer_id = $param["PayerID"];
     //get session variables
     $ItemName = $_SESSION['ItemName'];
     //Item Name
     $ItemPrice = $_SESSION['ItemPrice'];
     //Item Price
     $ItemNumber = $_SESSION['ItemNumber'];
     //Item Number
     $ItemDesc = $_SESSION['ItemDesc'];
     //Item Number
     $ItemQty = $_SESSION['ItemQty'];
     // Item Quantity
     $ItemTotalPrice = $_SESSION['ItemTotalPrice'];
     //(Item Price x Quantity = Total) Get total amount of product;
     $TotalTaxAmount = $_SESSION['TotalTaxAmount'];
     //Sum of tax for all items in this order.
     $HandalingCost = $_SESSION['HandalingCost'];
     //Handling cost for this order.
     $InsuranceCost = $_SESSION['InsuranceCost'];
     //shipping insurance cost for this order.
     $ShippinDiscount = $_SESSION['ShippinDiscount'];
     //Shipping discount for this order. Specify this as negative number.
     $ShippinCost = $_SESSION['ShippinCost'];
     //Although you may change the value later, try to pass in a shipping amount that is reasonably accurate.
     $GrandTotal = $_SESSION['GrandTotal'];
     $padata = '&TOKEN=' . urlencode($token) . '&PAYERID=' . urlencode($payer_id) . '&PAYMENTREQUEST_0_PAYMENTACTION=' . urlencode("SALE") . '&L_PAYMENTREQUEST_0_NAME0=' . urlencode($ItemName) . '&L_PAYMENTREQUEST_0_NUMBER0=' . urlencode($ItemNumber) . '&L_PAYMENTREQUEST_0_DESC0=' . urlencode($ItemDesc) . '&L_PAYMENTREQUEST_0_AMT0=' . urlencode($ItemPrice) . '&L_PAYMENTREQUEST_0_QTY0=' . urlencode($ItemQty) . '&PAYMENTREQUEST_0_ITEMAMT=' . urlencode($ItemTotalPrice) . '&PAYMENTREQUEST_0_TAXAMT=' . urlencode($TotalTaxAmount) . '&PAYMENTREQUEST_0_SHIPPINGAMT=' . urlencode($ShippinCost) . '&PAYMENTREQUEST_0_HANDLINGAMT=' . urlencode($HandalingCost) . '&PAYMENTREQUEST_0_SHIPDISCAMT=' . urlencode($ShippinDiscount) . '&PAYMENTREQUEST_0_INSURANCEAMT=' . urlencode($InsuranceCost) . '&PAYMENTREQUEST_0_AMT=' . urlencode($GrandTotal) . '&PAYMENTREQUEST_0_CURRENCYCODE=' . urlencode($this->PayPalCurrencyCode);
     //We need to execute the "DoExpressCheckoutPayment" at this point to Receive payment from user.
     $paypal = new MyPayPal();
     $httpParsedResponseAr = $paypal->PPHttpPost('DoExpressCheckoutPayment', $padata, $this->PayPalApiUsername, $this->PayPalApiPassword, $this->PayPalApiSignature, $this->PayPalMode);
     //Check if everything went ok..
     if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
         //        echo '<h2>Success</h2>';
         //        echo 'Your Transaction ID : '.urldecode($httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"]);
         /*
         //Sometimes Payment are kept pending even when transaction is complete.
         //hence we need to notify user about it and ask him manually approve the transiction
         */
         if ('Completed' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) {
             //            header("Content-type:text/html;charset=utf-8");
             echo '<div style="color:green">Payment Received! Your product will be sent to you very soon!</div>';
         } elseif ('Pending' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) {
             echo '<div style="color:red">Transaction Complete, but payment is still pending! ' . 'You need to manually authorize this payment in your <a target="_new" href="http://www.paypal.com">Paypal Account</a></div>';
         }
         // we can retrive transection details using either GetTransactionDetails or GetExpressCheckoutDetails
         // GetTransactionDetails requires a Transaction ID, and GetExpressCheckoutDetails requires Token returned by SetExpressCheckOut
         $padata = '&TOKEN=' . urlencode($token);
         $paypal = new MyPayPal();
         $httpParsedResponseAr = $paypal->PPHttpPost('GetExpressCheckoutDetails', $padata, $this->PayPalApiUsername, $this->PayPalApiPassword, $this->PayPalApiSignature, $this->PayPalMode);
         die;
         if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
             echo '<br /><b>Stuff to store in database :</b><br /><pre>';
             echo '<pre>';
             print_r($httpParsedResponseAr);
             echo '</pre>';
         } else {
             echo '<div style="color:red"><b>GetTransactionDetails failed:</b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
             echo '<pre>';
             print_r($httpParsedResponseAr);
             echo '</pre>';
         }
     } else {
         echo '<div style="color:red">支付失败<b>Error : </b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
         echo '<pre>';
         //        print_r($httpParsedResponseAr);
         echo '</pre>';
     }
 }
Esempio n. 4
0
 function run()
 {
     //start session in all pages
     session_start();
     //PHP >= 5.4.0
     //if(session_id() == '') { session_start(); } //uncomment this line if PHP < 5.4.0 and comment out line above
     $PayPalMode = 'sandbox';
     // sandbox or live
     $PayPalApiUsername = '******';
     //PayPal API Username
     $PayPalApiPassword = '******';
     //Paypal API password
     $PayPalApiSignature = 'AFcWxV21C7fd0v3bYYYRCpSSRl31AMo4Sr5CuFAYAsMOj.Mc4vQaYcSn';
     //Paypal API Signature
     $PayPalCurrencyCode = 'USD';
     //Paypal Currency Code
     $PayPalReturnURL = 'http://jolyjokerz.com/payment/paypal/complete';
     //Point to process.php page
     $PayPalCancelURL = 'http://jolyjokerz.com/payment/paypal/error';
     //Cancel URL if user clicks cancel
     $paypalmode = $PayPalMode == 'sandbox' ? '.sandbox' : '';
     if ($_POST) {
         //Mainly we need 4 variables from product page Item Name, Item Price, Item Number and Item Quantity.
         //Please Note : People can manipulate hidden field amounts in form,
         //In practical world you must fetch actual price from database using item id. Eg:
         //$ItemPrice = $mysqli->query("SELECT item_price FROM products WHERE id = Product_Number");
         $ItemName = "test";
         //Item Name
         $ItemPrice = 321312;
         //Item Price
         $ItemNumber = 13213123;
         //Item Number
         $ItemDesc = "test";
         //Item Number
         $ItemQty = 2;
         // Item Quantity
         $ItemTotalPrice = $ItemPrice * $ItemQty;
         //(Item Price x Quantity = Total) Get total amount of product;
         //Other important variables like tax, shipping cost
         $TotalTaxAmount = 2.58;
         //Sum of tax for all items in this order.
         $HandalingCost = 2.0;
         //Handling cost for this order.
         $InsuranceCost = 1.0;
         //shipping insurance cost for this order.
         $ShippinDiscount = -3.0;
         //Shipping discount for this order. Specify this as negative number.
         $ShippinCost = 3.0;
         //Although you may change the value later, try to pass in a shipping amount that is reasonably accurate.
         //Grand total including all tax, insurance, shipping cost and discount
         $GrandTotal = $ItemTotalPrice + $TotalTaxAmount + $HandalingCost + $InsuranceCost + $ShippinCost + $ShippinDiscount;
         //Parameters for SetExpressCheckout, which will be sent to PayPal
         $padata = '&METHOD=SetExpressCheckout' . '&RETURNURL=' . urlencode($PayPalReturnURL) . '&CANCELURL=' . urlencode($PayPalCancelURL) . '&PAYMENTREQUEST_0_PAYMENTACTION=' . urlencode("SALE") . '&L_PAYMENTREQUEST_0_NAME0=' . urlencode($ItemName) . '&L_PAYMENTREQUEST_0_NUMBER0=' . urlencode($ItemNumber) . '&L_PAYMENTREQUEST_0_DESC0=' . urlencode($ItemDesc) . '&L_PAYMENTREQUEST_0_AMT0=' . urlencode($ItemPrice) . '&L_PAYMENTREQUEST_0_QTY0=' . urlencode($ItemQty) . '&NOSHIPPING=0' . '&PAYMENTREQUEST_0_ITEMAMT=' . urlencode($ItemTotalPrice) . '&PAYMENTREQUEST_0_TAXAMT=' . urlencode($TotalTaxAmount) . '&PAYMENTREQUEST_0_SHIPPINGAMT=' . urlencode($ShippinCost) . '&PAYMENTREQUEST_0_HANDLINGAMT=' . urlencode($HandalingCost) . '&PAYMENTREQUEST_0_SHIPDISCAMT=' . urlencode($ShippinDiscount) . '&PAYMENTREQUEST_0_INSURANCEAMT=' . urlencode($InsuranceCost) . '&PAYMENTREQUEST_0_AMT=' . urlencode($GrandTotal) . '&PAYMENTREQUEST_0_CURRENCYCODE=' . urlencode($PayPalCurrencyCode) . '&LOCALECODE=GB' . '&LOGOIMG=http://www.sanwebe.com/wp-content/themes/sanwebe/img/logo.png' . '&CARTBORDERCOLOR=FFFFFF' . '&ALLOWNOTE=1';
         ############# set session variable we need later for "DoExpressCheckoutPayment" #######
         $_SESSION['ItemName'] = $ItemName;
         //Item Name
         $_SESSION['ItemPrice'] = $ItemPrice;
         //Item Price
         $_SESSION['ItemNumber'] = $ItemNumber;
         //Item Number
         $_SESSION['ItemDesc'] = $ItemDesc;
         //Item Number
         $_SESSION['ItemQty'] = $ItemQty;
         // Item Quantity
         $_SESSION['ItemTotalPrice'] = $ItemTotalPrice;
         //(Item Price x Quantity = Total) Get total amount of product;
         $_SESSION['TotalTaxAmount'] = $TotalTaxAmount;
         //Sum of tax for all items in this order.
         $_SESSION['HandalingCost'] = $HandalingCost;
         //Handling cost for this order.
         $_SESSION['InsuranceCost'] = $InsuranceCost;
         //shipping insurance cost for this order.
         $_SESSION['ShippinDiscount'] = $ShippinDiscount;
         //Shipping discount for this order. Specify this as negative number.
         $_SESSION['ShippinCost'] = $ShippinCost;
         //Although you may change the value later, try to pass in a shipping amount that is reasonably accurate.
         $_SESSION['GrandTotal'] = $GrandTotal;
         //We need to execute the "SetExpressCheckOut" method to obtain paypal token
         $httpParsedResponseAr = $this->PPHttpPost('SetExpressCheckout', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
         //Respond according to message we receive from Paypal
         if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
             //Redirect user to PayPal store with Token received.
             $paypalurl = 'https://www' . $paypalmode . '.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=' . $httpParsedResponseAr["TOKEN"] . '';
             header('Location: ' . $paypalurl);
         } else {
             //Show error message
             echo '<div style="color:red"><b>Error : </b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
             echo '<pre>';
             print_r($httpParsedResponseAr);
             echo '</pre>';
         }
     }
     //Paypal redirects back to this page using ReturnURL, We should receive TOKEN and Payer ID
     if (isset($_GET["token"]) && isset($_GET["PayerID"])) {
         //we will be using these two variables to execute the "DoExpressCheckoutPayment"
         //Note: we haven't received any payment yet.
         $token = $_GET["token"];
         $payer_id = $_GET["PayerID"];
         //get session variables
         $ItemName = $_SESSION['ItemName'];
         //Item Name
         $ItemPrice = $_SESSION['ItemPrice'];
         //Item Price
         $ItemNumber = $_SESSION['ItemNumber'];
         //Item Number
         $ItemDesc = $_SESSION['ItemDesc'];
         //Item Number
         $ItemQty = $_SESSION['ItemQty'];
         // Item Quantity
         $ItemTotalPrice = $_SESSION['ItemTotalPrice'];
         //(Item Price x Quantity = Total) Get total amount of product;
         $TotalTaxAmount = $_SESSION['TotalTaxAmount'];
         //Sum of tax for all items in this order.
         $HandalingCost = $_SESSION['HandalingCost'];
         //Handling cost for this order.
         $InsuranceCost = $_SESSION['InsuranceCost'];
         //shipping insurance cost for this order.
         $ShippinDiscount = $_SESSION['ShippinDiscount'];
         //Shipping discount for this order. Specify this as negative number.
         $ShippinCost = $_SESSION['ShippinCost'];
         //Although you may change the value later, try to pass in a shipping amount that is reasonably accurate.
         $GrandTotal = $_SESSION['GrandTotal'];
         $padata = '&TOKEN=' . urlencode($token) . '&PAYERID=' . urlencode($payer_id) . '&PAYMENTREQUEST_0_PAYMENTACTION=' . urlencode("SALE") . '&L_PAYMENTREQUEST_0_NAME0=' . urlencode($ItemName) . '&L_PAYMENTREQUEST_0_NUMBER0=' . urlencode($ItemNumber) . '&L_PAYMENTREQUEST_0_DESC0=' . urlencode($ItemDesc) . '&L_PAYMENTREQUEST_0_AMT0=' . urlencode($ItemPrice) . '&L_PAYMENTREQUEST_0_QTY0=' . urlencode($ItemQty) . '&PAYMENTREQUEST_0_ITEMAMT=' . urlencode($ItemTotalPrice) . '&PAYMENTREQUEST_0_TAXAMT=' . urlencode($TotalTaxAmount) . '&PAYMENTREQUEST_0_SHIPPINGAMT=' . urlencode($ShippinCost) . '&PAYMENTREQUEST_0_HANDLINGAMT=' . urlencode($HandalingCost) . '&PAYMENTREQUEST_0_SHIPDISCAMT=' . urlencode($ShippinDiscount) . '&PAYMENTREQUEST_0_INSURANCEAMT=' . urlencode($InsuranceCost) . '&PAYMENTREQUEST_0_AMT=' . urlencode($GrandTotal) . '&PAYMENTREQUEST_0_CURRENCYCODE=' . urlencode($PayPalCurrencyCode);
         //We need to execute the "DoExpressCheckoutPayment" at this point to Receive payment from user.
         $paypal = new MyPayPal();
         $httpParsedResponseAr = $paypal->PPHttpPost('DoExpressCheckoutPayment', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
         //Check if everything went ok..
         if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
             echo '<h2>Success</h2>';
             echo 'Your Transaction ID : ' . urldecode($httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"]);
             /*
             //Sometimes Payment are kept pending even when transaction is complete. 
             //hence we need to notify user about it and ask him manually approve the transiction
             */
             if ('Completed' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) {
                 echo '<div style="color:green">Payment Received! Your product will be sent to you very soon!</div>';
             } elseif ('Pending' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) {
                 echo '<div style="color:red">Transaction Complete, but payment is still pending! ' . 'You need to manually authorize this payment in your <a target="_new" href="http://www.paypal.com">Paypal Account</a></div>';
             }
             // we can retrive transection details using either GetTransactionDetails or GetExpressCheckoutDetails
             // GetTransactionDetails requires a Transaction ID, and GetExpressCheckoutDetails requires Token returned by SetExpressCheckOut
             $padata = '&TOKEN=' . urlencode($token);
             $paypal = new MyPayPal();
             $httpParsedResponseAr = $paypal->PPHttpPost('GetExpressCheckoutDetails', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
             if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
                 echo '<br /><b>Stuff to store in database :</b><br /><pre>';
                 /*
                 					#### SAVE BUYER INFORMATION IN DATABASE ###
                 					//see (http://www.sanwebe.com/2013/03/basic-php-mysqli-usage) for mysqli usage
                 $buyerName = $httpParsedResponseAr["FIRSTNAME"].' '.$httpParsedResponseAr["LASTNAME"];
                 					$buyerEmail = $httpParsedResponseAr["EMAIL"];
                 //Open a new connection to the MySQL server
                 					$mysqli = new mysqli('host','username','password','database_name');
                 //Output any connection error
                 					if ($mysqli->connect_error) {
                 						die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
                 					}		
                 $insert_row = $mysqli->query("INSERT INTO BuyerTable 
                 					(BuyerName,BuyerEmail,TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)
                 					VALUES ('$buyerName','$buyerEmail','$transactionID','$ItemName',$ItemNumber, $ItemTotalPrice,$ItemQTY)");
                 if($insert_row){
                 						print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />'; 
                 					}else{
                 						die('Error : ('. $mysqli->errno .') '. $mysqli->error);
                 					}
                 */
                 echo '<pre>';
                 print_r($httpParsedResponseAr);
                 echo '</pre>';
             } else {
                 echo '<div style="color:red"><b>GetTransactionDetails failed:</b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
                 echo '<pre>';
                 print_r($httpParsedResponseAr);
                 echo '</pre>';
             }
         } else {
             echo '<div style="color:red"><b>Error : </b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
             echo '<pre>';
             print_r($httpParsedResponseAr);
             echo '</pre>';
         }
     }
 }
 public function checkoutpaypalAction()
 {
     $this->layout('layout/lazadacheckout');
     $container = new Container('shopcart_lazada');
     $arraycart = $container->cart_lazada;
     $name = addslashes(trim($this->params()->fromPost('name')));
     $mail = addslashes(trim($this->params()->fromPost('email')));
     $phone = addslashes(trim($this->params()->fromPost('phone')));
     $address = addslashes(trim($this->params()->fromPost('address')));
     $checkout = addslashes(trim($this->params()->fromPost('checkout')));
     $id_us = addslashes(trim($this->params()->fromPost('idus')));
     //$total_price = addslashes(trim($this->params()->fromPost('totalprice')));
     //$time = addslashes(trim($this->params()->fromPost('time')));
     $paypalmode = PayPalMode == 'sandbox' ? '.sandbox' : '';
     $PayPalCurrencyCode = 'USD';
     //Paypal Currency Code
     $PayPalReturnURL = WEBPATH . '/shoppingcart/lazada/checkoutpaypal';
     //Point to process.php page
     $PayPalCancelURL = WEBPATH . '/shoppingcart/lazada/cancel';
     //Cancel URL if user clicks cancel
     foreach ($arraycart as $key => $value) {
         $arrayproduct[] = $key;
     }
     $listproduct_cat = $this->getProductAdtTable()->product_viewcart($arrayproduct);
     foreach ($listproduct_cat as $key1 => $value1) {
         $qty = $arraycart[$value1['id']];
         if ($value1['sale_products'] == 1) {
             $price = $value1['price'] - $value1['price'] * $value1['promotions'] / 100;
         } else {
             $price = $value1['price'];
         }
         $total_price += $qty * $price;
     }
     $customer = array('id_user' => $id_us, 'customer' => $name, 'email' => $mail, 'address' => $address, 'phone' => $phone, 'time' => '', 'totalprice' => $total_price, 'type' => $checkout);
     $post = $this->getRequest();
     if ($post->isPost()) {
         $TotalTaxAmount = 2.58;
         //Sum of tax for all items in this order.
         $HandalingCost = 2.0;
         //Handling cost for this order.
         $InsuranceCost = 1.0;
         //shipping insurance cost for this order.
         $ShippinDiscount = -3.0;
         //Shipping discount for this order. Specify this as negative number.
         $ShippinCost = 3.0;
         $paypal_data = '';
         $ItemTotalPrice = 0;
         foreach ($listproduct_cat as $key => $itmname) {
             $Qty = $arraycart[$itmname['id']];
             if ($itmname['sale_products'] == 1) {
                 $price_s = $itmname['price'] - $itmname['price'] * $itmname['promotions'] / 100;
             } else {
                 $price_s = $itmname['price'];
             }
             $paypal_data .= '&L_PAYMENTREQUEST_0_NAME' . $key . '=' . urlencode($itmname['name']);
             $paypal_data .= '&L_PAYMENTREQUEST_0_NUMBER' . $key . '=' . urlencode($itmname['id']);
             $paypal_data .= '&L_PAYMENTREQUEST_0_AMT' . $key . '=' . urlencode($price_s);
             $paypal_data .= '&L_PAYMENTREQUEST_0_QTY' . $key . '=' . urlencode($Qty);
             // item price X quantity
             $subtotal = $Qty * $price_s;
             //total price
             $ItemTotalPrice = $ItemTotalPrice + $subtotal;
             //create items for session
             $paypal_product['items'][] = array('name' => $itmname['name'], 'Qty' => $Qty, 'price' => $price_s, 'id' => $itmname['id']);
         }
         //Grand total including all tax, insurance, shipping cost and discount
         $GrandTotal = $ItemTotalPrice + $TotalTaxAmount + $HandalingCost + $InsuranceCost + $ShippinCost + $ShippinDiscount;
         $paypal_product['assets'] = array('tax_total' => $TotalTaxAmount, 'handaling_cost' => $HandalingCost, 'insurance_cost' => $InsuranceCost, 'shippin_discount' => $ShippinDiscount, 'shippin_cost' => $ShippinCost, 'grand_total' => $GrandTotal);
         $session_paypal_products = new Container('paypal_products');
         $session_paypal_products->paypal_products = $paypal_product;
         $session_customer = new Container('customer');
         $session_customer->customer = $customer;
         //Parameters for SetExpressCheckout, which will be sent to PayPal
         $padata = '&METHOD=SetExpressCheckout' . '&RETURNURL=' . urlencode($PayPalReturnURL) . '&CANCELURL=' . urlencode($PayPalCancelURL) . '&PAYMENTREQUEST_0_PAYMENTACTION=' . urlencode("SALE") . $paypal_data . '&NOSHIPPING=0' . '&PAYMENTREQUEST_0_ITEMAMT=' . urlencode($ItemTotalPrice) . '&PAYMENTREQUEST_0_TAXAMT=' . urlencode($TotalTaxAmount) . '&PAYMENTREQUEST_0_SHIPPINGAMT=' . urlencode($ShippinCost) . '&PAYMENTREQUEST_0_HANDLINGAMT=' . urlencode($HandalingCost) . '&PAYMENTREQUEST_0_SHIPDISCAMT=' . urlencode($ShippinDiscount) . '&PAYMENTREQUEST_0_INSURANCEAMT=' . urlencode($InsuranceCost) . '&PAYMENTREQUEST_0_AMT=' . urlencode($GrandTotal) . '&PAYMENTREQUEST_0_CURRENCYCODE=' . urlencode($PayPalCurrencyCode) . '&LOCALECODE=GB' . '&LOGOIMG=http://s11.bestmediainvestgroup.eu/public/advhtml/image/logo.png' . '&CARTBORDERCOLOR=FFFFFF' . '&ALLOWNOTE=1';
         /*
          echo "padata :<pre>";
          print_r($padata);
          echo "</pre>";
         
          die;
         */
         //We need to execute the "SetExpressCheckOut" method to obtain paypal token
         $paypal = new MyPayPal();
         $httpParsedResponseAr = $paypal->PPHttpPost('SetExpressCheckout', $padata, PayPalApiUsername, PayPalApiPassword, PayPalApiSignature, PayPalMode);
         //Respond according to message we receive from Paypal
         if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
             //Redirect user to PayPal store with Token received.
             $paypalurl = 'https://www' . $paypalmode . '.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=' . $httpParsedResponseAr["TOKEN"] . '';
             $this->redirect()->toUrl($paypalurl);
             //header('Location: '.$paypalurl);
         } else {
             //Show error message
             echo '<div style="color:red"><b>Error : </b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
             echo '<pre>';
             print_r($httpParsedResponseAr);
             echo '</pre>';
         }
     }
     //Paypal redirects back to this page using ReturnURL, We should receive TOKEN and Payer ID
     if (isset($_GET["token"]) && isset($_GET["PayerID"])) {
         $token = $_GET["token"];
         $payer_id = $_GET["PayerID"];
         $session_customer_new = new Container('customer');
         $paypal_productrts = $session_customer_new->customer;
         $session_paypal_products = new Container('paypal_products');
         $paypal_productrt = $session_paypal_products->paypal_products;
         $paypal_datan = '';
         $ItemTotalPrice2 = 0;
         if (!empty($paypal_productrt)) {
             $j = 0;
             foreach ($paypal_productrt['items'] as $key => $p_item) {
                 if ($p_item['sale_products'] == 1) {
                     $price_s1 = $p_item['price'] - $p_item['price'] * $p_item['promotions'] / 100;
                 } else {
                     $price_s1 = $p_item['price'];
                 }
                 $Qty = $arraycart[$p_item['id']];
                 $paypal_datan .= '&L_PAYMENTREQUEST_0_NAME' . $j . '=' . urlencode($p_item['name']);
                 $paypal_datan .= '&L_PAYMENTREQUEST_0_NUMBER' . $j . '=' . urlencode($p_item['id']);
                 $paypal_datan .= '&L_PAYMENTREQUEST_0_AMT' . $j . '=' . urlencode($price_s1);
                 $paypal_datan .= '&L_PAYMENTREQUEST_0_QTY' . $j . '=' . urlencode($Qty);
                 // item price X quantity
                 $subtotal2 = $Qty * $price_s1;
                 //total price
                 $ItemTotalPrice2 = $ItemTotalPrice2 + $subtotal2;
                 $j++;
             }
         }
         $padatan = '&TOKEN=' . urlencode($token) . '&PAYERID=' . urlencode($payer_id) . '&PAYMENTREQUEST_0_PAYMENTACTION=' . urlencode("SALE") . $paypal_datan . '&PAYMENTREQUEST_0_ITEMAMT=' . urlencode($ItemTotalPrice2) . '&PAYMENTREQUEST_0_TAXAMT=' . urlencode($paypal_productrt['assets']['tax_total']) . '&PAYMENTREQUEST_0_SHIPPINGAMT=' . urlencode($paypal_productrt['assets']['shippin_cost']) . '&PAYMENTREQUEST_0_HANDLINGAMT=' . urlencode($paypal_productrt['assets']['handaling_cost']) . '&PAYMENTREQUEST_0_SHIPDISCAMT=' . urlencode($paypal_productrt['assets']['shippin_discount']) . '&PAYMENTREQUEST_0_INSURANCEAMT=' . urlencode($paypal_productrt['assets']['insurance_cost']) . '&PAYMENTREQUEST_0_AMT=' . urlencode($paypal_productrt['assets']['grand_total']) . '&PAYMENTREQUEST_0_CURRENCYCODE=' . urlencode($PayPalCurrencyCode);
         //$oder_id_n = $paypal_productrt['assets']['oder'];
         //We need to execute the "DoExpressCheckoutPayment" at this point to Receive payment from user.
         $paypal = new MyPayPal();
         $httpParsedResponseAr = $paypal->PPHttpPost('DoExpressCheckoutPayment', $padatan, PayPalApiUsername, PayPalApiPassword, PayPalApiSignature, PayPalMode);
         //Check if everything went ok..
         if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
             //echo '<h2>Success</h2>';
             //echo 'Your Transaction ID : ' . urldecode($httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"]);
             //Lưu lại ID paypal để lưu vào db
             $_SESSION['id_paypal'] = urldecode($httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"]);
             /*
              //Sometimes Payment are kept pending even when transaction is complete.
              //hence we need to notify user about it and ask him manually approve the transiction
             */
             if ('Completed' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) {
                 //echo '<div style="color:green">Payment Received! Your product will be sent to you very soon!</div>';
             } elseif ('Pending' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) {
                 echo '<div style="color:red">Transaction Complete, but payment is still pending! ' . 'You need to manually authorize this payment in your <a target="_new" href="http://www.paypal.com">Paypal Account</a></div>';
             }
             $padata = '&TOKEN=' . urlencode($token);
             $paypal = new MyPayPal();
             $httpParsedResponseAr = $paypal->PPHttpPost('GetExpressCheckoutDetails', $padata, PayPalApiUsername, PayPalApiPassword, PayPalApiSignature, PayPalMode);
             if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
                 $buyerName = urldecode($httpParsedResponseAr["FIRSTNAME"]) . ' ' . urldecode($httpParsedResponseAr["LASTNAME"]);
                 $buyerEmail = urldecode($httpParsedResponseAr["EMAIL"]);
                 //echo '<pr>';
                 // echo $buyerName . '<br/>';
                 //echo $buyerEmail . '<br/>';
                 $session_customer_new = new Container('customer');
                 $customer_add = $session_customer_new->customer;
                 //print_r($customer_add);die;
                 // Lưu thông tin hóa đơn vào database
                 $dataoder = array('customer' => $customer_add['customer'], 'email' => $customer_add['email'], 'address' => $customer_add['address'], 'phone' => $customer_add['phone'], 'time' => $customer_add['time'], 'totalprice' => $customer_add['totalprice'], 'type' => $customer_add['type']);
                 $obj = new Oder();
                 $obj->exchangeArray($dataoder);
                 $this->getOrderAdtTable()->addoder($obj);
                 //Add oder detail
                 $get_odernew = $this->getOrderAdtTable()->getoder_new();
                 $id_odernew = $get_odernew['id'];
                 foreach ($arraycart as $key => $value) {
                     $arrayproduct[] = $key;
                 }
                 $listproduct_cat = $this->getProductAdtTable()->product_viewcart($arrayproduct);
                 foreach ($listproduct_cat as $key1 => $value1) {
                     $qty = $arraycart[$value1['id']];
                     $id_product = $value1['id'];
                     if ($value1['sale_products'] == 1) {
                         $price_product = $value1['price'] - $value1['price'] * $value1['promotions'] / 100;
                     } else {
                         $price_product = $value1['price'];
                     }
                     $datadetail = array('oder_id' => $id_odernew, 'quantity' => $qty, 'id_product' => $id_product, 'price_product' => $price_product);
                     $objdetail = new Oderdetail();
                     $objdetail->exchangeArray($datadetail);
                     $this->getOrderdetailAdtTable()->addoder_detail($objdetail);
                 }
                 $container = new Container('shopcart_lazada');
                 $arraycart = $container->cart_lazada;
                 unset($arraycart);
                 $container->cart_lazada = $arraycart;
                 //print_r($session_customer->name);
                 //echo '<pre>';
                 // print_r($httpParsedResponseAr);
                 //echo '</pre>';
             } else {
                 echo '<div style="color:red"><b>GetTransactionDetails failed:</b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
                 echo '<pre>';
                 print_r($httpParsedResponseAr);
                 echo '</pre>';
             }
         } else {
             echo '<div style="color:red"><b>Error : </b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
             echo '<pre>';
             print_r($httpParsedResponseAr);
             echo '</pre>';
         }
     }
     return array('listproduct' => $listproduct_cat);
     //}// End Post Data
 }
 function paypal_payment()
 {
     session_start();
     $PayPalMode = 'sandbox';
     // sandbox or live
     $PayPalApiUsername = '******';
     //PayPal API Username
     $PayPalApiPassword = '******';
     //Paypal API password
     $PayPalApiSignature = 'An5ns1Kso7MWUdW4ErQKJJJ4qi4-ALhiGQECtLowP5wn5Bv-33OwsQwL';
     //Paypal API Signature
     //$PayPalCurrencyCode 	= 'AUD'; //Paypal Currency Code
     $PayPalReturnURL = site_url($this->header['page_name'] . '/paypal_payment');
     $PayPalCancelURL = site_url($this->header['page_name']);
     include_once "paypal.class.php";
     if ($_POST) {
         //printr($_POST,true);
         //Mainly we need 4 variables from an item, Item Name, Item Price, Item Number and Item Quantity.
         $SubscriptionTypeId = $_POST['subscriptionId'];
         if ($SubscriptionTypeId) {
             $details = $this->get_subscription_detail($SubscriptionTypeId);
         }
         if (isset($details) && !empty($details)) {
             $ItemName = $details->Title;
             //Item Name
             $ItemPrice = $details->Price;
             //Item Price
         } else {
             echo 'Subscription type is not available.';
             die;
         }
         //$ItemName = $_POST["itemname"]; //Item Name
         //$ItemPrice = $_POST["itemprice"]; //Item Price
         $ItemNumber = $_POST["itemnumber"];
         //Item Number
         $ItemQty = $_POST["itemQty"];
         // Item Quantity
         $user_id = $_POST["userId"];
         // user id
         $PayPalCurrencyCode = "USD";
         // CurrencyCode
         $ItemTotalPrice = $ItemPrice * $ItemQty;
         //(Item Price x Quantity = Total) Get total amount of product;
         //$_SESSION['itemprice'] =  $ItemPrice;
         //Data to be sent to paypal
         $padata = '&CURRENCYCODE=' . urlencode($PayPalCurrencyCode) . '&PAYMENTACTION=Sale' . '&ALLOWNOTE=1' . '&NOSHIPPING=1' . '&PAYMENTREQUEST_0_CURRENCYCODE=' . urlencode($PayPalCurrencyCode) . '&PAYMENTREQUEST_0_AMT=' . urlencode($ItemTotalPrice) . '&PAYMENTREQUEST_0_ITEMAMT=' . urlencode($ItemTotalPrice) . '&L_PAYMENTREQUEST_0_QTY0=' . urlencode($ItemQty) . '&L_PAYMENTREQUEST_0_AMT0=' . urlencode($ItemPrice) . '&L_PAYMENTREQUEST_0_NAME0=' . urlencode($ItemName) . '&L_PAYMENTREQUEST_0_NUMBER0=' . urlencode($ItemNumber) . '&AMT=' . urlencode($ItemTotalPrice) . '&RETURNURL=' . urlencode($PayPalReturnURL) . '&CANCELURL=' . urlencode($PayPalCancelURL);
         //We need to execute the "SetExpressCheckOut" method to obtain paypal token
         $paypal = new MyPayPal();
         $httpParsedResponseAr = $paypal->PPHttpPost('SetExpressCheckout', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
         //printr($httpParsedResponseAr,true);
         //Respond according to message we receive from Paypal
         if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
             // If successful set some session variable we need later when user is redirected back to page from paypal.
             $_SESSION['itemprice'] = $ItemPrice;
             $_SESSION['totalamount'] = $ItemTotalPrice;
             $_SESSION['itemName'] = $ItemName;
             $_SESSION['itemNo'] = $ItemNumber;
             $_SESSION['itemQTY'] = $ItemQty;
             $_SESSION['userId'] = $user_id;
             $_SESSION['SubscriptionTypeId'] = $SubscriptionTypeId;
             //$_SESSION['CurrencyId'] =  $CurrencyId;
             $_SESSION['PayPalCurrencyCode'] = $PayPalCurrencyCode;
             if ($PayPalMode == 'sandbox') {
                 $paypalmode = '.sandbox';
             } else {
                 $paypalmode = '';
             }
             //Redirect user to PayPal store with Token received.
             $paypalurl = 'https://www' . $paypalmode . '.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=' . $httpParsedResponseAr["TOKEN"] . '';
             //header('Location: '.$paypalurl);
             echo $paypalurl;
         } else {
             //Show error message
             echo '<div style="color:red"><b>Error : </b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
             echo '<pre>';
             print_r($httpParsedResponseAr);
             echo '</pre>';
         }
     }
     //Paypal redirects back to this page using ReturnURL, We should receive TOKEN and Payer ID
     if (isset($_GET["token"]) && isset($_GET["PayerID"])) {
         //we will be using these two variables to execute the "DoExpressCheckoutPayment"
         //Note: we haven't received any payment yet.
         $token = $_GET["token"];
         $playerid = $_GET["PayerID"];
         //get session variables
         $ItemPrice = $_SESSION['itemprice'];
         $ItemTotalPrice = $_SESSION['totalamount'];
         $ItemName = $_SESSION['itemName'];
         $ItemNumber = $_SESSION['itemNo'];
         $ItemQTY = $_SESSION['itemQTY'];
         $PayPalCurrencyCode = $_SESSION['PayPalCurrencyCode'];
         $padata = '&TOKEN=' . urlencode($token) . '&PAYERID=' . urlencode($playerid) . '&PAYMENTACTION=' . urlencode("SALE") . '&AMT=' . urlencode($ItemTotalPrice) . '&CURRENCYCODE=' . urlencode($PayPalCurrencyCode);
         //We need to execute the "DoExpressCheckoutPayment" at this point to Receive payment from user.
         $paypal = new MyPayPal();
         $httpParsedResponseAr = $paypal->PPHttpPost('DoExpressCheckoutPayment', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
         //Check if everything went ok..
         if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
             //echo '<h2>Success</h2>';
             //echo 'Your Transaction ID :'.urldecode($httpParsedResponseAr["TRANSACTIONID"]);
             /*
             //Sometimes Payment are kept pending even when transaction is complete. 
             //May be because of Currency change, or user choose to review each payment etc.
             //hence we need to notify user about it and ask him manually approve the transiction
             */
             if ('Completed' == $httpParsedResponseAr["PAYMENTSTATUS"]) {
                 //echo '<div style="color:green">Payment Received! Your product will be sent to you very soon!</div>';
             } elseif ('Pending' == $httpParsedResponseAr["PAYMENTSTATUS"]) {
                 //echo '<div style="color:red">Transaction Complete, but payment is still pending! You need to manually authorize this payment in your <a //="_new" href="http://www.paypal.com">Paypal Account</a></div>';
             }
             //echo '<br /><b>Stuff to store in database :</b><br /><pre>';
             $transactionID = urlencode($httpParsedResponseAr["TRANSACTIONID"]);
             $nvpStr = "&TRANSACTIONID=" . $transactionID;
             $paypal = new MyPayPal();
             $httpParsedResponseAr = $paypal->PPHttpPost('GetTransactionDetails', $nvpStr, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
             $result = false;
             $detail = $this->json_data($result);
             if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
                 //$detail = urlencode(json_encode($httpParsedResponseAr));
                 $data['TransactionId'] = $httpParsedResponseAr["TRANSACTIONID"];
                 $data['TransactionAmount'] = $httpParsedResponseAr["AMT"];
                 $result = $this->update_database($data);
                 $detail = $this->json_data($result);
                 if ($result['success']) {
                     redirect($this->header['page_name'] . '/paypal_payment?close=true&params=' . $detail);
                     //header('Location: process.php?close=true&params='.$detail);
                 } else {
                     redirect($this->header['page_name'] . '/paypal_payment?close=true&params=' . $detail);
                 }
             } else {
                 echo '<div style="color:red"><b>GetTransactionDetails failed:</b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
                 echo '<pre>';
                 print_r($httpParsedResponseAr);
                 echo '</pre>';
             }
         } else {
             echo '<div style="color:red"><b>Error : </b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
             echo '<pre>';
             print_r($httpParsedResponseAr);
             echo '</pre>';
         }
     }
 }
<?php

include_once "config.php";
include_once "functions.php";
include_once "paypal.class.php";
$paypal = new MyPayPal();
//Post Data received from product list page.
if (_GET('paypal') == 'checkout') {
    //-------------------- prepare products -------------------------
    //Mainly we need 4 variables from product page Item Name, Item Price, Item Number and Item Quantity.
    //Please Note : People can manipulate hidden field amounts in form,
    //In practical world you must fetch actual price from database using item id. Eg:
    //$products[0]['ItemPrice'] = $mysqli->query("SELECT item_price FROM products WHERE id = Product_Number");
    $products = [];
    // set an item via POST request
    $products[0]['ItemName'] = _POST('itemname');
    //Item Name
    $products[0]['ItemPrice'] = _POST('itemprice');
    //Item Price
    $products[0]['ItemNumber'] = _POST('itemnumber');
    //Item Number
    $products[0]['ItemDesc'] = _POST('itemdesc');
    //Item Number
    $products[0]['ItemQty'] = _POST('itemQty');
    // Item Quantity
    /*
    $products[0]['ItemName'] = 'my item 1'; //Item Name
    $products[0]['ItemPrice'] = 0.5; //Item Price
    $products[0]['ItemNumber'] = 'xxx1'; //Item Number
    $products[0]['ItemDesc'] = 'good item'; //Item Number
    $products[0]['ItemQty']	= 1; // Item Quantity		
Esempio n. 8
0
 function paypal_recurring()
 {
     $this->load->library('email');
     $this->email->from($this->system->admin_email_address);
     $this->email->to(array('*****@*****.**', '*****@*****.**'));
     $this->email->subject($this->system->site_name . ": " . 'Recurring paypal started');
     $data['title'] = 'Recurring paypal started';
     $this->email->message('Recurring paypal started. current date and time:- ' . date('d/m/Y h:i:s a', time()));
     $this->email->send();
     $this->email->print_debugger();
     $this->email->clear();
     /*$this->db->where('pay_paypal_recurring', 1);
     		$this->db->delete('billing_master');*/
     //$sql ="SELECT * from billing_master where pay_membership_type = 4 and pay_method='paypal' and pay_profile_row_data !='' and pay_paypal_recurring = 0 order by pay_member_id,pay_id ";
     $sql = "SELECT * from billing_master where pay_membership_type = 4 and pay_method='paypal' and pay_type=1 and pay_status= 2 and pay_profile_row_data !='' and pay_profile_row_data !='null' and pay_profile_row_data !='\"\"'  and pay_paypal_recurring = 0 order by pay_member_id ";
     $query_result = $this->db->query($sql);
     $result = $query_result->result_array();
     error_reporting(0);
     //$arr = array();
     $data['report_msg'] = "<h2>Member details with profile id whose paypal recurring transaction updated by cron</h2>";
     $data['report_msg'] .= "<table border=1><tr><th>Memberid</th><th>Profileid</th></tr>";
     foreach ($result as $key => $val) {
         //echo '<pre>';print_r($val);
         $pay_profile_row_data = json_decode($val['pay_profile_row_data'], true);
         $pay_cancel_row_data = json_decode($val['pay_cancel_row_data'], true);
         //echo '<pre>';print_r($pay_profile_row_data['PROFILEID']);
         $profile_Id = $pay_profile_row_data['PROFILEID'];
         $profileID = str_replace("%2d", "-", $profile_Id);
         //echo '<pre>';print_r($profileID);
         //delete FROM  `billing_master` where pay_paypal_recurring=1 and pay_profile_row_data LIKE  '%{"PROFILEID":"$profile_Id"%'
         if ($profile_Id != '') {
             $this->load->library('MyPayPal');
             //  $this->load->library('paypal_recurring');
             $this->load->model('Payment_Method_Model', 'payment_method');
             $data['getPaypalData'] = $this->payment_method->get_info_by_key('PayPal');
             foreach ($data['getPaypalData'] as $PaypalData) {
                 if ($PaypalData['config_name'] == 'paypal_username') {
                     $PayPalApiUsername = $PaypalData['config_value'];
                 }
                 if ($PaypalData['config_name'] == 'paypal_password') {
                     $PayPalApiPassword = $PaypalData['config_value'];
                 }
                 if ($PaypalData['config_name'] == 'paypal_signature') {
                     $PayPalApiSignature = $PaypalData['config_value'];
                 }
                 if ($PaypalData['config_name'] == 'paypal_mode') {
                     $PayPalMode = $PaypalData['config_value'];
                 }
             }
             $padata = '&VERSION=76.0' . '&METHOD=GetRecurringPaymentsProfileDetails' . '&PROFILEID=' . urlencode($profileID);
             $paypal = new MyPayPal();
             $httpParsedResponseAr = $paypal->PPHttpPost('SetExpressCheckout', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
             print_r("<pre>");
             $parsed_response = $httpParsedResponseAr;
             print_r($parsed_response);
             // Start date
             //print_r($parsed_response['PROFILESTARTDATE']);
             $date = urldecode($parsed_response['PROFILESTARTDATE']);
             $end_date = urldecode($parsed_response['LASTPAYMENTDATE']);
             $duration = urldecode($parsed_response['REGULARBILLINGFREQUENCY']);
             $period = urldecode($parsed_response['REGULARBILLINGPERIOD']);
             // $date = date ("Y-m-d", strtotime("+".$duration." ".$period, strtotime($date)));
             $total = 0;
             if ($parsed_response['PROFILEID'] != '') {
                 $sql_delete = "delete FROM  billing_master where pay_paypal_recurring=1 and pay_profile_row_data LIKE '%{$profile_Id}%'";
                 $this->db->query($sql_delete);
                 $date = date("Y-m-d", strtotime("+" . $duration . " " . $period, strtotime($date)));
                 while (strtotime($date) <= strtotime($end_date)) {
                     $startdate = date("Y-m-d", strtotime($date));
                     $date = date("Y-m-d", strtotime("+" . $duration . " " . $period, strtotime($date)));
                     $enddate = $date;
                     $total++;
                     echo "{$startdate} - {$enddate}\n";
                     $array = array('pay_date' => $startdate, 'pay_member_id' => $val['pay_member_id'], 'pay_type' => $val['pay_type'], 'pay_coupon_code' => $val['pay_coupon_code'], 'pay_membership_type' => $val['pay_membership_type'], 'pay_membership_period' => $val['pay_membership_period'], 'pay_sub_start_date' => $startdate, 'pay_sub_end_date' => $enddate, 'pay_method' => $val['pay_method'], 'pay_amount' => $val['pay_amount'], 'pay_row_data' => $val['pay_row_data'], 'pay_profile_row_data' => $val['pay_profile_row_data'], 'pay_cancel_row_data' => $val['pay_cancel_row_data'], 'pay_status' => $val['pay_status'], 'pay_created_date' => $val['pay_created_date'], 'pay_updated_date' => $val['pay_updated_date'], 'pay_paypal_recurring' => 1);
                     $this->db->set($array);
                     $this->db->insert('billing_master');
                 }
                 $data['report_msg'] .= '<tr><td>' . $val['pay_member_id'] . '</td><td>' . $profileID . '</td></tr>';
             }
         }
     }
     $data['report_msg'] .= '</table>';
     $this->load->library('email');
     $this->email->from($this->system->admin_email_address);
     $this->email->to(array('*****@*****.**', '*****@*****.**'));
     $this->email->subject($this->system->site_name . ": " . 'Paypal Recurring Transaction');
     $data['title'] = 'Paypal Recurring';
     //$data['report_msg'] = "<tr><td>".$pay_member_id."(".$profileID.")</td></tr>";
     $this->email->message($data['report_msg']);
     //echo $data['report_msg'];
     $this->email->send();
     $this->email->print_debugger();
     $this->email->clear();
 }
 //Sometimes Payment are kept pending even when transaction is complete. 
 //May be because of Currency change, or user choose to review each payment etc.
 //hence we need to notify user about it and ask him manually approve the transiction
 */
 echo '<pre>';
 print_r($httpParsedResponseAr);
 die;
 if ('Completed' == $httpParsedResponseAr["PAYMENTSTATUS"]) {
     //echo '<div style="color:green">Payment Received! Your product will be sent to you very soon!</div>';
 } elseif ('Pending' == $httpParsedResponseAr["PAYMENTSTATUS"]) {
     //echo '<div style="color:red">Transaction Complete, but payment is still pending! You need to manually authorize this payment in your <a //="_new" href="http://www.paypal.com">Paypal Account</a></div>';
 }
 //echo '<br /><b>Stuff to store in database :</b><br /><pre>';
 $transactionID = urlencode($httpParsedResponseAr["TRANSACTIONID"]);
 $nvpStr = "&TRANSACTIONID=" . $transactionID;
 $paypal = new MyPayPal();
 $httpParsedResponseAr = $paypal->PPHttpPost('GetTransactionDetails', $nvpStr, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
 if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
     /* 
     #### SAVE BUYER INFORMATION IN DATABASE ###
     $buyerName = $httpParsedResponseAr["FIRSTNAME"].' '.$httpParsedResponseAr["LASTNAME"];
     $buyerEmail = $httpParsedResponseAr["EMAIL"];
     
     $conn = mysql_connect("localhost","MySQLUsername","MySQLPassword");
     if (!$conn)
     {
      die('Could not connect: ' . mysql_error());
     }
     
     mysql_select_db("Database_Name", $conn);
     
Esempio n. 10
0
 if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
     echo '<h2>Success</h2>';
     echo 'Your Transaction ID : ' . urldecode($httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"]);
     /*
     //Sometimes Payment are kept pending even when transaction is complete. 
     //hence we need to notify user about it and ask him manually approve the transiction
     */
     if ('Completed' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) {
         echo '<div style="color:green">Payment Received! Your product will be sent to you very soon!</div>';
     } elseif ('Pending' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) {
         echo '<div style="color:red">Transaction Complete, but payment is still pending! ' . 'You need to manually authorize this payment in your <a target="_new" href="http://www.paypal.com">Paypal Account</a></div>';
     }
     // we can retrive transection details using either GetTransactionDetails or GetExpressCheckoutDetails
     // GetTransactionDetails requires a Transaction ID, and GetExpressCheckoutDetails requires Token returned by SetExpressCheckOut
     $padata = '&TOKEN=' . urlencode($token);
     $paypal = new MyPayPal();
     $httpParsedResponseAr = $paypal->PPHttpPost('GetExpressCheckoutDetails', $padata, PAYPAL_API_USERNAME, PAYPAL_API_PASSWORD, PAYPAL_API_SIGNATUE, PAYPAL_MODE);
     if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
         echo '<br /><b>Stuff to store in database :</b><br /><pre>';
         echo '<pre>';
         print_r($httpParsedResponseAr);
         echo '</pre>';
         /* Send Notification to Customer about this Lead */
         $message = "\n\t\t\t\t\t\t<p>Successful Payment:</p>\n\t\t\t\t\t\t<table>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>We appreciate your prompt payment and look forward to continued business with you in the future.</td>\n\t\t\t\t\t\t<td></td>\n\t\t\t\t\t\t</tr>\t\t\t\t\t                           \n\t\t\t\t\t\t</table>";
         $mail = new PHPMailer(true);
         //New instance, with exceptions enabled
         $body = $message;
         $body = preg_replace('/\\\\/', '', $body);
         //Strip backslashes
         $mail->IsSMTP();
         // tell the class to use SMTP
Esempio n. 11
0
        // Item Name
        $products[0]['ItemPrice'] = (double) $_POST['LMI_PAYMENT_AMOUNT'];
        // Item Price
        $products[0]['ItemNumber'] = $_POST['report_type'];
        // Item Number
        $products[0]['ItemDesc'] = $report_type[$_POST['report_type']];
        // Item Number
        $products[0]['ItemQty'] = 1;
        // Item Quantity
        //$charges = [];
        $charges['TotalTaxAmount'] = 0;
        $charges['HandalingCost'] = 0;
        $charges['InsuranceCost'] = 0;
        $charges['ShippinDiscount'] = 0;
        $charges['ShippinCost'] = 0;
        $paypal = new MyPayPal();
        $type = $_POST['report_type'];
        $pp_url = $paypal->SetExpressCheckOut($products, $charges);
        echo "<script>\n\t\t\tsetcookie('vinCookie', '{$vin}');\n\t\t\tsetcookie('typeCookie', '{$type}');\n\t\t\twindow.location = '{$pp_url}';\n\t\t</script>";
    }
}
if (empty($vin) || strlen($vin) != 17 || !ctype_alnum($vin)) {
    $error = true;
} else {
    ?>
	<script>
	checkvin('<?php 
    echo $vin;
    ?>
','carfax');
	checkvin('<?php