Magento : Add customer default billing address - php

I am trying to import the customers into my new magento installation from an old site and want to set customer address as magento customer default billing address i hvae tried
$customer = $this->getCustomerModel();
$address = Mage::getModel('customer/address');
$customer->addAddress($results[0]['address']); //this says trying to save invalide object
$address ->addAddress($results[0]['address']); //this says undefined method
$results[0]['address'] this field contains the street address i have also the city,state, zip,postcode
Any idea about how can i set my customer address as its default billing or shipping address..

Well I have found it with help of Anoop sir.
$_custom_address = array (
'firstname' => 'Branko',
'lastname' => 'Ajzele',
'street' => array (
'0' => 'Sample address part1',
'1' => 'Sample address part2',
),
'city' => 'Osijek',
'region_id' => '',
'region' => '',
'postcode' => '31000',
'country_id' => 'HR', /* Croatia */
'telephone' => '0038531555444',
);
$customAddress = Mage::getModel('customer/address');
//$customAddress = new Mage_Customer_Model_Address();
$customAddress->setData($_custom_address)
->setCustomerId($customer->getId())
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
try {
$customAddress->save();
}
catch (Exception $ex) {
//Zend_Debug::dump($ex->getMessage());
}

Related

Rest API - Import JSON file with products to Drupal 8 and create product nodes with that data

