I have a site outside Magento's domain and I should allow Magento customer to login into Magento Store from this external site. Being completely new to Magento , I don't know how to implement this service. I was able to allow registration to Magento from an external site using REST API, but I can't find a similar way to login using REST services.
Magento – Login into Magento 2 site from external site
apiexternalloginmagento2rest
Related Solutions
By the time I finished writing this I spotted my error:
Magento expects the cookie domain to be entered without the initial "."
By using "mydomain.com" as my manual cookie domain, I can log in again. On setting the cookies, Magento prefixes a "." so the cookies I see in my browser are ".mydomain.com" and they work exactly the same across sub-domains, but it also recognises the cookies so that login works.
1) First Create webapi.xml declare url, interface and method
<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<route url="/V1/fetch/sociallogin" method="POST">
<service class="HIT\Customer\Api\SocialLoginCustomerInterface" method="socialLogin"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>
2) create di.xml for dependency injection
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="HIT\Customer\Api\SocialLoginCustomerInterface" type="HIT\Customer\Model\SocialLoginCustomer" />
</config>
3) create social login interface SocialLoginCustomerInterface.php
<?php
namespace HIT\Customer\Api;
interface SocialLoginCustomerInterface
{
/**
* Returns greeting message to user
*
* @api
* @param string $name Users name.
* @return string Greeting message with users name.
*/
public function socialLogin();
}
4) create SocialLoginCustomer.php for logic
<?php
namespace HIT\Customer\Model;
use HIT\Customer\Api\SocialLoginCustomerInterface;
use Magento\Framework\App\RequestFactory;
use Magento\Customer\Model\CustomerExtractor;
use Magento\Customer\Api\AccountManagementInterface;
class SocialLoginCustomer implements SocialLoginCustomerInterface
{
/**
* @var \Magento\Framework\App\Request\Http
*/
protected $_request;
/**
* @var EncryptorInterface
*/
protected $_encryptor;
/**
* @var \Magento\Customer\Model\CustomerFactory
*/
protected $customerFactory;
/**
* @var RequestFactory
*/
protected $requestFactory;
/**
* @var CustomerExtractor
*/
protected $customerExtractor;
/**
* @var AccountManagementInterface
*/
protected $customerAccountManagement;
/**
* @var Config\Source\BrandOptions
*/
protected $brandOptions;
/**
* @var \Magento\Customer\Model\ResourceModel\CustomerRepository
*
*/
protected $customerRepository;
/**
* @var \Magento\Customer\Model\AddressFactory
*/
protected $addressFactory;
/**
* @var \Magento\Customer\Model\ResourceModel\Customer\Collection
*/
protected $customerCollection;
/**
* @var \Magento\Framework\App\ResourceConnection
*/
protected $_resource;
/**
* CreateCustomer constructor.
* @param \Magento\Framework\App\Request\Http $request
* @param EncryptorInterface $encryptor
* @param \Magento\Customer\Model\CustomerFactory $customerFactory
* @param RequestFactory $requestFactory
* @param CustomerExtractor $customerExtractor
* @param AccountManagementInterface $customerAccountManagement
* @param Config\Source\MotherTongue $brandOptions
*/
public function __construct(
\Magento\Framework\App\Request\Http $request,
\Magento\Framework\Encryption\Encryptor $encryptor,
\Magento\Customer\Model\CustomerFactory $customerFactory,
RequestFactory $requestFactory,
CustomerExtractor $customerExtractor,
AccountManagementInterface $customerAccountManagement,
Config\Source\MotherTongue $brandOptions,
\Magento\Customer\Model\ResourceModel\CustomerRepository $customerRepository,
\Magento\Customer\Model\AddressFactory $addressFactory,
\Magento\Customer\Model\ResourceModel\Customer\Collection $customerCollection,
\Magento\Framework\App\ResourceConnection $resource
)
{
$this->_request = $request;
$this->_encryptor = $encryptor;
$this->customerFactory = $customerFactory;
$this->requestFactory = $requestFactory;
$this->customerExtractor = $customerExtractor;
$this->customerAccountManagement = $customerAccountManagement;
$this->brandOptions = $brandOptions;
$this->customerRepository = $customerRepository;
$this->addressFactory = $addressFactory;
$this->customerCollection = $customerCollection;
$this->_resource = $resource;
}
/**
* @return false|string
*/
public function socialLogin()
{
$customerInfo = $this->_request->getContent();
if($customerInfo){
$customerInfo = (array) json_decode($customerInfo);
}
$connection = $this->_resource->getConnection();
$tableName = $this->_resource->getTableName('social_login');
$data = array();
$diff = array_diff_key(['firstname' => 1, 'lastname' => 1, 'email' => 1, 'customer_telephone' => 1,'social_id' => 1], $customerInfo);
if ($customerInfo && count($diff) == 0) {
$result = $connection->fetchOne("SELECT `customer_id` FROM ".$tableName." WHERE `social_id`='".$customerInfo['social_id']."'");
if($result){
$customerObjModel = $this->customerFactory->create()->getCollection()->addAttributeToFilter('entity_id',$result)->getFirstItem();
$customerObj = (object)$customerObjModel->getData();
$customerDetails = array(
'customer_id' => $customerObj->entity_id,
'firstname' => $customerObj->firstname,
'lastname' => $customerObj->lastname,
'email' => $customerObj->email
);
$data['status'] = "true";
$data['msg'] = 'Successfully logged in.';
$data['customer_info'] =$customerDetails;
}else{
$customerData = [
'firstname' => $customerInfo['firstname'],
'lastname' => $customerInfo['lastname'],
'email' => $customerInfo['email']
];
$request = $this->requestFactory->create();
$request->setParams($customerData);
try {
$customer = $this->customerExtractor->extract('customer_account_create', $request);
$customer->setWebsiteId(1);
if (isset($customerInfo['customer_telephone'])) {
$customer->setCustomAttribute('customer_telephone', $customerInfo['customer_telephone']);
}
$customerModel = $this->customerRepository->save($customer);
$customerDetails = array(
'customer_id' => $customerModel->getId(),
'firstname' => $customerModel->getFirstname(),
'lastname' => $customerModel->getLastname(),
'email' => $customerModel->getEmail()
);
$result = $connection->query("INSERT INTO ".$tableName." (`customer_id`, `type`, `social_id`) VALUES (".$customerModel->getId().",'".$customerInfo['type']."','".$customerInfo['social_id']."')");
$data['status'] = "true";
$data['msg'] = 'Successfully Registered With Us.';
$data['customer_info'] =$customerDetails;
} catch (\Exception $e) {
$data['status'] = "false";
$data['msg'] = $e->getMessage();
}
}
} else {
$data['status'] = "false";
$data['msg'] = 'Missing Params';
}
echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT );// str_replace('\/','/',json_encode($data));
exit();
}
}
5) create table social_login fields are id
, customer_id
, type
, social_id
, created_at
Best Answer
You can use REST API also. Magento 2 framework builds in already a list of useful API functions.
Token-based authentication
http://devdocs.magento.com/guides/v2.1/get-started/authentication/gs-authentication-token.html
So, in your case, for example, we have a login form on your site. We have two input fields: username and password. In your controller, we can get these values and pass to the Magento API. A successful response will return with a token which is used for authentication on the Magento side.