How to implement Weibo as Social Media Provider Login

download How to implement Weibo as Social Media Provider Login

of 6

Transcript of How to implement Weibo as Social Media Provider Login

  • 8/19/2019 How to implement Weibo as Social Media Provider Login

    1/13

    1.

    2.a.

    i.

    How-To: Integrate WeChat as Login Option insideMagento 2Briefly description about how I did the integration of both platforms.

    How-To: Integrate WeChat and Magento 2

    Company: TMOModule name: Customer.Description: It will override some functions of the core Customer Login class.

    Create the file structure for the new Company/Module

    Register new module.Create these 3 files:

    In the module : composer.json and registration.phproot folder

  • 8/19/2019 How to implement Weibo as Social Media Provider Login

    2/13

    ii.

    b.

    {

      "name": "tmo/customer",

      "description": "Add functions to Magento Customer Module",

      "require": {

      "php": "~5.5.0|~5.6.0|~7.0.0"

      },

      "type": "magento2-module",

      "version": "1.0.7",

      "license": [

      "OSL-3.0",

      "AFL-3.0"

      ],

      "autoload": {

      "files": [

      "registration.php"

      ],

      "psr-4": {

      "Tmo\\Customer\\": ""

      }

      }

    }

    In , module.xml:etcfolder

     

    Run a terminal inside php container:

    docker exec -ti asiamagento2_php-fpm_1 bash

    Then execute:

    bin/magento module:enable --clear-static-content Tmo_Customer

    composer.json

    registration.php

    module.xml

  • 8/19/2019 How to implement Weibo as Social Media Provider Login

    3/13

    3.

    a.

    4.a.

    To register and add the module to Magento 2.Define a Model to use as dropdown menu inside backend configuration.This menu defines button sizes.

    Create the file with the next content:Model/Config/Source/ButtonSize.php

  • 8/19/2019 How to implement Weibo as Social Media Provider Login

    4/13

    5.

    a.

     

     

     

      Social Login Options

     

      Size of social media login provider icons

      Tmo\Customer\Model\Config\Source\ButtonSize

     

     

      Use WeChat as Social Login

      Magento\Config\Model\Config\Source\Yesno

      Enables de customer to login using his existing WeChat

    account.

     

     

      Wechat APP ID*

     

      Wechat Secret*

     

      Token*

     

     

     

    Add custom customer attributes.The varchar fields "social_uid", "social_oid" and "social_username" must be added.

    Create the file example code:Setup/UpgradeData.php,

    system.xml

  • 8/19/2019 How to implement Weibo as Social Media Provider Login

    5/13

    b.

    c.

    d.

    6.

    $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

      $customerSetup->addAttribute(

      \Magento\Customer\Model\Customer::ENTITY,

      'social_oid',

      [

      'input'=>'text',

      'type'=>'varchar',

      'label'=>'Social OpenID',

      'visible'=>false,

      'required'=>false,

      'system'=>false,

      'position'=> 156

      ]

      );

      $customerSetup->getEavConfig()->getAttribute('customer', 'social_oid')

      ->setData('used_in_forms',

    ['customer_account_create','customer_account_edit','adminhtml_customer'])

      ->save();

    Modify the module version in the file etc/module.xml, increment it. This is to tell Magento there are changes inthe module and it needs to update itself.@PHP container terminal,check Magento database status, if it found changes it will show them:

    bin/magento setup:db:status

    The module code base doesn't match the DB schema and data.

      Tmo_Customer schema: 1.0.24 -> 1.0.25

    Tmo_Customer data: 1.0.24 -> 1.0.25

    Run 'setup:upgrade' to update your DB schema and data.

    Update Magento runing this code:

    bin/magento setup:upgrade

    Create provider class.This is an abstract class which defines common methods for all providers, for example methods to get configuration, anarray of all providers.Put that class in Model/Social/Login/Provider.php

    Example of UpgradeData.php

  • 8/19/2019 How to implement Weibo as Social Media Provider Login

    6/13

    abstract class Provider

      {

      const BUTTON_SMALL='small';

      const BUTTON_MEDIUM='medium';

      const BUTTON_LARGE='large';

      const BUTTON_DEFAULT=self::BUTTON_SMALL;

      const XML_PATH_SOCIAL_LOGIN_BUTTON='customer/sociallogin/social_login_button_style';

     

    public static $impl= [

      Providers\Wechat::TITLE=>Providers\Wechat::TYPE,

      Providers\Facebook::TITLE=>Providers\Facebook::TYPE,

      Providers\Weibo::TITLE=>Providers\Weibo::TYPE,

      Providers\Douban::TITLE=>Providers\Douban::TYPE

      ];

     

    public static $buttonStyles=[

      self::BUTTON_SMALL=>'Small',

      self::BUTTON_MEDIUM=>'Medium',

      self::BUTTON_LARGE=>'Large'

      ];

    Example #1 of Provider.php

  • 8/19/2019 How to implement Weibo as Social Media Provider Login

    7/13

    7.

    public function name()

      {

      return $this->m_name;

      }

     

    public function title()

      {

      return $this->m_title;

    }

     

    public function domain()

      {

      return $this->m_domain;

      }

     

    public function template()

      {

      return "tmo/customer/view/frontend/templates/{$this->m_name}.phtml";

      }

     

    public function isEnabled()

      {

      return

    1===(int)$this->_scopeConfig->getValue("customer/sociallogin/social_login_enabled_{$this->m_name}

    ");

      }

     

    public function appID()

      {

      return

    $this->_scopeConfig->getValue("customer/sociallogin/social_login_appid_{$this->m_name}");

      } 

    public function secretKey()

      {

      return

    $this->_scopeConfig->getValue("customer/sociallogin/social_login_secret_{$this->m_name}");

      }

     

    public function authorizationUrl()

      {

      return

    $this->_scopeConfig->getValue("customer/sociallogin/social_login_general_auth_url_{$this->m_name}

    ");

      }

    Create individual provider classesThese classes implements the particular workflow to get authorization to use the services of specific provider.Put them inModel/Social/Login/Providers/

    Example #2 of Provider.php

  • 8/19/2019 How to implement Weibo as Social Media Provider Login

    8/13

    8.a.

    public function login(array $data_)

      {

      $strOauthAccessTokenURL = $this->oauhAccessTokenUrl();

      $parameters['appid'] = $this->appID();

      $parameters['secret'] = $this->secretKey();

      $parameters['code'] = $data_['code'];

      $parameters['grant_type'] = 'authorization_code';

      $parameters['state'] = $data_['state'];

     

    if (!$contents=$this->http($strOauthAccessTokenURL,$parameters,'GET'))

      return null;

     

    $result=json_decode($contents, true);

      $openid = $result["openid"];

      $access_token = $result["access_token"];

     

    $strGetUserInfo = $this->userInfoUrl();

      $parameters = array();

      $parameters['access_token'] = $access_token;

      $parameters['openid'] = $openid;

      $parameters['state'] = $data_['state'];

     

    if (!$contents=$this->http($strGetUserInfo,$parameters,'GET'))

      return null;

     

    $result=json_decode($contents, true);

     

    if(false===isset($result["nickname"]))

      return null;

      ...

     ...

    Create template fileFor each provider enabled to show in login form, this classCreate the fileview/frontend/templates/providers.phtml.

    renders a button (of size previously defined) with an URL to the authorization service.

    Example of Wechat.php

  • 8/19/2019 How to implement Weibo as Social Media Provider Login

    9/13

    b.

    c.

     

      ">

     

  • 8/19/2019 How to implement Weibo as Social Media Provider Login

    10/13

    9.

    a.

     

     

      var appVersion = navigator.appVersion;

      var isWeChat = appVersion.indexOf("MicroMessenger");

      if(isWeChat < 0 ){

      var obj = new WxLogin({

      id:"login_container",

      appid: "wx9a4eb803e732bdec",

      scope: "snsapi_login",

      redirect_uri:"",

      state: "wechatqrcode",

      style: "black",

      href: ""

      });

      }

     

    This piece of code will show the QR code to scan and log in using WeChat account, only when user is not using theWeChat web browser.

    Create layout. This file will tell Magento when to open which template and which block class is the owner of thetemplate.

    Create fileview/frontend/layout/customer_account_login.xml. This file completely overrides the original core file.Copy the original content into it and add the following lines:

     

     

     

    Note that the blocks still define the original class but with different template.

    part of newcustomers.phtml

    parto of customer_account_login.xml

    part of customer_account_login.xml

    part of customer_account_login.xml

  • 8/19/2019 How to implement Weibo as Social Media Provider Login

    11/13

    10.a.

    11.

    a.

    Create a block to write the html code which render the social media providers.Create the file . This file will initialize all the properties required to render html toBlock/RenderProvider.phpthe screen using templates, and also provide all the functionality (constructors, methods, functions, etc) to thetemplate files.

    public function getUri($provider)

      {  $provider_name = $provider->name();

      switch($provider_name)

      {

      case 'wechat':

      $uri = $provider->authorizationUrl();

      $appID = $provider->appID();

      $redirect_uri =

    "http://magento2.asia/index.php/customer/account/login/provider/".$provider_name;

      $response_type = "code";

      $state = 'wechatbrowser';

      $scope = "snsapi_login";

      $uri .=

    "?appid=$appID&redirect_uri=$redirect_uri&response_type=$response_type&state=$state&scope=$scope";

    break;

      default:

      $uri = 'http://magento2.asia/index.php/customer/account/login/';

      break;

      }

      return $uri;

      }

    Create the plugin to override core login actions.A plugin is a new implementation of Magento 2 and it's defined to instead of re-write already defined class, add

    functionality before or after the execution of the original function OR completely override it.Create the fileetc/di.xml. This file defines what class will be overrided by what plugin class.

    Example of class RenderProvider.php

  • 8/19/2019 How to implement Weibo as Social Media Provider Login

    12/13

    b.

     

     

     

     

     

     

     

    This file also defines something new in Magento 2: "preferences". Briefly, this preferences tells to Magento "whenyou'll see string create an instance of this ", and basically they are used in the constructors forthis typesomething also new called I'll write about it in another article.automatic dependency injection,Create the fileController/Account/Plugin.php. This is finally the plugin class which implements all the previousdefined functions. The next diagram explains how this plugin works:

    di.xml

  • 8/19/2019 How to implement Weibo as Social Media Provider Login

    13/13

    The plugin will intercept the core functionality of login module, it will check if there is a CODE and a PROVIDERin the URL, if that's there plugin will get the configuration of the provider, will try to connect to theauthorization service to get the user information, will check if the user already exists, if it does will redirectit to the dashboard but if it doesn't will register it into the database, and the redirect it to its dashboard.

    Related articles

    How-To: WeChat as Social Login (Part 1)How-To: Wechat as Social Login (Part 2)

    http://co.tmogroup.asia/pages/viewpage.action?pageId=7997197http://co.tmogroup.asia/pages/viewpage.action?pageId=7997248http://co.tmogroup.asia/pages/viewpage.action?pageId=7997248http://co.tmogroup.asia/pages/viewpage.action?pageId=7997197