質問

Im experiencing an issue with Magento 2.1.7

I want to login users programmatically by only their email.

But after setCustomerAsLoggedIn it still shows sign in or create an account in the header.

This issue is the same as Show customer name after setCustomerAsLoggedIn()

which still hasn't been resolved.

/* Magento\Customer\Model\Customer $this->customer */
$Customer = $this->customer->loadByEmail('foo@example.com');
/* Magento\Customer\Model\Session $this->customerSession */
$this->customerSession->setCustomerAsLoggedIn($customer);
役に立ちましたか?

解決

I faced the same issue. The only way I found to update the customer info in the header was by reloading the "customer" section of the localStorage via JavaScript. AFAIK there is no way to do that only in PHP, server side.

Calling customerData.reload(['customer'], true); will trigger an AJAX call to http://www.yoursite.com/customer/section/load/?sections=customer&update_section_id=true&_=some_token. That call returns an object containing the customer data and will trigger the update that replaces the welcome message by the name of the customer.

define([
    'jquery',
    'Magento_Customer/js/customer-data'
], function ($, customerData) {
    'use strict';

    customerData.reload(['customer'], true);
});

他のヒント

Not sure if this is the best method but you can force Magento 2 to reload the Customer Data by adding below code to your controller (or wherever your setCustomerAsLoggedIn method calling sit in):

...
/**
 * @var \Magento\Framework\Stdlib\Cookie\PhpCookieManager
 */
private $cookieMetadataManager;

/**
 * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
 */
private $cookieMetadataFactory;
...
public function __construct(
    ...
    \Magento\Framework\Stdlib\Cookie\PhpCookieManager $cookieManager,
    \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
)
{
    ...
    $this->cookieMetadataManager = $cookieManager;
    $this->cookieMetadataFactory = $cookieMetadataFactory;
}

...
$this->customerSession->setCustomerAsLoggedIn($customer);
$this->_customerSession->regenerateId();

//force Magento 2 to reload Customer Data in frontend
if ($this->cookieMetadataManager->getCookie('mage-cache-sessid')) {
    $metadata = $this->cookieMetadataFactory->createCookieMetadata();
    $metadata->setPath('/');
    $this->cookieMetadataManager->deleteCookie('mage-cache-sessid', $metadata);
}
ライセンス: CC-BY-SA帰属
所属していません magento.stackexchange
scroll top