EN IT
Open2b version 7.8

Facebook login

Open2b allows store customers to log in, and optionally sign up, using their Facebook account. Below is how to add a button on the login page to enable this feature.

Before you proceed

Changing template source code requires some knowledge of HTML, CSS, and JavaScript.

Before you proceed

You must have already created a Facebook app enabled for login and for the JavaScript SDK, with advanced permissions to access the public profile and email address. The app verification process must be completed.
You can consult the Facebook documentation for details.

Add the Log in with Facebook button

  1. Go to the Website section of the back office.
  2. Go to the Design subsection.
  3. Click Customize next to the template to modify. The Template Editor will open.
  4. Click HTML and CSS.
  5. Click the New > Empty file menu.
  6. Paste the following code into the file
    {
      "version": 8,
      "methods": ["loginWith", "signUp"]
    }
  7. From the Save... menu at the top, select Save As... to save the file.
  8. Save the file with the name storefront.json.
  9. Click the New > Empty file menu.
  10. Paste the following code into the file
    
    {##
      The FacebookLogin macro shows the "Log in with Facebook" button where it is called.
      If the customer has never authorized Facebook login for the site, confirmation will be requested,
      otherwise the customer will be logged in directly.
      If no customer is registered in the store with the email provided by Facebook, the customer will be
      registered. First name, last name and email will be taken from Facebook, while placeholder data
      will be entered for the other required registration fields.
    ##}
    
    {% macro FacebookLogin(appID string, consents []int) %}
    {% if ! isLoggedIn %}
      {% serializedConsents, _ := marshalJSON(consents) %}
      <div class="fb-login-button" data-width="" data-size="large" data-button-type="login_with" data-layout="default" data-auto-logout-link="false" data-use-continue-as="false"></div>
      <script type="text/javascript">
        window.fbAsyncInit = function() {
          FB.init({
            appId  : {{ appID }},
            cookie : true,
            xfbml  : true,
            version: 'v13.0'
          });
          FB.getLoginStatus(function(response) {
            statusChangeCallback(response);
          });
        };
    
        function statusChangeCallback(response) {
          var redirectURL = document.location.href.replace(/\/[^\/]*$/,'/');
          if (response.status === 'connected') {
            Open2b.Storefront.loginWith('Facebook',{ 'id': response.authResponse.userID , 'token': response.authResponse.accessToken}).then(function (response) {
                document.location = redirectURL;
            }).catch(function(error){
              if ( error.message === '(credentials NotFound) There is no customer for these credentials' ) {
                // The customer is not registered; we can register them using the storefront API, so we need to fetch their data from Facebook.
                FB.api('/me?fields=first_name,last_name,email', function(response) {
                  var customer = {
                    address: {
                      firstName: response.first_name,
                      lastName: response.last_name,
                      street1: "N.D.",
                      city: "N.D.",
                      postalCode: "56100",
                      stateProv: "PI",
                      country: "IT",
                      email: response.email,
                    },
                    privacyConsents: {{ serializedConsents }},
                    password: _generatePassword(10)
                  };
                  Open2b.Storefront.signUp(customer).then(function() {
                    document.location = redirectURL + 'user-data';
                  }).catch(function(){
                    alert("It was not possible to log in with Facebook; please use the standard login.")
                  });
                });
              } else {
                alert("It was not possible to log in with Facebook; please use the standard login.")
              }
            });
          }
        }
        function _generatePassword(length) {
          var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!\\$%&/()=?^,.;:-<>#'|[]{}@_";
          var password = "";
          var array = new Uint32Array(1);
          for ( var i = 0; i < length; i++ ) {
            crypto.getRandomValues(array);
            password += chars[array[0]%chars.length];
          }
          return password;
        }
      </script>
      <div id="fb-root"></div>
      <script async defer crossorigin="anonymous" src="https://connect.facebook.net/{{language.Code}}_{{language.Region}}/sdk.js"></script>
    {% end if %}
    {% end macro %}
  11. From the Save... menu at the top, select Save As... to save the file.
  12. Save the file with the name login-with-facebook.html, in the /imports folder.
  13. Click the login.html file. The file source will open in the center of the page.
  14. Find the following line:
    {% extends "layouts/standard.html" %}
    and immediately after insert a new line with the following code
    {% import "imports/login-with-facebook.html" %}
  15. Find the following line:
    <p class="sign-up"><a href="sign-up.html" title="{{ translate(`Sign up`) }}">{{ translate("Sign up") }}</a></p>
    and immediately after paste the following code:
    {{ FacebookLogin("386761733020509", []int{ 6, 7 }) }}
    replacing 386761733020509 with your Facebook app ID and replacing 6, 7 with the IDs of your mandatory registrations consents, separated by a comma.
  16. From the Save... menu at the top, select Save to save the file.
  17. Click css and then base.css. The file source will open in the center of the page.
  18. Add the following code at the end of the file
    .fb-login-button.fb_iframe_widget { display: block; margin-top: 1em; text-align: center; }
  19. From the Save... menu at the top, select Save to save the file.
  20. Click the monitor icon at the top left.
  21. Go to the login page and verify it looks correct.
  22. Click Save at the bottom left.
  23. Click Apply.