Showing posts with label Magento. Show all posts
Showing posts with label Magento. Show all posts
Magento sales order after save ( sales_order_save_after )

Magento sales order after save ( sales_order_save_after )

<?php
class Pixel_Beforeorder_Model_Observer extends Varien_Event_Observer{

    /*
    ** Before save the product user id should be update for current product
    */
    public function beforeSaveOrder($observer){
        $session = Mage::getSingleton('checkout/session');
        foreach ($session->getQuote()->getAllItems() as $item) {
            $id = $item->getId();
            $resource = Mage::getSingleton('core/resource');
            $writeConnection = $resource->getConnection('core_write');
            $query = "UPDATE sales_flat_quote_item SET act = 0 WHERE item_id = $id";
            $writeConnection->query($query);
        }
    }

}
?>







<?xml version="1.0"?>
<config>
    <modules>
        <Pixel_Beforeorder>
            <version>1.0.0</version>
        </Pixel_Beforeorder>
    </modules>
    <global>
         <models>
            <pixel_beforeorder>
                 <class>Pixel_Beforeorder_Model</class>
            </pixel_beforeorder>
        </models>
        <events>
            <sales_order_save_after>
                <observers>
                    <pixel_beforeorder>
                        <type>singleton</type>
                        <class>pixel_beforeorder/observer</class>
                        <method>beforeSaveOrder</method>
                    </pixel_beforeorder>
                </observers>
            </sales_order_save_after>
        </events>
    </global>
</config>
magento paypal chained payment or adaptive payment

magento paypal chained payment or adaptive payment

magento paypal chained payment or adaptive payment


<?php
class Pixel_Paypalpayment_Block_Standard_Redirect extends Mage_Core_Block_Abstract
{
    protected function _toHtml()
    {
        $standard                           =   Mage::getModel('paypalpayment/standard');
        $form                               =   new Varien_Data_Form();

        $trans = $standard->getStandardCheckoutFormFields();
       
        $orders = Mage::getModel('sales/order')->loadByIncrementId($trans['Notes']);
        $marging_percent                    =   Mage::getStoreconfig('payment/paypalpayment_standard/margin_ammount');
        $marging_ammount                    =   ($orders->getBaseSubtotal() * $marging_percent)/100;
        foreach ($orders->getAllItems() as $items)
        {
                $_product                   =   Mage::getSingleton('catalog/product')->load($items->getProductId());
                $vendorid                   =   $_product->getVendorid();
        }
        $vendormodel                        =   Mage::getModel('vendorpayment/vendorpayment')->load($vendorid);
        $primary_seller                     =   $vendormodel->getEmail();
        $secondary_seller                   =   Mage::getStoreconfig('payment/paypalpayment_standard/merchant_email');
        $buyer_email                        =   $trans['CustomerEmail'];
        $total_amount                       =   $trans['TransactionAmount'];
        $sandbox                            =   Mage::getStoreconfig('payment/paypalpayment_standard/sandbox');
        $actionType                            =   "PAY";
        $cancelUrl                            =   $trans['RedirectorFailed'];
        $returnUrl                            =   $trans['RedirectorSuccess'];   
        $currencyCode                        =   "USD";
        $receiverEmailArray                    =   array($primary_seller, $secondary_seller);
        $receiverAmountArray                =   array($total_amount, $marging_ammount);
        $receiverPrimaryArray               =   array('true');
        $receiverInvoiceIdArray             =   array('','');
        $senderEmail                        =   $buyer_email;
        $feesPayer                            =   "PRIMARYRECEIVER";
        $ipnNotificationUrl                    =   "";
        $memo                                =   "";       
        $pin                                =   "";       
        $preapprovalKey                        =   "";       
        $reverseAllParallelPaymentsOnError    =   "";   
        $trackingId                            =   Mage :: helper ('paypalpayment')->generateTrackingID();
        $resArray                           =   Mage::helper('paypalpayment')->CallPay($actionType, $cancelUrl, $returnUrl, $currencyCode,
                                                $receiverEmailArray,$receiverAmountArray, $receiverPrimaryArray, $receiverInvoiceIdArray,$feesPayer,
                                                $ipnNotificationUrl, $memo, $pin, $preapprovalKey, $reverseAllParallelPaymentsOnError, $senderEmail,
                                                $trackingId);
                                               
        $cmd                                =   "cmd=_ap-payment&paykey=".urldecode($resArray["payKey"]);
     
        $payPalURL                          =   "";
        if ($sandbox == 1)
        {
            $payPalURL                      =   "https://www.sandbox.paypal.com/webscr?" . $cmd;
        }
        else
        {
            $payPalURL                      =   "https://www.paypal.com/webscr?" . $cmd;
        }
       
        $form->setAction($payPalURL)
        ->setId('paypalpayment_standard_checkout')
        ->setName('paypalpayment_standard_checkout')
        ->setMethod('POST')
        ->setUseContainer(true);
        $html                               =   '<html><body>';
        $html                              .=   $this->__('You will be redirected to Paypal in a few seconds.');
        $html                              .=   $form-> toHtml();
        $html                              .=   '<script type="text/javascript">document.getElementById("paypalpayment_standard_checkout").submit();
                                                </script>';
        $html                              .=   '</body></html>';
        return $html;
    }
}
Magento paypal chained payment Adaptive payment

