Skip to content

Instantly share code, notes, and snippets.

@molotovbliss
Last active August 29, 2015 14:06
Show Gist options
  • Save molotovbliss/fded62c1b82175c2848d to your computer and use it in GitHub Desktop.
Save molotovbliss/fded62c1b82175c2848d to your computer and use it in GitHub Desktop.
Shopify to Magento Customer Import via Shopify API
<?php
/**
* Shopify import of customers via Shopify API to Magento
* by: [email protected] (http://molotovbliss.com)
* USE AT YOUR OWN RISK.
*
* Requires: Avs_FastSimpleImport https://github.com/avstudnitz/AvS_FastSimpleImport
* cURL, simpleXML, Magento
*/
ob_implicit_flush(true);
require_once('app/Mage.php');
umask(0);
ini_set('display_errors', 1);
Mage::setIsDeveloperMode(true);
Mage::app();
set_time_limit(0);
//Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
Mage::app()->setCurrentStore(Mage_Core_Model_App::DISTRO_STORE_ID);
class Client {
// Configuration found in Shopify private API creation
// http://docs.shopify.com/api/tutorials/creating-a-private-app
// Total number of items to be returned from shopify API per request
public $limit = 100;
private $_config = array(
'api_key' => '',
'secret' => '',
'token' => '',
'store_url' => '.myshopify.com'
);
private $_action = "/admin/";
public $varienIo;
public $_varDir = "";
public $_mediaDir = "";
public function __construct() {
$this->setExportDir();
$this->setMediaDir();
$this->varienIo = new Varien_Io_File();
Mage::getModel('core/config_options')->createDirIfNotExists($this->_varDir);
Mage::getModel('core/config_options')->createDirIfNotExists($this->_varDir);
}
private function setAction($action) {
$this->_action = $action;
}
public function setExportDir() {
$this->_varDir = Mage::getModel('core/config_options')->getVarDir() . DIRECTORY_SEPARATOR . "shopify" . DIRECTORY_SEPARATOR;
}
public function setMediaDir() {
$this->_mediaDir = Mage::getBaseDir('media') . DIRECTORY_SEPARATOR . 'shopify' . DIRECTORY_SEPARATOR;
}
// build simple URL Request
// $action should contain trailing and starting slashes /
// example $action = /admin/collects/count.xml
public function buildUrlRequest($action, $page = 1, $id = NULL, $fields = NULL) {
$url = 'https://' . $this->_config['api_key'] . ':' . $this->_config['token'] . '@' . $this->_config['store_url'] . $action . $id . '.xml';
$url .= '?limit='.$this->limit;
$url .= '&page='.$page;
$url .= '&fields='.$fields;
echo "Requesting: ".$url."<br />";
$filename = str_replace('/', '', $action.'_'.$id.'_'.$this->limit.'_'.$page.'_'.$fields);
$this->setAction($filename.".xml");
return $url;
}
/**
* Request
* @param str $request
* @return xml
*/
public function request($request) {
$session = curl_init();
curl_setopt($session, CURLOPT_URL, $request);
curl_setopt($session, CURLOPT_ENCODING, "UTF-8" );
curl_setopt($session, CURLOPT_HTTPGET, 1);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_HTTPHEADER, array('Accept: application/xml', 'Content-Type: application/xml;'));
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
if(preg_match("/^(https)/",$request)) curl_setopt($session,CURLOPT_SSL_VERIFYPEER,false);
$response = curl_exec($session);
curl_close($session);
$xml = new SimpleXMLElement($response);
// save copy of generated xml for processing
$xml->asXml($this->_varDir . $this->_action);
return $xml;
}
}
// Create new Shopify client
$shopifyAPI = new Client;
/** @var $import AvS_FastSimpleImport_Model_Import */
$import = Mage::getModel('fastsimpleimport/import');
// get total number of results divide to get offset for pages
$customersCountUrl = $shopifyAPI->buildUrlRequest('/admin/customers/count');
$customersCount = (int) $shopifyAPI->request($customersCountUrl);
$pages = $customersCount / $shopifyAPI->limit;
$pagesRounded = ceil($pages);
ob_start();
echo "Total Customers Found: ".$customersCount*$shopifyAPI->limit." | Total of Required API Requests: ".$pagesRounded;
echo("<hr />");
ob_flush();
flush();
// Get Products
$offset = 1;
while($offset <= $pagesRounded) {
$customersUrl = $shopifyAPI->buildUrlRequest('/admin/customers',$offset);
$customers = $shopifyAPI->request($customersUrl);
echo("<hr />");
$data = array();
$subscribers = array();
foreach($customers as $c) {
// progress status
echo(str_pad(".",2048," "));
ob_flush();
flush();
$email = (string) $c->{'email'};
$firstName = ($c->{'first-name'} == "" ? " " : (string) $c->{'first-name'});
$lastName = ($c->{'last-name'} == "" ? " " : (string) $c->{'last-name'});
$acceptsMarketing = (string) $c->{'accepts-marketing'};
$addresses = $c->{'addresses'};
$defaultAddress = $c->{'default-address'};
// phone required field
if($defaultAddress->{'phone'} == "") {
$defaultPhone = " ";
} else {
$defaultPhone = (string) $defaultAddress->{'phone'};
}
if($acceptsMarketing == "true") {
$subscribers[] = $email;
}
$data = array(
array(
'email' => $email,
'_website' => 'base',
'accountcreated_in' => 'Shopify Import',
'group_id' => 1,
'firstname' => $firstName,
'lastname' => $lastName,
'is_active' => ($c->{'state'} == 'disabled' ? false : true) ,
'_address_firstname' => ($defaultAddress->{'first-name'} == "" ? " " : (string) $defaultAddress->{'first-name'}),
'_address_lastname' => ($defaultAddress->{'last-name'} == "" ? " " : (string) $defaultAddress->{'last-name'}),
'_address_street' => (string) $defaultAddress->{'address1'},
//'_address_street2' => (string) $defaultAddress->{'address2'},
'_address_postcode' => (string) $defaultAddress->{'zip'},
'_address_city' => (string) $defaultAddress->{'city'},
'_address_region' => (string) $defaultAddress->{'province-code'},
'_address_country_id' => (string) $defaultAddress->{'country-code'},
'_address_telephone' => $defaultPhone,
'_address_default_billing_' => ($defaultAddress->{'default'} == "true" ? true : false),
'_address_default_shipping_' => ($defaultAddress->{'default'} == "true" ? true : false),
'reward_update_notification' => true,
'reward_warning_notification' => true,
'is_subscribed' => ($acceptsMarketing == 'true' ? 'true' : 'false'),
),
);
$addressToSave = array();
foreach($addresses->address as $address) {
// skip defaults from creating duplicate entries
if($address->{'default'} == "true") {
continue;
}
// phone required field
if($address->{'phone'} == "") {
$phone = " ";
} else {
$phone = (string) $address->{'phone'};
}
$data[] = array(
'email' => null,
'_website' => null,
'_address_firstname' => ($address->{'first-name'} == "" ? " " : (string) $address->{'first-name'}),
'_address_lastname' => ($address->{'last-name'} == "" ? " " : (string) $address->{'last-name'}),
'_address_street' => (string) $address->{'address1'},
//'_address_street2' => (string) $address->{'address2'},
'_address_postcode' => (string) $address->{'zip'},
'_address_city' => (string) $address->{'city'},
'_address_region' => (string) $address->{'province-code'},
'_address_country_id' => (string) $address->{'country-code'},
'_address_telephone' => $phone,
'_address_default_billing_' => ($address->{'default'} == "true" ? true : false),
'_address_default_shipping_' => ($address->{'default'} == "true" ? true : false),
);
}
//zend_debug::dump($data);
try {
$import->processCustomerImport($data);
} catch (Exception $e) {
zend_debug::dump($e->getMessage());
}
}
// newsletter subscriptions
foreach($subscribers as $email) {
$subscriberModel = Mage::getModel('newsletter/subscriber');
$customerModel = Mage::getModel('customer/customer');
zend_debug::dump($email);
$customer = $customerModel->setWebsiteId(1)->loadByEmail($email);
//zend_debug::dump($customer->getData());
if ($customer->getId()){
$subscriber = $subscriberModel->loadByEmail($email);
//zend_debug::dump($subscriber->getData());
if (!$subscriber->getId()) {
// || $subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED
// || $subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_NOT_ACTIVE) {
$subscriber->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED);
$subscriber->setSubscriberEmail($email);
$subscriber->setSubscriberConfirmCode($subscriber->RandomSequence());
}
$subscriber->setStoreId(Mage::app()->getStore()->getId());
$subscriber->setCustomerId($customer->getId());
try {
$subscriber->save();
}
catch (Exception $e) {
//throw new Exception($e->getMessage());
zend_debug::dump($e->getMessage());
}
}
}
$offset++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment