0

这是问题所在:我正在使用脚本在 Magento 中创建一个用户,并尝试登录该用户(如果他/她已经存在)。

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';
    }
}

脚本回显“用户在线!”,但是当我转到主页时,它向我显示登录按钮,就好像我没有登录一样。我如何登录用户?

4

1 回答 1

0

你设置了网站ID吗?

您还可以通过 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();
}

或者

$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);

于 2013-07-09T17:14:57.010 回答