Magento paypal chained payment Adaptive payment

Magento paypal chained payment (Adaptive payment)

Data.php

<?php

class Pixel_Paypalpayment_Helper_Data extends Mage_Core_Helper_Abstract
{

    public $Env;
    public $API_UserName ;
    public $API_Password ;
    public $API_Signature;
    public $API_AppID = "APP-80W284485P519543T";
    public $API_Endpoint = "";
    public $USE_PROXY;
    public $PROXY_HOST;
    public $PROXY_PORT;
   
   
    public function __construct()
    {     
         /* $this->API_UserName  =   $vendormodel->getApiusername();  
          $this->API_Password =$vendormodel->getApipassword(); 
          $this->API_Signature = $vendormodel->getApisignature(); 
          $this->Env = $vendormodel->getSandbox();
           
        if ($this->Env == 1) 
        {
            $this->API_Endpoint = "https://svcs.sandbox.paypal.com/AdaptivePayments";
        }
        else
        {
            $this->API_Endpoint = "https://svcs.paypal.com/AdaptivePayments";
        }

        $this->USE_PROXY = false;*/

        if (session_id() == "") 
            session_start();
    }   

    function generateCharacter () {
        $possible = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
        return $char;
    }

    function generateTrackingID () {
       
        $GUID = $this->generateCharacter().$this->generateCharacter().$this->generateCharacter().$this->generateCharacter().$this->generateCharacter();
        $GUID .= $this->generateCharacter().$this->generateCharacter().$this->generateCharacter().$this->generateCharacter();
        return $GUID;
       
    }

    function CallRefund( $payKey, $transactionId, $trackingId, $receiverEmailArray, $receiverAmountArray )
    {
       
        $nvpstr = "";
        if ("" != $payKey)
        {
            $nvpstr = "payKey=" . $this->urlencode($payKey);
            if (0 != count($receiverEmailArray))
            {
                reset($receiverEmailArray);
                while (list($key, $value) = each($receiverEmailArray))
                {
                    if ("" != $value)
                    {
                        $nvpstr .= "&receiverList.receiver(" . $key . ").email=" . urlencode($value);
                    }
                }
            }
            if (0 != count($receiverAmountArray))
            {
                reset($receiverAmountArray);
                while (list($key, $value) = each($receiverAmountArray))
                {
                    if ("" != $value)
                    {
                        $nvpstr .= "&receiverList.receiver(" . $key . ").amount=" . urlencode($value);
                    }
                }
            }
        }
        elseif ("" != $trackingId)
        {
            $nvpstr = "trackingId=" . urlencode($trackingId);
            if (0 != count($receiverEmailArray))
            {
                reset($receiverEmailArray);
                while (list($key, $value) = each($receiverEmailArray))
                {
                    if ("" != $value)
                    {
                        $nvpstr .= "&receiverList.receiver(" . $key . ").email=" . urlencode($value);
                    }
                }
            }
            if (0 != count($receiverAmountArray))
            {
                reset($receiverAmountArray);
                while (list($key, $value) = each($receiverAmountArray))
                {
                    if ("" != $value)
                    {
                        $nvpstr .= "&receiverList.receiver(" . $key . ").amount=" . urlencode($value);
                    }
                }
            }
        }
        elseif ("" != $transactionId)
        {
            $nvpstr = "transactionId=" . urlencode($transactionId);
            // the caller should only have 1 entry in the email and amount arrays
            if (0 != count($receiverEmailArray))
            {
                reset($receiverEmailArray);
                while (list($key, $value) = each($receiverEmailArray))
                {
                    if ("" != $value)
                    {
                        $nvpstr .= "&receiverList.receiver(" . $key . ").email=" . urlencode($value);
                    }
                }
            }
            if (0 != count($receiverAmountArray))
            {
                reset($receiverAmountArray);
                while (list($key, $value) = each($receiverAmountArray))
                {
                    if ("" != $value)
                    {
                        $nvpstr .= "&receiverList.receiver(" . $key . ").amount=" . urlencode($value);
                    }
                }
            }
        }

        /* Make the Refund call to PayPal */
        $resArray = $this->hash_call("Refund", $nvpstr);

        /* Return the response array */
        return $resArray;
    }
   
    function CallPaymentDetails( $payKey, $transactionId, $trackingId )
    {
        /* Gather the information to make the PaymentDetails call.
            The variable nvpstr holds the name value pairs
        */
       
        $nvpstr = "";
       
        // conditionally required fields
        if ("" != $payKey)
        {
            $nvpstr = "payKey=" . $this->urlencode($payKey);
        }
        elseif ("" != $transactionId)
        {
            $nvpstr = "transactionId=" . $this->urlencode($transactionId);
        }
        elseif ("" != $trackingId)
        {
            $nvpstr = "trackingId=" . $this->urlencode($trackingId);
        }

        /* Make the PaymentDetails call to PayPal */
        $resArray = $this->hash_call("PaymentDetails", $nvpstr);

        /* Return the response array */
        return $resArray;
    }

