1

we are using custom module for finding shipping charges and we wrote the list of supported zip codes in below code.

what we need is instead of saving zip codes in code, we want to save list of zip codes in database. we saved list of zip codes in backend as below. Now we have to connect this DB to below code, so that only these zip codes should allow to place an order. enter image description here

<?php
class module_Mpperproductshipping_Model_Carrier_LocalDelivery extends Mage_Shipping_Model_Carrier_Abstract
{
    /*  Use group alias */
    protected $_code = 'mpperproductshipping';

    public function collectRates(Mage_Shipping_Model_Rate_Request $request){        
    $postCode = $request->getDestPostcode();
    $restrictedCodes = array(


110001,
110002,

); //restricted values. they can come from anywhere
    if (!in_array($postCode, $restrictedCodes)) { 
         return false;

    }   

        $result = Mage::getModel('shipping/rate_result');

        /* Edited by vikas_mage */
        $postcode=$request->getDestPostcode();
        $countrycode=$request->getDestCountry();
        $items=$request->getAllItems();
        /* End Editing by vikas_mage */

        $postcode=str_replace('-', '', $postcode);
        $shippingdetail=array();

        /*  one start */
        $shippostaldetail=array('countrycode'=>$countrycode,'postalcode'=>$postcode,'items'=>$items);
       /*  one end  */

         /* tt start - ship charges never work  
         $shippostaldetail=array('countrycode'=>$countrycode,'postalcode'=>$postcode);
         tt end */


        foreach($items as $item) {
            $proid=$item->getProductId();
            $options=$item->getProductOptions();
            $mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
            if(!$mpassignproductId) {
                foreach($item->getOptions() as $option) {
                    $temp=unserialize($option['value']);
                    if($temp['mpassignproduct_id']) {
                        $mpassignproductId=$temp['mpassignproduct_id'];
                    }
                }
            }
            if($mpassignproductId) {
                $mpassignModel = Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId);
                $partner = $mpassignModel->getSellerId();
            } else {
                $collection=Mage::getModel('marketplace/product')
                    ->getCollection()->addFieldToFilter('mageproductid',array('eq'=>$proid));
                foreach($collection as $temp) {
                    $partner=$temp->getUserid();
                }
            }

            $product=Mage::getModel('catalog/product')->load($proid)->getWeight();
            $weight=$product*$item->getQty();
            if(count($shippingdetail)==0){
                array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
            }else{
                $shipinfoflag=true;
                $index=0;
                foreach($shippingdetail as $itemship){
                    if($itemship['seller_id']==$partner){
                        $itemship['items_weight']=$itemship['items_weight']+$weight;
                        $itemship['product_name']=$itemship['product_name'].",".$item->getName();
                        $itemship['item_id']=$itemship['item_id'].",".$item->getId();
                        $itemship['qty']=$itemship['qty']+$item->getQty();
                        $shippingdetail[$index]=$itemship;
                        $shipinfoflag=false;
                    }
                    $index++;
                }
                if($shipinfoflag==true){
                    array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
                }
            }
        }
        $shippingpricedetail=$this->getShippingPricedetail($shippingdetail,$shippostaldetail);

        if($shippingpricedetail['errormsg']!==""){
            Mage::getSingleton('core/session')->setShippingCustomError($shippingpricedetail['errormsg']);
            return $result;
        }
        /*store shipping in session*/
        $shippingAll=Mage::getSingleton('core/session')->getData('shippinginfo');
        $shippingAll[$this->_code]=$shippingpricedetail['shippinginfo'];
        Mage::getSingleton('core/session')->setData('shippinginfo',$shippingAll);

        $method = Mage::getModel('shipping/rate_result_method');
        $method->setCarrier($this->_code);
        $method->setCarrierTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/title'));
        /* Use method name */
        $method->setMethod($this->_code);
        $method->setMethodTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/name'));
        $method->setCost($shippingpricedetail['handlingfee']);
        $method->setPrice($shippingpricedetail['handlingfee']); 
        $result->append($method);
        return $result; 
    }







