Magento update order shipping address - php

At the end of the purchase, the user has the possibility to change your shipping address. Im trying to update this information, but it dosen't work. This is my code:
$customer = Mage::getModel('customer/session')->getCustomer();
$order = Mage::getSingleton('checkout/session')->getLastOrder();
$postData = Mage::app()->getRequest()->getPost();
$_new_address = array (
'firstname' => $postData['nombre'],
'lastname' => $postData['apellidos'],
'street' => array ('0' => $postData['direccion']),
'city' => $postData['localidad'],
'region_id' => $postData['provincia_id'],
'region' => '',
'postcode' => $postData['codigo_postal'],
'country_id'=> 'ES',
'telephone' => $postData['telefono']
);
$customAddress = Mage::getModel('customer/address');
$customAddress->setData($_new_address)
->setCustomerId($customer->getId())
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
// Save address
try {
$customAddress->save();
} catch (Exception $e) {
Mage::getSingleton('core/session')->addError($e->getMessage());
header('Location: /');
exit;
}
// Update the order
try {
$order->setShippingAddress($customAddress)->save();
} catch (Exception $e) {
Mage::getSingleton('core/session')->addError($e->getMessage());
header('Location: /');
exit;
}
Can I update an order or is not allowed? Can anyone give me a tip?

My problem was that the Billing address and shipping address in the order, are different than having the user has as default addresses.
At the end the code looks like this:
$order = Mage::getSingleton('checkout/session')->getLastOrder();
$postData = Mage::app()->getRequest()->getPost();
// Try to get shipping and billing address data.
$orderShippingAddress = $order->getShippingAddress()->getId();
$orderShipping = Mage::getModel('sales/order_address')->load($orderShippingAddress);
$orderBillingAddress = $order->getBillingAddress()->getId();
$orderBilling = Mage::getModel('sales/order_address')->load($orderBillingAddress);
// Updating data.
$orderShipping->addData($postData);
$orderBilling->addData($postData);
try {
$orderShipping->implodeStreetAddress()->save();
$orderBilling->implodeStreetAddress()->save();
} catch (Exception $e) {
Mage::logException($e);
Mage::getSingleton('core/session')->addError($e->getMessage());
header('Location: /after/success/envio');
exit;
}
Now, it works. Thanks for your help #R.S

Assuming that you want to update the shipping address for an order, take a look # addressSaveAction() in /app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php
$order = Mage::getSingleton('checkout/session')->getLastOrder();
//Get shipping address Id
$addressId = $order->getShippingAddress()->getId();
$address = Mage::getModel('sales/order_address')->load($addressId);
$data = $this->getRequest()->getPost();
$address->addData($data);
$address->implodeStreetAddress()->save();
Also i'm not sure if Mage::getSingleton('checkout/session')->getLastOrder() will still contain a valid order id after you submit your form since you will be loading a new page

While functioning correctly both other answers have an excessive address loading. The getShippingAddress already returns instance of sales/order_address. So the procedure can be simplified to following:
$order = Mage::getSingleton('checkout/session')->getLastOrder();
$data = $this->getRequest()->getPost();
$order->getShippingAddress()->addData($data)
->save();
Also implodeStreetAddress method call only required if you use multiline street address.

Related

Stripe : New customer created even when customer_id is not empty?

I'm trying to retrieve my user's existing cards from Stripe with the below code. That said, when I use the below backend, even though I'm telling Stripe to ONLY create a new customer if $customer_id is NOT present, a new customer ID is created anyway even when customer_id is NOT null? I feel like I'm missing something obvious here...
.php
$email = $_POST['email'];
$customer_id = $_POST['customer_id']; //get this id from somewhere a database table, post parameter, etc.
$customer = \Stripe\Customer::create(array(
'email' => $email,
));
$customer_id = $_POST['customer_id']; //get this id from somewhere a database table, post parameter, etc.
// if the customer id doesn't exist create the customer
if ($customer_id !== null) {
$key = \Stripe\EphemeralKey::create(
["customer" => $customer->id],
["stripe_version" => $_POST['api_version']]
);
header('Content-Type: application/json');
exit(json_encode($key));
} else {
// \Stripe\Customer::retrieve($customer_id);
$cards = \Stripe\Customer::retrieve($customer_id)->sources->all();
// return the cards
header('Content-Type: application/json');
exit(json_encode($key));
}
Your IF condition should we switched around. Currently you create a customer if the customer_id is present. Based on the description you'd like to see the opposite, right?
In this case all you'd need to do is to switch around the if / else bodies:
if ($customer_id !== null) {
$cards = \Stripe\Customer::retrieve($customer_id)->sources->all();
// return the cards
header('Content-Type: application/json');
exit(json_encode($cards)); // you might want to return the cards here?
} else {
$key = \Stripe\EphemeralKey::create(
["customer" => $customer->id],
["stripe_version" => $_POST['api_version']]
);
header('Content-Type: application/json');
exit(json_encode($key));
}
AND remove the create block at the top. That will create a customer object as well, which you don't need.

