Magento. Customer online, but not logged in - magento

Here is the problem:
I am using a script to create a user in Magento and trying to login this user if he he/she already exists.
try {
// If new, save customer information
$customer -> firstname = $firstname;
$customer -> lastname = $lastname;
$customer -> email = $email;
$customer -> password_hash = md5($password);
if ($customer -> save()) {
echo $customer -> firstname . " " . $customer -> lastname . " information is saved!";
$customer->setConfirmation(null);
$customer->save();
} else {
echo "An error occured while saving customer";
}
} catch(Exception $e) {
// If customer already exists, initiate login
if (preg_match('/This customer email already exists/', $e)) {
$customer -> loadByEmail($email);
$session = Mage::getSingleton('customer/session');
$session -> login($email, $password);
echo $session -> isLoggedIn() ? $session -> getCustomer() -> getName() . ' is online!' : 'not logged in';
}
}
the script echoes "user is online!", but when I go to the main page, it shows me the login button, as if I am not logged in. How do I login the user?

Did you set the website id?
You could also check if the customer exist by loadByEmail
$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
// This customer email exists
if($customer->getId()){
Mage::getSingleton('core/session', array('name' => 'frontend'));
Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($customer);
}
else{
.....
$customer->save();
}
or
$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
if(!$customer->getId()){
$customer->setFirstname($firstname);
$customer->setLastname($lastname);
.....
$customer->save();
}
Mage::getSingleton('core/session', array('name' => 'frontend'));
Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($customer);
See
Auto Login customer to Magento
Programatically create customer

Related

Programatically adding product to magento cart not working at the first time only

I'm creating custom functions for sign up and adding product to customer cart.
If user signed up using my function first product that he/she added will not be added to the cart unless he added another product after that everything working perfect and the first product also appear in the cart.
If user signed up by using magento sign up form then used my function to add product to the cart everything working.
Sign up code
public function signupAction() {
$email = $this->getRequest()->getPost('email');
$password = $this->getRequest()->getPost('password');
$firstName = $this->getRequest()->getPost('firstName');
$LastName = $this->getRequest()->getPost('LastName');
$session = Mage::getSingleton('customer/session');
$session->setEscapeMessages(true);
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->setWebsiteId($websiteId)
->setStore($store)
->setFirstname($firstName)
->setLastname($LastName)
->setEmail($email)
->setPassword($password);
try {
$customer->cleanPasswordsValidationData();
$customer->save();
$this->_dispatchRegisterSuccess($customer);
$this->_successProcessRegistration($customer);
} catch (Mage_Core_Exception $e) {
} catch (Exception $e) {
}
}
Add to cart code
public function addAction() {
$form_key = Mage::getSingleton('core/session')->getFormKey();
$json = $this->getRequest()->getPost('json');
$jsonObj = json_decode($json);
$cart = $this->_getCart();
$cart->init();
$response = array();
try {
foreach ($jsonObj as $data) {
$param = ['form_key' => $form_key,
'qty' => $data->qty, 'product' => $data->productId];
$product = $this->_initProduct($param['product']);
if ($data->type == 'simple') {
$cart->addProduct($product, $param);
}
}
$cart->save();
$this->_getSession()->setCartWasUpdated(true)
/**
* #todo remove wishlist observer processAddToCart
*/
Mage::dispatchEvent('checkout_cart_add_product_complete',
array('product' => $product,
'request' => $this->getRequest(),
'response' => $this->getResponse()));
if (!$cart->getQuote()->getHasError()) {
$response['status'] = 'SUCCESS';
} else {
$response['status'] = 'Error';
}
} catch (Mage_Core_Exception $e) {
$msg = "";
if ($this->_getSession()->getUseNotice(true)) {
$msg = $e->getMessage();
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$msg .= $message . '<br/>';
}
}
$response['status'] = 'ERROR';
$response['message'] = $msg;
} catch (Exception $e) {
$response['status'] = 'ERROR';
$response['message'] = $this->__('Cannot add items.');
Mage::logException($e);
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
return;
}
refresh the page is solution because magento use the form key to validate the data
so when login a customer then session is change according to that and it working
let me know if you have more Questions .

Magento : Add product to wish list programatically