public function getShippingPricedetail($shippingdetail,$shippostaldetail) {
        $shippinginfo=array();
        $handling=0;
        $session = Mage::getSingleton('checkout/session');
        $customerAddress = $session->getQuote()->getShippingAddress();


/* Edited by vikas_boy */
$customerPostCode = $shippostaldetail['postalcode'];
$items = $shippostaldetail['items'];
 /* End Editing by vikas_boy  */




 /* one  */

        foreach($shippingdetail as $shipdetail) {
            $seller = Mage::getModel("customer/customer")->load($shipdetail['seller_id']);
            $sellerAddress = $seller->getPrimaryShippingAddress();
            $distance = $this->getDistanse($sellerAddress->getPostcode(),$customerPostCode);
            // echo "distance ".$distance;die;
            $price = 0;
            $itemsarray=explode(',',$shipdetail['item_id']);
            foreach($items as $item) {
                $proid=$item->getProductId();
                $options=$item->getProductOptions();
                $mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
                if(!$mpassignproductId) {
                    foreach($item->getOptions() as $option) {
                        $temp=unserialize($option['value']);
                        if($temp['mpassignproduct_id']) {
                            $mpassignproductId=$temp['mpassignproduct_id'];
                        }
                    }
                }
                 if ($item->getHasChildren()){

                    continue;
                }
                $mpshippingcharge = 0;
                $localDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/local_shipping_distance');
                $regionalDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/regional_shipping_distance');
                $stateDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/state_shipping_distance');
                if(in_array($item->getId(),$itemsarray)) {
                    if($mpassignproductId) {
                        if($distance < $localDistance) {
                            $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getLocalShippingCharge();
                        } elseif($distance > $localDistance && $distance < $regionalDistance) {
                            $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getRegionalShippingCharge();
                        } elseif($distance > $regionalDistance) {
                            $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getStateShippingCharge();
                        }
                    } else {
                         // echo "imte ".$item->getProductId();
                        if($distance < $localDistance) {
                            $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpLocalShippingCharge();
                            // echo "imte ".$item->getProductId();
                            // echo "ship ".$mpshippingcharge;
                        } elseif($distance > $localDistance && $distance < $regionalDistance) {
                            $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpRegionalShippingCharge();
                        } elseif($distance > $regionalDistance) {
                            $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpStateShippingCharge();
                        }   
                    }

                    /* tt */
                    // echo "test ".$mpshippingcharge;die;
                    if(!is_numeric($mpshippingcharge)){
                        $price=$price+floatval($this->getConfigData('defalt_ship_amount')* floatval($item->getQty()));
                    }else{
                        $price=$price+($mpshippingcharge * floatval($item->getQty()));
                    }
                    /* tt end */

                    /* one
                    if(floatval($mpshippingcharge)==0){
                        $price=$price+floatval($this->getConfigData('defalt_ship_amount'));
                    }else{
                        $price=$price+$mpshippingcharge;
                    }
                      one end */
                }
            }

            $handling = $handling+$price;
            $submethod = array(array('method'=>Mage::getStoreConfig('carriers/'.$this->_code.'/title'),'cost'=>$price,'error'=>0));
            array_push($shippinginfo,array('seller_id'=>$shipdetail['seller_id'],'methodcode'=>$this->_code,'shipping_ammount'=>$price,'product_name'=>$shipdetail['product_name'],'submethod'=>$submethod,'item_ids'=>$shipdetail['item_id']));
        }
        $msg="";
        return array('handlingfee'=>$handling,'shippinginfo'=>$shippinginfo,'errormsg'=>$msg);
    }


 /* one end */

    /* tt start */

    private function getDistanse($origin,$destination) {
        $url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=".$origin.",india&destinations=".$destination.",india&mode=driving&language=en-EN&sensor=false";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $response = curl_exec($ch);
        curl_close($ch);
        $response_all = json_decode($response);
        $distance = $response_all->rows[0]->elements[0]->distance->value / 1000;
        if($distance==0){
            $zips = array(
                $origin,$destination
                // ... etc ...
            );

            $geocoded = array();
            $serviceUrl = "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:%s&sensor=false";
            $curl = curl_init();
            foreach ($zips as $zip) {
                curl_setopt($curl, CURLOPT_URL, sprintf($serviceUrl, urlencode($zip)));
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
                $data = json_decode(curl_exec($curl));
                $info = curl_getinfo($curl);
                if ($info['http_code'] != 200) {
                    // Request failed
                } else if ($data->status !== 'OK') {
                    // Something happened, or there are no results
                } else {
                    $geocoded[$zip] =$data->results[0]->geometry->location;
                }
            }
            $distance=$this->DistAB($geocoded[$zips[0]]->lat,$geocoded[$zips[0]]->lng,$geocoded[$zips[1]]->lat,$geocoded[$zips[1]]->lng);

            }
        return $distance;
    }

    /* tt end * /





/* tt start  */

public function DistAB($lat_a,$lon_a,$lat_b,$lon_b)

      { 

        $measure_unit = 'kilometers';

        $measure_state = false;

        $measure = 0;

        $error = '';

          $delta_lat = $lat_b - $lat_a ;
          $delta_lon = $lon_b - $lon_a ;
          $earth_radius = 6372.795477598;

          $alpha    = $delta_lat/2;
          $beta     = $delta_lon/2;
          $a        = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($this->lat_a)) * cos(deg2rad($this->lat_b)) * sin(deg2rad($beta)) * sin(deg2rad($beta)) ;
          $c        = asin(min(1, sqrt($a)));
          $distance = 2*$earth_radius * $c;
          $distance = round($distance, 4);

         $measure = $distance;
         return $measure;

      }

    }
  • your question is unclear. Could you add more details? – Sohel Rana Apr 2 '16 at 18:54
  • @SohelRana means now we added some zip codes in localdelivey.php file, so that only those zip codes are allowing to place an order. instead of adding zip codes in localdelivery.php file, i want to update the the zip codes in backend. – Baby in Magento Apr 2 '16 at 18:56
  • i already created some module, so that if we update the zip codes in backend, than its saving in database. now i have to remove zip codes present in localdelivery.php file , and add in backend. and what zip codes i add in backend, only those zip codes should allow to place an order. – Baby in Magento Apr 2 '16 at 18:59
  • So where your checking zipcode wise order. Before place order or before shipping method list? – Sohel Rana Apr 2 '16 at 19:05
  • if i understood correctly, once user enter zip code in shipping address, than he will move to shipping method, at that time we are checking zip code entered by user exists or not in localdelivery.php file , if it exists we alllow for next step , otherwise we will show error message. – Baby in Magento Apr 2 '16 at 19:07
