Question

A new customer who makes a virtual product purchase through paypal has their billing address passed to Magento. The address is attached to the order but is not attached to the customer. What would be the best way to attach this to the customer and also set it as the default billing address on their account?

Was it helpful?

Solution

You're going to want to tap into the predispatch event of the Mage_Paypal_IpnController class:

Create the xml in your custom module to handle the observer for the predispatch:

<global>
    <events>
        <controller_action_predispatch_paypal_ipn_index>
            <observers>
                <mymodule_paypal_ipn_index>
                    <type>singleton</type>
                    <class>yourmodel/observer</class>
                    <method>ipnPreDispatch</method>
                </mymodule_paypal_ipn_index>
            </observers>
        </controller_action_predispatch_paypal_ipn_index>
    </events>
</global>

Observer.php:

<?php

class YourCompany_YourModule_Model_Observer
{

    public function ipnPreDispatch($observer)
    {
        //get the request object and post data
        $data = $observer->getControllerAction()->getRequest()->getPost();

        //get the email address
        $email = $data['email_address'];

        //get the customer via the email
        $customer = Mage::getModel("customer/customer")->loadByEmail($email);

        //set the customer default address
        $default_address = array (
            'firstname' => $data['first'],
            'lastname' => $data['last'],
            'street' => array (
                '0' => $data['street1'],
                '1' => $data['street2'],
            ),
            'city' => $data['city'],
            'region_id' => $data['state'],
            'postcode' => $data['zipcode'],
            'country_id' => $data['country'],
            'telephone' => $data['telephone'],
        );
        $address = Mage::getModel('customer/address');

        $address->setData($default_address)
                    ->setCustomerId($customer->getId())
                    ->setIsDefaultBilling('1')
                    ->setIsDefaultShipping('1')
                    ->setSaveInAddressBook('1');
        try {
            $address->save();
        } catch(Exception $e) {
            Mage::logExeption($e);
        }

    }

}

I'm not certain of the format of the IPN, so the keys of $data in the observer above may need to be altered to adjust. Also, I'm not sure of the business rules, so at the moment it sets all IPN customer addresses to the default to whatever was on their most recent order. This is not production-ready, but gets you 90% of the way there.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top