I have added the below code in my controller to add the product to wishlist programmatically. But whenever ajax request goes to the controller it replaces my previously added product from the wishlist and adds the new one to wishlist.
Can somebody please help with this.
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
// Load the customer's data
$customer = Mage::getSingleton('customer/session')->getCustomer();
//echo $customer->getName(); // Full Name
$customerId = $customer->getId(); // First Name
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customerId, true);
$product = Mage::getModel('catalog/product')->load($productId);
$result = $wishlist->addNewItem($product);
$wishlist->save();
echo "added to wishlist";
}
You can try below :
$product = Mage::getModel('catalog/product')->load($productId);
if (!$product->getId() || !$product->isVisibleInCatalog()) {
//$this->__('Cannot specify product.');
}
try {
$requestParams = $this->getRequest()->getParams();
$buyRequest = new Varien_Object($requestParams=array());
$result = $wishlist->addNewItem($product, $buyRequest);
if (is_string($result)) {
Mage::throwException($result);
}
$wishlist->save();
Mage::dispatchEvent(
'wishlist_add_product',
array(
'wishlist' => $wishlist,
'product' => $product,
'item' => $result
)
);
Mage::helper('wishlist')->calculate();
$message = $this->__('%1$s has been added to your wishlist. Click here to continue shopping.',
$product->getName(), Mage::helper('core')->escapeUrl($referer));
} catch (Mage_Core_Exception $e) {
echo $this->__('An error occurred while adding item to wishlist: %s', $e->getMessage());
}
catch (Exception $e) {
echo ($this->__('An error occurred while adding item to wishlist.'));
}

Magento: Login and redirect to account page from outside magento

I am using this below code to login and redirect to account page:
<?php
include('store/app/Mage.php');
Mage::app();
if($_POST && $_POST['login']['username'] && $_POST['login']['password']){
$email = $_POST['login']['username'];
$password = $_POST['login']['password'];
$session = Mage::getSingleton('customer/session');
try {
$log = $session->login($email, $password);
$session->setCustomerAsLoggedIn($session->getCustomer());
$customer_id = $session->getCustomerId();
$send_data["success"] = true;
$send_data["message"] = "Login Success";
$send_data["customer_id"] = $customer_id;
Mage::getSingleton('customer/session')->loginById($customer_id);
Mage_Core_Model_Session_Abstract_Varien::start();
}catch (Exception $ex) {
$send_data["success"] = false;
$send_data["message"] = $ex->getMessage();
}
}else {
$send_data["success"]=false;
$send_data["message"]="Enter both Email and Password";
}
echo json_encode($send_data);
?>
And then on file from where I am making ajax request, I am using this code:
if(data.success){
window.location = "http://domain.com/store/customer/account/"
}
But it always show user as logout, though I do get correct customer id as well as success.
$email = strip_tags($_GET["login"]);
$password = strip_tags($_GET["psw"]);
function loginUser( $email, $password ) {
umask(0);
ob_start();
session_start();
Mage::app('default');
Mage::getSingleton("core/session", array("name" => "frontend"));
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
try {
$customer->loadByEmail($email);
$session = Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($customer);
if($session->login($email, $password)){ return true;} else { };
}catch(Exception $e){
return $e->getMessage();
}
}
if (loginUser($email,$password) == 1) {
echo ".. user loged as ".Mage::getSingleton('customer/session')->getCustomer()->getName()."<br>";} else {
//bad things goes here
}
In my case Martin's code works if I change the session name
session_name('frontend');
session_start();
If you leave the session name alone it defaults PHPSESSID which isn't the same as that created by Magento on a manual login and didn't work in my install. That may vary, try logging in manually and check your cookie names.
session_name documentation: http://php.net/manual/en/function.session-name.php

Magento doesn't assign website id when creating customer programatically