    function CallPay( $actionType, $cancelUrl, $returnUrl, $currencyCode, $receiverEmailArray, $receiverAmountArray,
                        $receiverPrimaryArray, $receiverInvoiceIdArray, $feesPayer, $ipnNotificationUrl,
                        $memo, $pin, $preapprovalKey, $reverseAllParallelPaymentsOnError, $senderEmail, $trackingId )
    {
        /* Gather the information to make the Pay call.
            The variable nvpstr holds the name value pairs
        */
        $standard  =   Mage::getModel('paypalpayment/standard');
        $trans = $standard->getStandardCheckoutFormFields();
         $productId = Mage::app()->getRequest()->getParam('id');
         $_product= Mage::getSingleton('catalog/product')->load($productId);
         $pro=$_product['vendorid'];
         $vendor_model=Mage::getModel('vendorpayment/vendorpayment')->load($pro,'user_vendor');
         $this->API_UserName = $vendor_model->getApiusername();
         $this->API_Password = $vendor_model->getApipassword();
         $this->API_Signature = $vendor_model->getApisignature();
         $Env = $this->Env = 'sandbox';
         
         $ItemName= $_product['name'];
         $ItemNumber=$_product['sku'];
         $ItemQty = 1;
         $ItemPrice=$_product['price'];
         $PayPalReturnURL= $trans['RedirectorSuccess'];
         $PayPalCancelURL= $trans['RedirectorFailed'];
         
        $orderId = Mage::getSingleton('checkout/session')->getLastOrderId();
        $order = Mage::getModel('sales/order')->load($orderId);
        $items = $order->getAllItems();
        $itemcount=count($items);
        $totalItems = Mage::getModel('checkout/cart')->getQuote()->getItemsCount();
        $shipping_amt= $order->getData('shipping_amount');
        $name=array();
        $unitPrice=array();
        $sku=array();
        $ids=array();
        $price = 0;
        $qty=array();
            foreach ($items as $itemId => $item)
            {   
               $name[] = $item->getName();
               $unitPrice[]=$item->getPrice();
               $sku[]=$item->getSku();
               $ids[]=$item->getProductId();
               $qty[]=$item->getQtyToInvoice();
               //$singleitem= $unitPrice * $qty;
               $items_summary .= 
                '&L_PAYMENTREQUEST_0_QTY'.$itemId.'='.urlencode( $item->getQtyToInvoice() ).
                '&L_PAYMENTREQUEST_0_AMT'.$itemId.'='.urlencode( (float)$item->getPrice() ).
                '&L_PAYMENTREQUEST_0_NAME'.$itemId.'='.urlencode( $item->getName() ).
                '&L_PAYMENTREQUEST_0_NUMBER'.$itemId.'='.urlencode( $item->getSku() );
              $price += $item->getQtyToInvoice() * $item->getPrice();
              //$new[] = $price;
               
            }
      // print_r($price);
       //exit;
       
        $totalQuantity = Mage::getModel('checkout/cart')->getQuote()->getItemsQty();        
        $subTotal = Mage::getModel('checkout/cart')->getQuote()->getSubtotal();       
        $grandTotal = Mage::getModel('checkout/cart')->getQuote()->getGrandTotal();
        
        
        //print_r($grandTotal);exit;
         //$ItemTotalPrice = $grandTotal;
         //print_r($totalQuantity);exit;
          $PayPalCurrencyCode="USD";
        echo $nvpStr = $padata =   
                  '&CURRENCYCODE='.urlencode($PayPalCurrencyCode).
                '&PAYMENTACTION=Sale'.
                '&ALLOWNOTE=1'.
                '&PAYMENTREQUEST_0_SHIPPINGAMT='.urlencode((float)$shipping_amt).
                '&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($PayPalCurrencyCode).
                '&PAYMENTREQUEST_0_AMT='.urlencode((float)$grandTotal).
                '&PAYMENTREQUEST_0_ITEMAMT='.urlencode((float)$subTotal). 
                $items_summary.
                '&AMT='.urlencode((float)$grandTotal).
                '&RETURNURL='.urlencode($PayPalReturnURL ).
                '&CANCELURL='.urlencode($PayPalCancelURL);
         //print_r($ItemTotalPrice);exit;
       
         
         
         
       

    /*     $nvpStr = $padata =   '&CURRENCYCODE='.urlencode($PayPalCurrencyCode).
                '&PAYMENTACTION=Sale'.
                '&ALLOWNOTE=1'.
                '&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($PayPalCurrencyCode).
                '&PAYMENTREQUEST_0_AMT='.urlencode('300').
                '&PAYMENTREQUEST_0_ITEMAMT='.urlencode('300').
                '&L_PAYMENTREQUEST_0_QTY0='. urlencode('1').
                '&L_PAYMENTREQUEST_0_AMT0='.urlencode('100').
                '&L_PAYMENTREQUEST_0_NAME0='.urlencode($ItemName).
                '&L_PAYMENTREQUEST_0_NUMBER0='.urlencode($ItemNumber).
                '&L_PAYMENTREQUEST_0_QTY1='. urlencode('1').
                '&L_PAYMENTREQUEST_0_AMT1='.urlencode('200').
                '&L_PAYMENTREQUEST_0_NAME1='.urlencode('Test 1').
                '&L_PAYMENTREQUEST_0_NUMBER1='.urlencode('2').
                '&AMT='.urlencode('300').
                '&RETURNURL='.urlencode($PayPalReturnURL).
                '&CANCELURL='.urlencode($PayPalCancelURL);
        //print_r($nvpStr);exit;*/
        $httpParsedResponseAr = $this->PPHttpPost('SetExpressCheckout', $nvpStr,$this->API_UserName ,$this->API_Password,$this->API_Signature,$Env);
        //print_r($httpParsedResponseAr);exit;
        if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
    // Redirect to paypal.com.
    $token = urldecode($httpParsedResponseAr["TOKEN"]);
    echo $payPalURL = "https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=$token";
   
    if("sandbox" === $Env || "beta-sandbox" === $Env) {
        $payPalURL = "https://www.$Env.paypal.com/webscr&cmd=_express-checkout&token=$token";
    }
    header("Location: $payPalURL");
    exit;
} else  {
    exit('SetExpressCheckout failed: ' . print_r($httpParsedResponseAr, true));
}   

       
        // required fields
       