add credit card to existing user

I have this credit card adding when a customer first signs up
// CREDIT CARD CODE (STRIPE)
$q_get_user = "select * from users where `id` = '$user_id' ";
$r_get_user = mysqli_query($conn,$q_get_user);
$get_user = mysqli_fetch_assoc($r_get_user);
if(1) {
\Stripe\Stripe::setApiKey("sk_live_9N676756776");
try {
$t = \Stripe\Token::create(
array(
"card" => array(
"name" => $get_user['first_name']." ".$get_user['last_name'],
"number" => $credit_num,
"exp_month" => $credit_month,
"exp_year" => $credit_year,
"cvc" => $credit_ccv
)
)
);
if($t->id != '') {
try {
$c = \Stripe\Customer::create(array(
"description" => "Customer for ".$get_user['email'],
"source" => $t->id)
);
if($c->id != '') {
$stripe_token_response = mysqli_real_escape_string($conn, json_encode($t));
$stripe_token_id = mysqli_real_escape_string($conn, $t->id);
$stripe_customer_response = mysqli_real_escape_string($conn, json_encode($c));
$stripe_customer_id = mysqli_real_escape_string($conn, $c->id);
$stripe_card_id = mysqli_real_escape_string($conn, $c->default_source);
}
} catch (Exception $e) {
//print_r($e->getMessage());
header('Location: /credits?error=cc&message='.urlencode($e->getMessage()));die;
}
}
} catch (Exception $e) {
//print_r($e->getMessage());
header('Location: /credits?error=cc&message='.urlencode($e->getMessage()));die;
}
}
// END - CREDIT CARD CODE (STRIPE)
How can I make it inside of it being for a new customer for it to add to an existing customer? Therefore the customer is adding a new card (they will have more than one)
You are sending card details through the API directly, which is probably not something you want to do. This means that you get the card numbers on your server which has some serious PCI compliance implications. I would strongly advise you to modify your integration so that you always tokenize the card details first by using Stripe.js or Stripe Checkout client-side to send the card details to Stripe directly and get a unique card token (tok_XXX) that you'd then send safely to your server to create the Customer or add as a Card.
You can find a description of the 'card update' process here; the only difference you need is that, instead of doing this to replace the card:
$cu->source = $_POST['stripeToken']; // obtained with Checkout
You want to do this to add a new one:
$customer->sources->create(array("source" => $t->id));

Mailchimp PHP api v.2, User already exists or unsubscribe returns error

I'm using the Mailchimp v.2 API PHP wrapper to handle subscriptions... https://bitbucket.org/mailchimp/mailchimp-api-php however if a subscriber already exists on the list or the subscriber was unsubscribed, it returns an error, and I want to know a way I can code this to where if either of those cases exist, it will continue running the code without displaying an error. I apologize if this is a simple question.
$api_key = "XXXXXXXXX";
$list_id = "XXXXXX";
require('Mailchimp.php');
$Mailchimp = new Mailchimp( $api_key );
$Mailchimp_Lists = new Mailchimp_Lists( $Mailchimp );
$merge_vars = array('FNAME'=>htmlentities($_POST['stripeFirstName']), 'LNAME'=>htmlentities($_POST['stripeLastName']) );
$subscriber = $Mailchimp_Lists->subscribe( $list_id, array( 'email' => htmlentities($_POST['stripeEmail']) ), $merge_vars );
You'll want to make use of try and catch. Mailchimp is pretty verbose about what goes wrong.
try {
$result = $Mailchimp_Lists->subscribe(
$list_id,
array(/* ... */), // primary subscriber data
array(/* ... */), // merge fields
'html', // email-type preference
false // double-opt-in
);
// Action for successful subscribe attempt.
} catch (\Exception $e) {
if ($e instanceof \Mailchimp_List_AlreadySubscribed) {
// In case they are already subscribed:
$errors[] = $e->getMessage();
} else {
// In case something else went wrong.
$errors[] = 'There was an error adding your email to the list. Would you mind trying again?';
}
// Debug time!
var_dump($errors);
}

How can I send POST data with curl to a magento controller function from an external site?