For a website I have to import products with a Rest API to a Drupal 8 webshop. Here is the documentation of the API: https://www.floraathome.nl/api-documentatie/v1/
I succesfully got the data from all products using:
https://api.floraathome.nl/v1/products/get?apitoken=[MY_TOKE]&type=json
I also succeeded printing out some data from it in a PHP file:
<?php
$url = 'https://api.floraathome.nl/v1/products/get?apitoken=[MY_TOKE]&type=json';
$json = file_get_contents($url);
$retVal = json_decode($json, TRUE);
foreach($retVal['data'] as $retV){
echo $retV['dutchname']."<br>";
echo $retV['purchaseprice']."<br>";
echo $retV['promotionaltext']."<br><br>";
}
I have no experience with API's or anything like it. But now I would like to be able to import the data from the API into Drupal 8, as products.
What would be my best solution to approach this?
Thanks in advance,
Mike
This is how I would do it, I hope it works for you.
For store creation:
<?php
// The store type. Default is 'online'.
$type = 'online';
// The user id the store belongs to.
$uid = 1;
// The store's name.
$name = 'My Store';
// Store's email address.
$mail = 'admin#example.com';
// The country code.
$country = 'US';
// The store's address.
$address = [
'country_code' => $country,
'address_line1' => '123 Street Drive',
'locality' => 'Beverly Hills',
'administrative_area' => 'CA',
'postal_code' => '90210',
];
// The currency code.
$currency = 'USD';
// If needed, this will import the currency.
$currency_importer = \Drupal::service('commerce_price.currency_importer');
$currency_importer->import($currency);
$store = \Drupal\commerce_store\Entity\Store::create([
'type' => $type,
'uid' => $uid,
'name' => $name,
'mail' => $mail,
'address' => $address,
'default_currency' => $currency,
'billing_countries' => [
$country,
],
]);
// If needed, this sets the store as the default store.
$store_storage = \Drupal::service('entity_type.manager')->getStorage('commerce_store');
$store_storage->markAsDefault($store);
// Finally, save the store.
$store->save();
For variation (indicated by $variation do something like
<?php
$price = new \Drupal\commerce_price\Price('24.99', 'USD');
$variation = ProductVariation::create([
'type' => 'default', // The default variation type is 'default'.
'sku' => 'test-product-01', // The variation sku.
'status' => 1, // The product status. 0 for disabled, 1 for enabled.
'price' => $price,
]);
$variation->save();
Finally, for the product:
<?php
use \Drupal\commerce_product\Entity\Product;
use \Drupal\commerce_product\Entity\ProductVariation;
$req=\Drupal::httpClient()->get("https://api.floraathome.nl/v1/products/get?apitoken=[MY_TOKE]&type=json");
$res=json_decode($req);
foreach($res['data'] as $r) {
$product = Product::create(['type' => 'default', 'variations' => $variation, 'stores' => $sid]);
$product->set('title', $r['dutchname'];
...
...
...
$product->save();
}
I hope you get the idea.
Note: Needless to say, I had to make variables/values up as I don't have access to the API.

Getting the rate of a specific service - EasyPost

I currently have EasyPost creating a shipment. When I create the shipment it provides me with all the available services and rates.
I would like to dynamically select service and only return that rate.
I originally would read through the array using the index number (I guess that how to describe it).
The problem with this is every time I create a new shipment the order of the rates array changes so what would have been $shipment->rates[0]['rate'] would be express and then the next time first class.
I want to create a shipment with "Express" and only return that rate.
Any advice would be appreciated.
Here is my code:
$name = $this->thiscustomer->cust_first . ' ' . $this->thiscustomer->cust_first;
$street_1 = $this->thiscustomer->street_1;
$street_2 = $this->thiscustomer->street_2;
$city = $this->thiscustomer->city;
$state = $this->thiscustomer->state;
$zip = $this->thiscustomer->zip;
$weight = $this->weight;
$packaging = $this->packaging;
$service = $this->service;
$caddress = $this->consultant->address;
$cstreet_1 = $this->consultant->street_1;
$cstreet_2 = $this->consultant->street_2;
$ccity = $this->consultant->city;
$cstate = $this->consultant->state;
$czip = $this->consultant->zip;
$cname = $this->consultant->first_name . ' ' . $this->consultant->last_name;
$cuser_id = $this->consultant->user_id;
require_once(dirname(__FILE__) . '/lib/easypost.php');
\EasyPost\EasyPost::setApiKey('KUk4fZUI6YaYc1h0FiIXFw');
$shipment = \EasyPost\Shipment::create(array(
'to_address' => array(
"name" => $name,
"street1" => $street_1,
"street2" => $street_2,
"city" => $city,
"state" => $state,
"zip" => $zip
),
'from_address' => array(
"company" => $cname,
"street1" => $cstreet_1,
"street2" => $cstreet_2,
"city" => $ccity,
"state" => $cstate,
"zip" => $czip
),
'parcel' => array(
'weight' => $weight,
'predefined_package'=> $packaging
),
'rates' => array(
'service' => $service
)
));
echo $shipment->rates[0]['rate']. '<br>';
In EasyPost's Getting Started Guide there is an example of buying a specific carrier+rate:
$shipment->buy($shipment->lowest_rate(array('USPS'), array('Express')));
you can get different rates through below lines of code
if(!empty($shipment->rates))
{
$count = 0;
foreach($shipment->rates as $rate)
{
$serviceRates[$count] = [
'service' => $rate->service,
'carrier' => $rate->carrier,
'rate' => $rate->rate,
'currency' => $rate->currency,
'delivery_days' => $rate->delivery_days
];
$count++;
}
}
else
{
echo 'no result fond for given address';
}
print_r($serviceRates);
#KFunk is correct that EasyPost does not provide a native way to accomplish what you are asking since this use case is unique to you. The EasyPost client libraries provide all the functions needed to interact with the API; however, all of the business logic is left to the user.
If you want to create a shipment but only show a single rate to the user, you will need to filter out the other rates in your own application. To do this, you can follow the simple example here:
<?php
\EasyPost\EasyPost::setApiKey($_ENV['EASYPOST_API_KEY']);
// Create your shipment, the response will contain all rates for all configured carriers
$shipment = \EasyPost\Shipment::create([
'to_address' => [
'name' => 'Dr. Steve Brule',
'street1' => '179 N Harbor Dr',
'city' => 'Redondo Beach',
'state' => 'CA',
'zip' => '90277',
'country' => 'US',
'phone' => '3331114444',
'email' => 'dr_steve_brule#gmail.com'
],
'from_address' => [
'name' => 'EasyPost',
'street1' => '417 Montgomery Street',
'street2' => '5th Floor',
'city' => 'San Francisco',
'state' => 'CA',
'zip' => '94104',
'country' => 'US',
'phone' => '3331114444',
'email' => 'support#easypost.com'
],
'parcel' => [
'length' => 20.2,
'width' => 10.9,
'height' => 5,
'weight' => 65.9
]
]);
$rates = $shipments->rates;
// Filter out all the rates that aren't the desired one, in this case - `Express`
$expressRate = null;
foreach ($rates as $rate) {
if ($rate->service == "Express") {
$expressRate = $rate;
break;
}
}
// Return $expressRate to your UI or do with it what you need
echo $expressRate;
Relying on array ordering is an antipattern that should be avoided. Array indices are never guaranteed to remain in the same order and do not have a strong bond to the data in question.
For further help with the EasyPost API specifically, you can reach out to our support team via support#easypost.com. Best of luck!

How to create order programmatically logged in customer?

Currently I make php script to generate order not logged in customer but i want to use this script for logged in customer dynamically for logged in customer my code is
$quote = Mage::getModel('sales/quote')
->setStoreId(Mage::app()->getStore('default')->getId());
// for guest orders only:
$quote->setCustomerEmail('customer#email.com');
//}
// add product(s)
$product = Mage::getModel('catalog/product')->load(1307,1305);
$buyInfo = array(
'qty' => 1,
// custom option id => value id
// or
// configurable attribute id => value id
);
$quote->addProduct($product, new Varien_Object($buyInfo));
//$quote->addProduct($product2, new Varien_Object($buyInfo));
$addressData = array(
'firstname' => 'Test',
'lastname' => 'Test',
'street' => 'Sample Street 10',
'city' => 'Somewhere',
'postcode' => '123456',
'telephone' => '123456',
'country_id' => 'US',
'region_id' => 12, // id from directory_country_region table
);
$billingAddress = $quote->getBillingAddress()->addData($addressData);
$shippingAddress = $quote->getShippingAddress()->addData($addressData);
$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('flatrate_flatrate')
->setPaymentMethod('checkmo');
$quote->getPayment()->importData(array('method' => 'checkmo'));
$quote->collectTotals()->save();
echo "quote save";
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
echo "order save";
$order = $service->getOrder();
printf("Created order %s\n", $order->getIncrementId());
}catch(Exception $e){
print_r($e->getMessage());
}
this script is create order programmatically for not loggedin customer
Arvind,
Follow the same quote object. Use below methods in quote object to create an order for logged in customer.
$quote->setCustomerId()->setCustomerIsGuest(false)->setCustomerFirstname()->setCustomerLastname()->setCustomerGroupId();
This will create the order for the provided customer information. Hope this will help.

Create a customer address to already exist customer - Magento

I'm trying create programmatically a new address to customers that was imported a some time ago for me.
My Code:
//All variables about customer address info are filled
$customerModel = Mage::getModel('customer/customer');
$customer = $customerModel->setWebsiteId(1)->loadByEmail($_email);
if($customer->getId()) {
$addressData = array (
'firstname' => $customer->getFirstname(),
'lastname' => $customer->getLastname(),
'street' => "$_s1
$_s2
$_s3
$_s4",
'city' => $_city,
'country_id' => 'BR',
'region_id' => $_regionid,
'postcode' => $_cep,
'telephone' => $_tel,
'celular' => $_cel,
'is_default_billing' => 1,
'is_default_shipping' => 1
);
$address = Mage::getModel('customer/address');
$address->addData($addressData);
$customer->addAddress($address);
try {
print_r($addressData);
$customer->save();
}
catch (Exception $e) {
}
}
Object loaded '$customer' isnt what I need: a full customer object.
Any Idea?
You have to save customer address in different way, following is address saving code.
$customerAddress = Mage::getModel('customer/address');
$customerAddress->setData($addressData)
->setCustomerId($customer->getId())
->setSaveInAddressBook('1');
$customerAddress->save();
The full code will look like:
$customerModel = Mage::getModel('customer/customer');
$customer = $customerModel->setWebsiteId(1)->loadByEmail($_email);
if($customer->getId()) {
$addressData = array (
'firstname' => $customer->getFirstname(),
'lastname' => $customer->getLastname(),
'street' => "$_s1
$_s2
$_s3
$_s4",
'city' => $_city,
'country_id' => 'BR',
'region_id' => $_regionid,
'postcode' => $_cep,
'telephone' => $_tel,
'celular' => $_cel,
'is_default_billing' => 1,
'is_default_shipping' => 1
);
$customerAddress = Mage::getModel('customer/address');
$customerAddress->setData($addressData)
->setCustomerId($customer->getId())
->setSaveInAddressBook('1');
$customerAddress->save();
//And reload customer object
$customer = Mage::getModel('customer/customer')->load($customer->getId());
//Check customer data
print_r($customer->getData());
//Check addresses
foreach($customer->getAddresses() as $address)
{
print_r($address);
}
}

How to edit Magento current logged user details via php code

$session = Mage::getSingleton('customer/session');
$customer_id = $session->getId();
$customer_data = Mage::getModel('customer/customer')->load($customer_id);
print_r($customer_data);
Through this code ican get user details
I need to know How to edit the user details like address,password ..etc in the same Way using Php codes
Thanks all
for Password you can set using $customer_id
$password = 'Any Things'
$customer = Mage::getModel('customer/customer')->load($customer_id);
$customer->setPassword($password);
$customer->save();
For Edit address you have to load address model
For Example if you want to edit billing Address :
$customer = Mage::getModel('customer/customer')->load($customer_id);
$address = $customer->getDefaultBilling();
$address->setFirstname("Test");
$address->save();
OR :
using address id get from customer object :
$address = Mage::getModel('customer/address')->load($customerAddressId);
$address->setFirstname("Test");
$address->save();
You can use php magic get and set methods
Suppose to set password you can use $customer_data->setPassword('1234567');
$customer_data->save();
For customer address
$_custom_address = array (
'firstname' => 'firstname',
'lastname' => 'lastname',
'street' => array (
'0' => 'Sample address part1',
'1' => 'Sample address part2',
),
'city' => 'city',
'region_id' => '',
'region' => '',
'postcode' => '31000',
'country_id' => 'US',
'telephone' => '0038531555444',
);
$customAddress = Mage::getModel('customer/address')
$customAddress->setData($_custom_address)
->setCustomerId($customer->getId())
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
try {
$customAddress->save();
}
catch (Exception $ex) {
//Zend_Debug::dump($ex->getMessage());
}
For more info http://inchoo.net/ecommerce/magento/programming-magento/programatically-create-customer-and-order-in-magento-with-full-blown-one-page-checkout-process-under-the-hood/
You can use methods of Mage_Customer_Model_Customer class:
$customerSession = Mage::getSingleton('customer/session');
$customerModel = Mage::getModel('customer/customer')->load($customerSession->getId());
$customerModel->changePassword('new_password');

Categories