        $nvpstr = 'actionType=' . urlencode($actionType);
       
        $nvpstr .= '&currencyCode=' . urlencode($currencyCode);
        $nvpstr .= "&returnUrl=" . urlencode($returnUrl) . "&cancelUrl=" . urlencode($cancelUrl);
       
        if (0 != count($receiverAmountArray))
        {
            reset($receiverAmountArray);
            while (list($key, $value) = each($receiverAmountArray))
            {
                if ("" != $value)
                {
                    $nvpstr .= "&receiverList.receiver(" . $key . ").amount=" . urlencode($value);
                }
            }
        }

        if (0 != count($receiverEmailArray))
        {
            reset($receiverEmailArray);
            while (list($key, $value) = each($receiverEmailArray))
            {
                if ("" != $value)
                {
                    $nvpstr .= "&receiverList.receiver(" . $key . ").email=" . urlencode($value);
                }
            }
        }

        if (0 != count($receiverPrimaryArray))
        {
            reset($receiverPrimaryArray);
            while (list($key, $value) = each($receiverPrimaryArray))
            {
                if ("" != $value)
                {
                    $nvpstr = $nvpstr . "&receiverList.receiver(" . $key . ").primary=" . urlencode($value);
                }
            }
        }

        if (0 != count($receiverInvoiceIdArray))
        {
            reset($receiverInvoiceIdArray);
            while (list($key, $value) = each($receiverInvoiceIdArray))
            {
                if ("" != $value)
                {
                    $nvpstr = $nvpstr . "&receiverList.receiver(" . $key . ").invoiceId=" . urlencode($value);
                }
            }
        }
   
        // optional fields
        if ("" != $feesPayer)
        {
            $nvpstr .= "&feesPayer=" . urlencode($feesPayer);
        }

        if ("" != $ipnNotificationUrl)
        {
            $nvpstr .= "&ipnNotificationUrl=" . urlencode($ipnNotificationUrl);
        }

        if ("" != $memo)
        {
            $nvpstr .= "&memo=" . urlencode($memo);
        }

        if ("" != $pin)
        {
            $nvpstr .= "&pin=" . urlencode($pin);
        }

        if ("" != $preapprovalKey)
        {
            $nvpstr .= "&preapprovalKey=" . urlencode($preapprovalKey);
        }

        if ("" != $reverseAllParallelPaymentsOnError)
        {
            $nvpstr .= "&reverseAllParallelPaymentsOnError=" . urlencode($reverseAllParallelPaymentsOnError);
        }

        if ("" != $senderEmail)
        {
            $nvpstr .= "&senderEmail=" . urlencode($senderEmail);
        }