I m creating customer programatically but customer created successfully but can't login with frontend.issue is website id dosen't assign to customer i have tried below code
if ($detail->ContactEmail && $detail->ContactName != '' && filter_var($detail->ContactEmail, FILTER_VALIDATE_EMAIL)) {
$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId(1);
$customer->loadByEmail($detail->ContactEmail);
/*
* Check if the email exist on the system.
* If YES, it will not create a user account.
*/
if (!$customer->getId()) {
//setting data such as email, firstname, lastname, and password
$customer->setEmail($detail->ContactEmail);
$name = preg_split('/\s+/', trim($detail->ContactName));
if (count($name) == 1) {
$customer->setFirstname($name[0]);
$customer->setLastname($name[0]);
} else {
$customer->setFirstname($name[0]);
$customer->setLastname($name[1]);
}
//$customer->setWebsiteId(array(1));
$customer->setcontactJobTitle($detail->ContactJobTitle);
$customer->setcontactSeqNo($detail->ContactSeqNo);
$customer->setdebtorAccNo($detail->DebtorAccNo);
$customer->setdebtorApiKey($debtorAPI);
$customer->setStoreId(Mage::app()->getStore('default')->getId());
$customer->setPassword($customer->generatePassword($passwordLength));
}
try {
//the save the data and send the new account email.
$customer->save();
$customer->setConfirmation(null);
$customer->save();
$customer->sendNewAccountEmail();
$customerCount[] = $i;
//echo 'contact added';
}
catch (Exception $e) {
//echo 'contact not added';
}
I have found where is the problem to saving customer. whenever we load the customer by loadByEmail function we must set website id to load customer otherwise customer save raise the exception Customer website ID must be specified when using the website scope. so I have made following changes to set website id when creating customer.
if ($detail->ContactEmail && $detail->ContactName != '' && filter_var($detail->ContactEmail, FILTER_VALIDATE_EMAIL)) {
$customer = Mage::getModel('customer/customer')->setWebsiteId(1);
$customer->loadByEmail($detail->ContactEmail); /* changed line */
/*
* Check if the email exist on the system.
* If YES, it will not create a user account.
*/
if (!$customer->getId()) {
//setting data such as email, firstname, lastname, and password
$customer->setEmail($detail->ContactEmail);
$name = preg_split('/\s+/', trim($detail->ContactName));
if (count($name) == 1) {
$customer->setFirstname($name[0]);
$customer->setLastname($name[0]);
} else {
$customer->setFirstname($name[0]);
$customer->setLastname($name[1]);
}
$customer->setcontactJobTitle($detail->ContactJobTitle);
$customer->setcontactSeqNo($detail->ContactSeqNo);
$customer->setdebtorAccNo($detail->DebtorAccNo);
$customer->setdebtorApiKey($debtorAPI);
$customer->setStoreId(Mage::app()->getStore('default')->getId());
$customer->setPassword($customer->generatePassword($passwordLength));
}
try {
//the save the data and send the new account email.
$customer->save();
$customer->setConfirmation(null);
$customer->setWebsiteId(1); /* changed line */
$customer->save();
$customer->sendNewAccountEmail();
$customerCount[] = $i;
//echo 'contact added';
}
catch (Exception $e) {
//echo 'contact not added';
}
please find the below code for creating customer programmatically:
error_reporting(E_ALL | E_STRICT);
$mageFilename = 'app/Mage.php';
if (!file_exists($mageFilename)) {
if (is_dir('downloader')) {
header("Location: downloader");
} else {
echo $mageFilename." was not found";
}
exit;
}
require_once $mageFilename;
Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app('default');
$customer_email = 'test#testemail.com';
$customer_fname = 'test_firstname';
$customer_lname = 'test_lastname';
$passwordLength = 10;
$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($customer_email);
if(!$customer->getId()) {
$customer->setEmail($customer_email);
$customer->setFirstname($customer_fname);
$customer->setLastname($customer_lname);
$customer->setPassword($customer->generatePassword($passwordLength));
}
try{
$customer->save();
$customer->setConfirmation(null);
$customer->save();
}
================================================================================

Creating orders programmatically

I try to create an order in code, but sometimes the code works, but sometimes it goes wrong with exception "The requested Payment Method is not available." (first browser request is ok, but the second one goes wrong, etc..).
My code is:
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
$customer = Mage::getSingleton('customer/session')->getCustomer();
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
} else {
$customer = Mage::getModel('customer/customer');
$email = 'test#example.com';
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->setStoreId(Mage::app()->getStore()->getId());
$customer->loadByEmail($email);
Mage::getSingleton('customer/session')->loginById($customer->getId());
}
$customAddress = Mage::getModel('customer/address')
->setCustomerId($customer->getId())
->getCustomer();
$customAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling();
if ($customAddressId) {
$customAddress = Mage::getModel('customer/address')->load($customAddressId);
}
Mage::getSingleton('checkout/session')->getQuote()
->setBillingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress))
->setShippingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress));
$product = Mage::getModel('catalog/product')
->setStoreId(Mage::app()->getStore()->getId())
->load(2);
$cart = Mage::getSingleton('checkout/cart');
$cart->truncate();
try {
$cart->addProduct($product, array('qty' => 2));
$cart->save();
$message = $this->__('%s was successfully added to your shopping cart.', $product->getName());
Mage::getSingleton('checkout/session')->addSuccess($message);
} catch (Exception $ex) {
echo $ex->getMessage();
}
$storeId = Mage::app()->getStore()->getId();
$checkout = Mage::getSingleton('checkout/type_onepage');
$checkout->initCheckout();
$checkout->saveCheckoutMethod('register');
$checkout->saveShippingMethod('flatrate_flatrate');
$checkout->savePayment(array('method' => 'banktransfer'));
try {
$checkout->saveOrder();
} catch (Exception $ex) {
echo $ex->getMessage();
}
$cart->truncate();
$cart->save();
$cart->getItems()->clear()->save();
Mage::getSingleton('customer/session')->logout();
I checked your code in my local server, It s working fine 1st time, but second time it shows error like The requested Shipping Method is not available not like you mentioned above. But after I enabled that shipping method it working fine, So try to enable the shipping and payment methods that you used in your code in admin..

Resources