I have a custom controller with a function in my magento site which programmatically creates a customer, add a product to his cart and redirects him to checkout page. Everything works fine. The controller function is accessible through the URL mymagentopage.de/namespace/controllername/functionname and will redirect the user to magento's one-page-checkout page.
Now I need to pass data (name, email and adress from the user) from an external page to this function. I thought I could do this with curl. But it won't work. I always get a blank page without any errors. I never worked with curl before and I am also quite new to magento so I don't really know what the problem might be. Can somebody help me or give me a hint? Or is there another/better way to pass data from an external site?
I use the code in this example on my external site to post the user data to my mageno function using the link mymagentopage.de/namespace/controllername/functionname. The curl code on the external site is executed when the user submits a form, but I got only a blank page...
The magento controller function:
class MyModule_Test_CustomController extends Mage_Core_Controller_Front_Action {
// this is the action that loads the cart and redirects to the cart page
public function cartAction() {
// Get customer session
$session = Mage::getSingleton('customer/session');
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$email = 'test#test.de'
$price = '20';
function IscustomerEmailExists($email, $websiteId = null){
$customer = Mage::getModel('customer/customer');
if ($websiteId) {
$customer->setWebsiteId($websiteId);
}
$customer->loadByEmail($email);
if ($customer->getId()) {
return $customer->getId();
}
return false;
}
$cust_exist = IscustomerEmailExists($email,$websiteId);
if($cust_exist){
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
$session_customer = Mage::getSingleton('customer/session')->loginById($customer->getId());
$customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling();
if ($customerAddressId){
$customAddress = Mage::getModel('customer/address')->load($customerAddressId);
$customAddress->getData();
}
}
else{
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
if(!$customer->getId()) {
$customer->setStore($store);
$customer->setEmail($email);
$customer->setFirstname('John');
$customer->setLastname('Doe');
$customer->setPassword('somepassword');
}
try {
$customer->save();
$customer->setConfirmation(null);
$customer->save();
$session_customer = Mage::getSingleton('customer/session')->loginById($customer->getId());
}
catch (Exception $ex) {
}
//Build billing address for customer, for checkout
$_custom_address = array (
'firstname' => 'John',
'lastname' => 'Doe',
'street' => 'Sample address part1',
'city' => 'Munich',
'region_id' => 'BAY',
'region' => 'BAY',
'postcode' => '81234',
'country_id' => 'DE',
'telephone' => '0123455677',
);
$customAddress = Mage::getModel('customer/address');
$customAddress->setData($_custom_address)
->setCustomerId($customer->getId())
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
try {
$customAddress->save();
}
catch (Exception $ex) {
}
}
Mage::getSingleton('checkout/session')->getQuote()->setBillingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress));
// Get cart instance
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
$product = Mage::getModel('catalog/product');
$product->load('2');
$product->setPrice($price);
$product->save();
$cart->addProduct($product, array('qty' => 1));
$session->setCartWasUpdated(true);
$cart->save();
Mage::app()->getResponse()->setRedirect(Mage::helper('checkout/url')->getCheckoutUrl()); //redirect to Checkout
}
}
Ok, I was thinking way too complicated... I just had to point the form "action" of my external site to the magento page directly which executes my magento action. Then I had to catch the parameters with
$this->getRequest()->getPost('email');
in the magento action. And that's it. So simple...
In your POST code, the fields aren't being url encoded which might generate bad requests or other failures.
Try this:
public function post_to_url($url, $data) {
$fields = http_build_query($fields); // encode array to POST string
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, 1);
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_USERAGENT, 'Mozilla/5.0');
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($post, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($post);
// for debugging
var_dump(curl_getinfo($post), $result);
// if(false === $result) { // request failed
// die('Error: "' . curl_error($post) . '" - Code: ' . curl_errno($post));
// }
curl_close($post);
}

How to send lead via API to Getresponse

I have a html form where name and email address are getting collected. I try to submit these informations to a GetResponse list using this script:
<?php
function mytheme_save_to_getresponse($form)
{
require_once 'jsonRPCClient.php';
$api_key = 'myAPIkey';
$api_url = 'http://api2.getresponse.com';
$client = new jsonRPCClient($api_url);
$result = NULL;
try {
$result = $client->get_campaigns(
$api_key,
array (
# find by name literally
'name' => array ( 'EQUALS' => 'testlist' )
)
);
}
catch (Exception $e) {
# check for communication and response errors
# implement handling if needed
die($e->getMessage());
}
$campaigns = array_keys($result);
$CAMPAIGN_ID = array_pop($campaigns);
$subscriberEmail = $_GET['email'];
try {
$result = $client->add_contact(
$api_key,
array (
'campaign' => $CAMPAIGN_ID,
'name' => $subscriberName,
'email' => $subscriberEmail,
'cycle_day' => '0'
)
);
}
catch (Exception $e) {
# check for communication and response errors
# implement handling if needed
die($e->getMessage());
}
}
?>
The script doesn't show any errors but GetResponse is not saving the lead to my list. Am I doing something wrong?
Thanks
James
If u are getting a response as [queued]=>1 then your script is working fine..
It will be added to your contact only after a validation/confirmation of entered email
$subscriberEmail will recieve a confirmation email...after the user click on the link contact will get added
This line is wrong:
'name' => $subscriberName,
because you have undefined variable and post it to then GetResponse API 'name' params without value so GetResponse API return Invalid params.
Change to:
$subscriberName => "Some_test_name", // for test only
In this line:
$subscriberEmail = $_GET['email'];
you should set some email in GET table maybe for test just change to:
$subscriberEmail = "test#domain.com"; // or sth like this.
Last idea is var_dump $result variable then you see response from GetResponse API
$result = null; // before try {
var_dump($result); // before end of function } ?>
Your code is looks good and You have to set the call back url for error handling

Categories