        if ("" != $trackingId)
        {
            $nvpstr .= "&trackingId=" . urlencode($trackingId);
        }

       
       
       
        /* Make the Pay call to PayPal */
        $resArray = $this->hash_call("Pay", $nvpstr);
        /* Return the response array */
        return $resArray;
    }

    /*
    '-------------------------------------------------------------------------------------------------------------------------------------------
    ' Purpose:     Prepares the parameters for the PreapprovalDetails API Call.
    ' Inputs:
    '
    ' Required:
    '        preapprovalKey:        A preapproval key that identifies the agreement resulting from a previously successful Preapproval call.
    ' Returns: 
    '        The NVP Collection object of the PreapprovalDetails call response.
    '--------------------------------------------------------------------------------------------------------------------------------------------   
    */
    function CallPreapprovalDetails( $preapprovalKey )
    {
        /* Gather the information to make the PreapprovalDetails call.
            The variable nvpstr holds the name value pairs

        */
       
        // required fields
        $nvpstr = "preapprovalKey=" . urlencode($preapprovalKey);

        /* Make the PreapprovalDetails call to PayPal */
        $resArray = hash_call("PreapprovalDetails", $nvpstr);

        /* Return the response array */
        return $resArray;
    }
   
    /*
    '-------------------------------------------------------------------------------------------------------------------------------------------
    ' Purpose:     Prepares the parameters for the Preapproval API Call.
    ' Inputs:
    '
    ' Required:
    '
    ' Optional:
    '
    '       
    ' Returns: 
    '        The NVP Collection object of the Preapproval call response.
    '--------------------------------------------------------------------------------------------------------------------------------------------   
    */
    function CallPreapproval( $returnUrl, $cancelUrl, $currencyCode, $startingDate, $endingDate, $maxTotalAmountOfAllPayments,
                                $senderEmail, $maxNumberOfPayments, $paymentPeriod, $dateOfMonth, $dayOfWeek,
                                $maxAmountPerPayment, $maxNumberOfPaymentsPerPeriod, $pinType )
    {
        /* Gather the information to make the Preapproval call.
            The variable nvpstr holds the name value pairs
        */
       
        // required fields
        $nvpstr = "returnUrl=" . urlencode($returnUrl) . "&cancelUrl=" . urlencode($cancelUrl);
        $nvpstr .= "&currencyCode=" . urlencode($currencyCode) . "&startingDate=" . urlencode($startingDate);
        $nvpstr .= "&endingDate=" . urlencode($endingDate);
        $nvpstr .= "&maxTotalAmountOfAllPayments=" . urlencode($maxTotalAmountOfAllPayments);
       
        // optional fields
        if ("" != $senderEmail)
        {
            $nvpstr .= "&senderEmail=" . urlencode($senderEmail);
        }

        if ("" != $maxNumberOfPayments){
            $nvpstr .= "&maxNumberOfPayments=" . urlencode($maxNumberOfPayments);
        }
       
        if ("" != $paymentPeriod){
            $nvpstr .= "&paymentPeriod=" . urlencode($paymentPeriod);
        }

        if ("" != $dateOfMonth){
            $nvpstr .= "&dateOfMonth=" . urlencode($dateOfMonth);
        }

        if ("" != $dayOfWeek)
        {
            $nvpstr .= "&dayOfWeek=" . urlencode($dayOfWeek);
        }

        if ("" != $maxAmountPerPayment)
        {
            $nvpstr .= "&maxAmountPerPayment=" . urlencode($maxAmountPerPayment);
        }

        if ("" != $maxNumberOfPaymentsPerPeriod)
        {
            $nvpstr .= "&maxNumberOfPaymentsPerPeriod=" . urlencode($maxNumberOfPaymentsPerPeriod);
        }

        if ("" != $pinType)
        {
            $nvpstr .= "&pinType=" . urlencode($pinType);
        }
   
        /* Make the Preapproval call to PayPal */
        $resArray = hash_call("Preapproval", $nvpstr);

        /* Return the response array */
        return $resArray;
    }

    /**
      '-------------------------------------------------------------------------------------------------------------------------------------------
      * hash_call: Function to perform the API call to PayPal using API signature
      * @methodName is name of API method.
      * @nvpStr is nvp string.
      * returns an associative array containing the response from the server.
      '-------------------------------------------------------------------------------------------------------------------------------------------
    */
    //function hash_call($methodName, $nvpStr)
    function hash_call($methodName_, $nvpStr_) {

            //global $Env;
           
            // Set up your API credentials, PayPal end point, and API version.
            $this->API_Endpoint .= "/" . $methodName;
           
            // Set the curl parameters.
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
            curl_setopt($ch, CURLOPT_VERBOSE, 1);
       
            // Turn off the server and peer verification (TrustManager Concept).
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
       
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$request);
            curl_setopt($ch, CURLOPT_HTTPHEADER,  array(
                'X-PAYPAL-REQUEST-DATA-FORMAT: NV',
                'X-PAYPAL-RESPONSE-DATA-FORMAT: NV',
                'X-PAYPAL-SECURITY-USERID: ' . $this->API_UserName,
                'X-PAYPAL-SECURITY-PASSWORD: ' .$this->API_Password,
                'X-PAYPAL-SECURITY-SIGNATURE: ' . $this->API_Signature,
                'X-PAYPAL-SERVICE-VERSION: 1.3.0',
                'X-PAYPAL-APPLICATION-ID: ' . $this->API_AppID
                ));
            if($USE_PROXY)
            curl_setopt ($ch, CURLOPT_PROXY, $PROXY_HOST. ":" . $PROXY_PORT); 

        // RequestEnvelope fields
        $detailLevel    = urlencode("ReturnAll");    // See DetailLevelCode in the WSDL for valid enumerations
        $errorLanguage    = urlencode("en_US");        // This should be the standard RFC 3066 language identification tag, e.g., en_US

        // NVPRequest for submitting to server
        $nvpreq = "requestEnvelope.errorLanguage=$errorLanguage&requestEnvelope.detailLevel=$detailLevel";
        $nvpreq .= "&$nvpStr";



        //setting the nvpreq as POST FIELD to curl
        curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

        //getting response from server
        $response = curl_exec($ch);

        //converting NVPResponse to an Associative Array
        $nvpResArray=$this->deformatNVP($response);
       
        $nvpReqArray=$this->deformatNVP($nvpreq);
        $_SESSION['nvpReqArray']=$nvpReqArray;

        if (curl_errno($ch)) 
        {
            // moving to display page to display curl errors
        echo      $_SESSION['curl_error_no']=curl_errno($ch) ;
        echo      $_SESSION['curl_error_msg']=curl_error($ch);

              //Execute the Error handling module to display errors. 
        } 
        else 
        {
             //closing the curl
              curl_close($ch);
        }
        return $nvpResArray;
    }

    function RedirectToPayPal ( $cmd )
    {
        // Redirect to paypal.com here
        global $Env;

        $payPalURL = "";
       
        if ($Env == "sandbox") 
        {
            $payPalURL = "https://www.sandbox.paypal.com/webscr?" . $cmd;
        }
        else
        {
            $payPalURL = "https://www.paypal.com/webscr?" . $cmd;
        }

        header("Location: ".$payPalURL);
    }   
   
    /*'----------------------------------------------------------------------------------
     * This function will take NVPString and convert it to an Associative Array and it will decode the response.
      * It is usefull to search for a particular key and displaying arrays.
      * @nvpstr is NVPString.
      * @nvpArray is Associative Array.
       ----------------------------------------------------------------------------------
      */
    function deformatNVP($nvpstr)
    {
   
   
        $intial=0;
         $nvpArray = array();

        while(strlen($nvpstr))

        {
            //postion of Key
            $keypos= strpos($nvpstr,'=');
            //position of value
            $valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);
            /*getting the Key and Value values and storing in a Associative Array*/
            $keyval=substr($nvpstr,$intial,$keypos);
            $valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
            //decoding the respose
            //$nvpArray[$this->urldecode($keyval)] =$this->urldecode( $valval);
             $nvpArray[urldecode($keyval)]=urldecode( $valval);
            $nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
         }
        return $nvpArray;
    }
   
    function PPHttpPost($methodName_, $nvpStr_, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode) {
            // Set up your API credentials, PayPal end point, and API version.
            $API_UserName = urlencode($PayPalApiUsername);           
            $API_Password = urlencode($PayPalApiPassword);
            $API_Signature = urlencode($PayPalApiSignature);
            //$Env= $this->Env;
            if($PayPalMode=='sandbox')
            {
                $paypalmode     =    '.sandbox';
            }
            else
            {
                $paypalmode     =    '';
            }
   
            $API_Endpoint = "https://api-3t".$paypalmode.".paypal.com/nvp";
            $version = urlencode('76.0');
       
            // Set the curl parameters.
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
            curl_setopt($ch, CURLOPT_VERBOSE, 1);
       
            // Turn off the server and peer verification (TrustManager Concept).
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
       
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
       
            // Set the API operation, version, and API signature in the request.
            echo $nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
       
            // Set the request as a POST FIELD for curl.
            curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
       
            // Get response from the server.
            $httpResponse = curl_exec($ch);
       
            if(!$httpResponse) {
                exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
            }

            // Extract the response details.
            $httpResponseAr = explode("&", $httpResponse);
       
            $httpParsedResponseAr = array();
            foreach ($httpResponseAr as $i => $value) {
                $tmpAr = explode("=", $value);
                if(sizeof($tmpAr) > 1) {
                    $httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
                }
            }
            if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
                exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
            }
       
        return $httpParsedResponseAr;
    }   
   
}

