3

I need to create a user account using social network via the API.

I have created via native iOS application that hooks into magento 2 store API. However, I can not find a way to create an account using any of social extensions. They add buttons however they do not expose any functionality over rest API for creating accounts or login.

  • Did you reached for the solution? – Jsparo30 Apr 26 '17 at 14:56
  • Still looking - Mostly likely will need to code the full implementation – justacoder Apr 27 '17 at 16:53
  • Do you have an Idean, how to get the token after login with social ? review this https://magento.stackexchange.com/questions/175480/get-token-authentication-for-customer-logged-with-facebook-twitter-magento-2 – Jsparo30 May 24 '17 at 8:43
  • You can follow this guide: cloudways.com/blog/add-social-login-in-magento-2 to add Social login to your site. – Say Truth Jul 7 '17 at 2:04
  • Any solution for login and create a customer account API for Facebook and Google ? – Kirti Nariya Sep 19 '19 at 12:52
0

At first create a custom rest api with below route. you can follow this link: https://alankent.me/2015/07/24/creating-a-new-rest-web-service-in-magento-2/ to create custom res api.

<!-- ws: social login -->
<route url="/V1/customrestapi/login" method="POST">
    <service class="PackageName\CustomRestApi\Api\SocialloginInterface" method="socialLogin"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>

Then in the socialLogin method pass the social data as array.Here you can put your logic as shown below code.

/**
* Copyright 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/

namespace PackageName\CustomRestApi\Model;

use PackageName\CustomRestApi\Api\SocialloginInterface;
/**
 * Defines the implementaiton class of the calculator service contract.
 */
class Sociallogin implements SocialloginInterface
{

protected $_storeManager;
protected $_scopeConfig;
protected $_objectManager;
protected $_customerFactory;


public function __construct(
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Framework\ObjectManagerInterface $objectManager,
\Magento\Customer\Model\CustomerFactory $customerFactory
)
{
    $this->_storeManager = $storeManager;
    $this->_scopeConfig = $scopeConfig;
    $this->_objectManager =  $objectManager;
    $this->_customerFactory = $customerFactory;
}

/**
 * Check Login.
 *
 * @api
 * @param string[] $data The array of strings to socialLogin.
 * @return $this
 */
public function socialLogin($data) {
    // json array for data should be {"data":{"email":"test@gmail.com","password":"password","type":"fb/gp","socialId":"","socialToken":"","firstName":"","lastName":"","dob":"","gender":""}}
    // type is used to identify social media facebook or google+
       if($data['type']=='fb'){
           // facbook login logic goes here
        }
       elseif($data['type']=='gp'){
           // google plus login logic goes here
       }
}
  • Any solution for login and create a customer account API for Facebook and Google ? – Kirti Nariya Sep 19 '19 at 12:53
  • Just use the above given method and then you can create customer programatically. – Prasanta Hatui Sep 30 '19 at 4:41
  • Have created for login Facebook and Google for Login and Registration Rest API? If you have done. could you please share the code ? So helpful for me. – Kirti Nariya Sep 30 '19 at 5:10
  • I have no access of code right now. You can post your issue what you have tried. – Prasanta Hatui Sep 30 '19 at 5:17
  • I have created as per your answer API and created simple function not added full code. But I can't able to identify in code where i am login in facebook or google. – Kirti Nariya Sep 30 '19 at 5:30
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.