2
+50

Create a module called 'ZipcodeChecker' config.xml is


<?xml version="1.0"?>
<config>
    <modules>
        <SR_ZipcodeChecker>
            <version>0.0.0.1
        </SR_ZipcodeChecker>
    </modules>
    <frontend>
        <routers>
            <checkout>
                <args>
                    <modules>
                        <SR_ZipcodeChecker before="Mage_Checkout">SR_ZipcodeChecker_Checkout</SR_ZipcodeChecker>
                    </modules>
                </args>
            </checkout>
        </routers>
    </frontend>
    <global>
        <helpers>
            <zipcodechecker>
                <class>SR_ZipcodeChecker_Helper</class>
            </zipcodechecker>
        </helpers>
    </global>
</config>

Create a controller 'app/code/local/SR/ZipcodeChecker/controllers/Checkout/OnepageController.php'


require_once Mage::getModuleDir('controllers', 'Mage_Checkout') . DS . 'OnepageController.php';

class SR_ZipcodeChecker_Checkout_OnepageController extends Mage_Checkout_OnepageController
{
    /**
     * Perform address validation on checkout billing address.
     */
    public function saveBillingAction()
    {
        $address = Mage::app()->getRequest()->getPost('billing', array());
        $result = array();
        if(isset($address['use_for_shipping']) && ($address['use_for_shipping'])) {
            $result = Mage::helper('zipcodechecker')->validateZipCode($address);
        }

        if (empty($result['error'])) {
            parent::saveBillingAction();
        } else {
            $this->getResponse()->setHeader('Content-type', 'application/json');
            $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result['error']));
        }
    }

    /**
     * Perform address validation on checkout shipping address.
     */
    public function saveShippingAction()
    {
        $address = Mage::app()->getRequest()->getPost('shipping', array());
        $result = Mage::helper('zipcodechecker')->validateZipCode($address);

        if (empty($result['error'])) {
            parent::saveShippingAction();
        } else {
            $this->getResponse()->setHeader('Content-type', 'application/json');
            $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result['error']));
        }
    }
}

Create a helper for performing global action 'app/code/local/SR/ZipcodeChecker/Helper/Data.php'


class SR_ZipcodeChecker_Helper_Data extends Mage_Core_Helper_Abstract
{
    protected $zipCode = array('90001', '90004');

    public function validateZipCode($address)
    {
        $result = array();
        if(isset($address['postcode']) && $address['postcode']) {
            if(!(in_array($address['postcode'], $this->zipCode))) {
                $result['error'] = 'Zipcode not allowed';
            }
        } else {
            $result['error'] = 'Zipcode not allowed';
        }

        return $result;
    }
}

3
+50

If you want receive data from the your module field (textarea in system config), you could use next solution:

public function getRestrictedZipCodes()
{
    // Replace 'test/module/zips' with the original path from the system.xml file
    $restrictedCodesString = Mage::getStoreConfig('test/module/zips');
    $restrictedCodesString = preg_replace('/\s+/', '', $restrictedCodesString);
    $restrictedCodes = explode(',', $restrictedCodesString);
    if (!empty($restrictedCodes) && is_array($restrictedCodes)) {
        array_walk($restrictedCodes, 'trim');
        $restrictedCodes = array_filter($restrictedCodes);
    }

    return $restrictedCodes;
}

Update code:

public function collectRates(Mage_Shipping_Model_Rate_Request $request)
{        
    $postCode = $request->getDestPostcode();
    $restrictedCodes = $this->getRestrictedZipCodes(); //changes
    if (!in_array($postCode, $restrictedCodes)) { 
         return false;
}
// other code.....

Test field:
Test field in system configuration

Result: Result in debug

If you want get your zip codes anywhere you can always use getRestrictedZipCodes() method.

You can find path to the field in the system.xml file of your module (in the etc directory)

If you want to transfer your zip code values elsewhere in the database, you will need to create a separate collection and source model for your zip codes.

  • i will try & let you know..... – Baby in Magento Apr 3 '16 at 14:35
  • Thanks , it worked for me. but as @Sohel answer gave first, i accepted his answer. – Baby in Magento Apr 3 '16 at 14:50
  • @BabyinMagento ok – Siarhey Uchukhlebau Apr 3 '16 at 14:54
1

create an extension what will provide a section in system configuration(You can create this by silk module creator). and corresponding messages. and create an Ajax for front-end check. and fetch data from that system->configuration part and do your checking part. enjoy.. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.