Magento Admin Password Change (How To Reset Admin Password in Magento)

Magento Admin password change

How To Reset Admin Password in Magento?
  1. Log into your Magento admin panel.
  2. Go to System > My account
















    3. type your new password















    4. Enteryour new password then click Save Account button 










    Hope  your password has been successfully Updated/ Changed




Reindexing in magento programmatically



<?php
require_once('app/Mage.php');
Mage::app('default');
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
try{
$indexerByShell = Mage::getBaseDir('shell/indexer.php');
if(file_exists($indexerByShell)) 

$indexListByCode = array(
"catalog_product_attribute",
"catalog_product_price",
"catalog_product_flat",
"catalog_category_flat",
"catalog_category_product",
"catalog_url",
"catalogsearch_fulltext",
"cataloginventory_stock"
);
foreach($indexListByCode as $indexer) 

echo "reindex $indexer \n "; 
exec("php $indexerByShell --reindex $indexer"); 
}
}
}catch(Exception $e){
echo $e;
}
?>

Magento Color swatch simple product

Creating custom attribute. Simply create a drop down selection box and create the same amount of drop down options as you have images, giving them the same name Red, Green, Blue, etc.






You need to modify your /template/page/html/head.phtml file to include the jQuery script  

 <script type="text/javascript">
jQuery(document).ready(function() {
   // On document ready hide all images first
    jQuery("#imageShowcase img").hide();
    jQuery("#productImgDefault").show();
  
    jQuery("#select_25").change(function() {
    var optionValueText = jQuery.trim(jQuery('#select_25 :selected').text());
    if(optionValueText != "-- Please Select --")
    {
 
        // Hide all images on slect element change action
        jQuery("#imageShowcase img").hide();
     optionValueText = optionValueText.split(" +", 2);
//alert (optionValueText[0]);
        // Show the image based on selected value
        jQuery("#productImg" + optionValueText[0]).show();
    }
    });

});
</script>

please check the select_4 option in your file


The final step is to modify the /template/catalog/product/view/media.phtml file

<?php $_product = $this->getProduct() ?>


<div id="imageShowcase">

<?php if ($_product->getImage() != 'no_selection' && $_product->getImage()): ?>
    <img id="productImgDefault" src="<?php echo $this->helper('catalog/image')->init($_product, 'image')->resize(256); ?>" alt="<?php echo $this->htmlEscape($_product->getName()) ?>" />
<?php else: ?>
    <img id="productImgDefault" src="<?php echo $this->helper('catalog/image')->init($_product, 'image')->resize(256); ?>" alt="<?php echo $this->htmlEscape($_product->getName()) ?>" />
<?php endif; ?>
<?php if (count($this->getGalleryImages()) > 0): ?>

<?php foreach ($this->getGalleryImages() as $_image): ?>
    <img src="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'image', $_image->getFile())->resize(256);; ?>" alt="no image" id="productImg<?php echo $this->htmlEscape($_image->getLabel())?>" />
<?php endforeach; ?>
</div>

<?php endif; ?>
  You to see final result




Magento Chain payment configuration. ( magento chained payment free extension )

<?xml version="1.0"?>
<config>
    <modules>
        <Pixel_Paypalpayment>
            <version>0.1.0</version>
        </Pixel_Paypalpayment>
    </modules>
    <frontend>
        <routers>
            <paypalpayment>
                <use>standard</use>
                <args>
                    <module>Pixel_Paypalpayment</module>
                    <frontName>paypalpayment</frontName>
                </args>
            </paypalpayment>
        </routers>
        <layout>
            <updates>
                <paypalpayment>
                    <file>paypalpayment.xml</file>
                </paypalpayment>
            </updates>
        </layout>
    </frontend>
    <admin>
        <routers>
            <paypalpayment>
                <use>admin</use>
                <args>
                    <module>Pixel_Paypalpayment</module>
                    <frontName>paypalpayment</frontName>
                </args>
            </paypalpayment>
        </routers>
    </admin>
     
    <global>
        <models>
            <paypalpayment>
                <class>Pixel_Paypalpayment_Model</class>
                <resourceModel>paypalpayment_mysql4</resourceModel>
            </paypalpayment>
            <paypalpayment_mysql4>
                <class>Pixel_Paypalpayment_Model_Mysql4</class>
            </paypalpayment_mysql4>
        </models>
        <resources>
            <paypalpayment_setup>
                <setup>
                    <module>Pixel_Paypalpayment</module>
                </setup>
            </paypalpayment_setup>
        </resources>
        <blocks>
            <paypalpayment>
                <class>Pixel_Paypalpayment_Block</class>
            </paypalpayment>
        </blocks>
        <helpers>
            <paypalpayment>
                <class>Pixel_Paypalpayment_Helper</class>
            </paypalpayment>
        </helpers>
    </global>
    <default>
        <payment>
            <paypalpayment_standard>
                <active>1</active>
                <customer_id></customer_id>
                <secret_key></secret_key>
                <model>paypalpayment/standard</model>
                <order_status>processing</order_status>
                <test>1</test>
                <debug>1</debug>
                <title>Paypal Payment</title>
            </paypalpayment_standard>
        </payment>
    </default>
</config>
Magento Filter product grid

Magento Filter product grid

<?php
class Pixel_Filterproducts_Model_Observer extends Varien_Event_Observer{

    protected $_productAttributeUser;
    protected $_currentAdminuser;
    protected $_masterAdminRoleId;

    public function __construct(){

        $this->_productAttributeUser = 'vendorid';
        $this->_currentAdminuser = Mage::getSingleton('admin/session')->getUser();
        $this->_masterAdminRoleId = 1;

    }

    /*
    ** List Products Filter by Particular Users
    */
    public function filterProductsByUsers($observer){

        if(Mage::getDesign()->getArea() != 'adminhtml' || $this->_currentAdminuser->getRole()->getRoleId() == $this->_masterAdminRoleId)
        return;
        $event = $observer->getEvent();
        $collection = $event->getCollection()->addAttributeToFilter( 'vendorid', array('eq' =>$this->_currentAdminuser->getUserId() ) );
        /*$count = count($collection->getData());
        if($count > 1)
        echo '
            <style type="text/css">
                .scalable.add{ display:none;}
            </style>
        ';*/
        return $this;

    }
    /*
    ** Before save the product user id should be update for current product
    */
    public function beforeSaveProductUserId($observer){
        if($this->_masterAdminRoleId != $this->_currentAdminuser->getRole()->getRoleId()){
            $observer->getProduct()->setData($this->_productAttributeUser, $this->_currentAdminuser->getUserId());
        }else{
            $_orgPro = Mage::getModel('catalog/product')->load($observer->getProduct()->getId());
            $observer->getProduct()->setData($this->_productAttributeUser, $this->_currentAdminuser->getUserId());
            if($_orgPro->getUser())
            $observer->getProduct()->setData($this->_productAttributeUser, $_orgPro->getVendorid());
        }
    }
}
?>









<?xml version="1.0"?>
<config>
    <modules>
        <Pixel_Filterproducts>
            <version>1.0.0</version>
        </Pixel_Filterproducts>
    </modules>
   
    <global>
         <models>
            <pixel_filterproducts>
                 <class>Pixel_Filterproducts_Model</class>
            </pixel_filterproducts>
        </models>
        <blocks>
            <pixel_filterproducts>
                <class>Pixel_Filterproducts_Block</class>
            </pixel_filterproducts>
            <adminhtml>
                <rewrite>
                    <catalog_product_grid>Pixel_Filterproducts_Block_Adminhtml_Catalog_Product_Grid</catalog_product_grid>
                    <catalog_product>Pixel_Filterproducts_Block_Adminhtml_Catalog_Product</catalog_product>
                </rewrite>
            </adminhtml>
        </blocks>

        <events>
            <catalog_product_collection_load_before>
                <observers>
                    <pixel_filterproducts>
                        <type>singleton</type>
                        <class>pixel_filterproducts/observer</class>
                        <method>filterProductsByUsers</method>
                    </pixel_filterproducts>
                </observers>
            </catalog_product_collection_load_before>
            <catalog_product_save_before>
                <observers>
                    <pixel_filterproducts>
                        <type>singleton</type>
                        <class>pixel_filterproducts/observer</class>
                        <method>beforeSaveProductUserId</method>
                    </pixel_filterproducts>
                </observers>
            </catalog_product_save_before>
        </events>
    </global>
   
</config>













<?php
class Pixel_Filterproducts_Block_Adminhtml_Catalog_Product_Grid extends Mage_Adminhtml_Block_Catalog_Product_Grid{

    protected function _prepareColumns()
    {
        $user_options = array();
        $adminUserModel = Mage::getModel('admin/user');
        $userCollection = $adminUserModel->getCollection()->load();
        foreach ($userCollection as $use_coll)
        {
            $user_options[$use_coll->getId()] = $use_coll->getFirstname();
        }
      
       $user = Mage::getSingleton('admin/session');
       $userId = $user->getUser()->getUserId();
       if($userId == 1)
       {
            $this->addColumn('Vendor',
                array(
                    'header'=> Mage::helper('catalog')->__('Vendor'),
                    'type' => 'options',
                    'renderer' => 'Pixel_Filterproducts_Block_Adminhtml_Catalog_Product_Renderer_Vendor',
                    'index'=>'vendorid',
                    'options'=> $user_options,
                   
                )
             );
        }
         $ban_options = array();
         $banner = Mage::getModel('banner/banner')->getCollection();
            foreach ($banner as $ban)
            {
                $banner_options[$ban->getCode()] = $ban->getName();
            }
       /* $this->addColumn('banner', array(
            'header'    =>  Mage::helper('catalog')->__('Banner'),
            'width'     =>  '100',
            'renderer' => 'Pixel_Filterproducts_Block_Adminhtml_Catalog_Product_Renderer_Banner',
            'type'      =>  'options',
            'options'   =>  $banner_options,
            'index' => 'banner',
           
        ));*/
        return parent::_prepareColumns();
    }

}
?>


<?php
class Pixel_Filterproducts_Block_Adminhtml_Catalog_Product_Renderer_Vendor extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract{

    protected $_productAttributeUser;
    public function __construct(){
        $this->_productAttributeUser = 'vendorid';
    }
    public function render(Varien_Object $row){
        $row = Mage::getModel('catalog/product')->load($row->getEntityId());
        if($_userId = $row->getData($this->_productAttributeUser)){
            $_userTmp = Mage::getSingleton('admin/user')->load($_userId);
            //print_r($_userTmp->getUserId());
            if($_userTmp)
            return $_userTmp->getFirstname().' '.$_userTmp->getLastname();
        }
        return;
    }
  
}
?>

Pageviews from the past week