ใช้งาน OAuth กับ API ของ Business Profile

คำขอทุกรายการที่แอปพลิเคชันส่งไปยัง Business Profile API ต้องมีโทเค็นการให้สิทธิ์ โทเค็นการให้สิทธิ์จะระบุผู้ใช้หรือแอปพลิเคชันไปยัง Google ซึ่งอนุญาตการเข้าถึง API ของ Business Profile แอปพลิเคชันต้องใช้โปรโตคอล OAuth 2.0 เพื่อให้สิทธิ์คำขอ

คู่มือนี้จะอธิบายถึงวิธีต่างๆ ที่คุณจะใช้เพื่อติดตั้งใช้งาน OAuth 2.0 บนแพลตฟอร์มได้ Google Identity Platform มีฟังก์ชัน Google Sign-In และ OAuth ที่ใช้ในคู่มือนี้

โปรดอ่านคำแนะนำที่นี่เพื่อทำความเข้าใจวิธีใช้ Oauth 2.0 สำหรับแอปพลิเคชันเว็บเซิร์ฟเวอร์

การใช้งาน OAuth 2.0 มีข้อดีดังนี้

  • ปกป้องสิทธิ์เข้าถึงข้อมูลของเจ้าของธุรกิจ
  • สร้างข้อมูลประจำตัวของเจ้าของธุรกิจเมื่อลงชื่อเข้าใช้บัญชี Google
  • กำหนดว่าแพลตฟอร์มหรือแอปพลิเคชันของพาร์ทเนอร์จะเข้าถึงและแก้ไขข้อมูลตำแหน่งได้โดยต้องได้รับความยินยอมอย่างชัดแจ้งจากเจ้าของธุรกิจ เจ้าของสามารถ เพิกถอนการเข้าถึงนี้ได้ในภายหลัง
  • สร้างเอกลักษณ์ของแพลตฟอร์มพาร์ทเนอร์
  • ช่วยให้แพลตฟอร์มของพาร์ทเนอร์สามารถดำเนินการทางออนไลน์หรือออฟไลน์ในนามของเจ้าของธุรกิจ ซึ่งรวมถึงการตอบรีวิว การสร้างโพสต์ และการอัปเดตรายการในเมนู

การเข้าถึง API ด้วย OAuth 2.0

ก่อนเริ่มต้น คุณต้องกำหนดค่าโปรเจ็กต์ Google Cloud และเปิดใช้ API ของ Business Profile สำหรับข้อมูลเพิ่มเติม โปรดดูเอกสารสำหรับการตั้งค่าพื้นฐาน

ทําตามขั้นตอนต่อไปนี้เพื่อสร้างข้อมูลเข้าสู่ระบบและหน้าจอขอความยินยอม

  1. จากหน้าข้อมูลเข้าสู่ระบบในคอนโซล API ให้คลิกสร้างข้อมูลเข้าสู่ระบบ และเลือก "รหัสไคลเอ็นต์ OAuth" จากรายการแบบเลื่อนลง
  2. เลือกประเภทแอปพลิเคชัน กรอกข้อมูลที่เกี่ยวข้อง แล้วคลิกสร้าง
  3. คลิกบันทึก
  4. อัปเดตการตั้งค่าหน้าจอขอความยินยอม OAuth จากตรงนั้น คุณสามารถอัปเดตชื่อแอปพลิเคชันและโลโก้ รวมถึงลิงก์ไปยังข้อกำหนดในการให้บริการและนโยบายความเป็นส่วนตัวของคุณ

รูปภาพต่อไปนี้แสดงช่องชื่อแอปพลิเคชันและโลโก้ในหน้าจอคำยินยอม OAuth

รูปภาพต่อไปนี้แสดงช่องเพิ่มเติมที่ปรากฏบนหน้าจอคำยินยอม OAuth

รูปภาพต่อไปนี้คือตัวอย่างสิ่งที่ผู้ใช้อาจเห็นก่อนให้ความยินยอม

วิธีการรวม OAuth 2.0

คุณติดตั้งใช้งาน OAuth 2.0 ได้โดยใช้วิธีต่อไปนี้

เนื้อหาต่อไปนี้มีข้อมูลเกี่ยวกับวิธีการเหล่านี้เพื่อผสานรวม OAuth 2.0 เข้ากับแอปพลิเคชัน

ขอบเขตการให้สิทธิ์

ต้องมีขอบเขต OAuth อย่างใดอย่างหนึ่งต่อไปนี้

  • https://www.googleapis.com/auth/business.manage
  • https://www.googleapis.com/auth/plus.business.manage

ขอบเขต Plus.business.manage เลิกใช้งานแล้วและพร้อมให้รักษาความเข้ากันได้ย้อนหลังสำหรับการติดตั้งใช้งานที่มีอยู่

ไลบรารีของไคลเอ็นต์

ตัวอย่างที่เจาะจงภาษาในหน้านี้ใช้ไลบรารีของไคลเอ็นต์ Google API เพื่อใช้การให้สิทธิ์ OAuth 2.0 หากต้องการเรียกใช้ตัวอย่างโค้ด ก่อนอื่นคุณต้องติดตั้งไลบรารีไคลเอ็นต์สำหรับภาษาของคุณ

ไลบรารีของไคลเอ็นต์พร้อมให้บริการสำหรับภาษาต่อไปนี้

Google Sign-In

Google Sign-In เป็นวิธีที่รวดเร็วที่สุดในการผสานรวม OAuth กับแพลตฟอร์ม มีให้บริการสำหรับ Android, iOS, เว็บ และอีกมากมาย

Google Sign-In เป็นระบบการตรวจสอบสิทธิ์ที่มีความปลอดภัย ซึ่งช่วยให้ผู้ใช้ลงชื่อเข้าใช้ด้วยบัญชี Google ซึ่งเป็นบัญชีเดียวกับที่ใช้ลงชื่อเข้าใช้บริการอื่นๆ ของ Google เมื่อลงชื่อเข้าใช้แล้ว ผู้ใช้จะยินยอมให้แอปพลิเคชันเรียกใช้ Business Profile API และแลกเปลี่ยนรหัสการให้สิทธิ์ที่ใช้รับโทเค็นการรีเฟรชและเข้าถึงโทเค็น

การเข้าถึงแบบออฟไลน์

คุณอาจต้องเรียกใช้ Business Profile API ในนามของผู้ใช้แม้ว่าผู้ใช้จะออฟไลน์อยู่ก็ตาม เราแนะนำให้แพลตฟอร์มรวมฟังก์ชันการทำงานนี้ไว้ด้วย เนื่องจากคุณจะแก้ไข ดู และจัดการข้อมูลได้ทุกเมื่อหลังจากที่ผู้ใช้ลงชื่อเข้าใช้และให้ความยินยอมแล้ว

Google จะถือว่าผู้ใช้ลงชื่อเข้าใช้ด้วยบัญชี Google แล้ว และได้ยินยอมให้แอปพลิเคชันเรียก Business Profile API และแลกเปลี่ยนรหัสการให้สิทธิ์ที่ใช้กันหลังจากนั้นเพื่อรับโทเค็นการรีเฟรช และหลังจากนั้นเป็นโทเค็นเพื่อการเข้าถึง ผู้ใช้สามารถจัดเก็บโทเค็นการรีเฟรชได้อย่างปลอดภัย และนำไปใช้รับโทเค็นเพื่อการเข้าถึงใหม่ได้ทุกเมื่อ โปรดอ่านข้อมูลเพิ่มเติมที่ Google Sign-In สำหรับแอปฝั่งเซิร์ฟเวอร์

ข้อมูลโค้ดต่อไปนี้จะแสดงวิธีใช้การเข้าถึงแบบออฟไลน์ในแอปพลิเคชันของคุณ หากต้องการเรียกใช้โค้ดนี้ โปรดดูเรียกใช้ตัวอย่าง

<!-- The top of file index.html -->
<html itemscope itemtype="http://schema.org/Article">
<head>
  <!-- BEGIN Pre-requisites -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
  </script>
  <script src="https://apis.google.com/js/client:platform.js?onload=start" async defer>
  </script>
  <!-- END Pre-requisites -->
<!-- Continuing the <head> section -->
  <script>
    function start() {
      gapi.load('auth2', function() {
        auth2 = gapi.auth2.init({
          client_id: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
          // Scopes to request in addition to 'profile' and 'email'
          scope: 'https://www.googleapis.com/auth/business.manage',
          immediate: true
        });
      });
    }
  </script>
</head>
<body>
  <!-- Add where you want your sign-in button to render -->
<!-- Use an image that follows the branding guidelines in a real app, more info here:
 https://developers.google.com/identity/branding-guidelines
-->
<h1>Business Profile Offline Access Demo</h1>

<p> This demo demonstrates the use of Google Identity Services and OAuth to gain authorization to call the Business Profile APIs on behalf of the user, even when the user is offline.

When a refresh token is acquired, store this token securely on your database. You will then be able to use this token to refresh the OAuth credentials and make offline API calls on behalf of the user. 

The user may revoke access at any time from the <a href='https://myaccount.google.com/permissions'>Account Settings</a> page.
</p>

<button id="signinButton">Sign in with Google</button><br>
<input id="authorizationCode" type="text" placeholder="Authorization Code" style="width: 60%"><button id="accessTokenButton" disabled>Retrieve Access/Refresh Token</button><br>
 <input id="refreshToken" type="text" placeholder="Refresh Token, never expires unless revoked" style="width: 60%"><button id="refreshSubmit">Refresh Access Token</button><br>
 <input id="accessToken" type="text" placeholder="Access Token" style="width: 60%"><button id="gmbAccounts">Get Business Profile Accounts</button><br>
 <p>API Responses:</p>
<script>
    //Will be populated after sign in.
    var authCode;
  $('#signinButton').click(function() {
    // signInCallback
    auth2.grantOfflineAccess().then(signInCallback);
  });

  $('#accessTokenButton').click(function() {
    // signInCallback defined in step 6.
    retrieveAccessTokenAndRefreshToken(authCode);
  });

  $('#refreshSubmit').click(function() {
    // signInCallback defined in step 6.
    retrieveAccessTokenFromRefreshToken($('#refreshToken').val());
  });

   $('#gmbAccounts').click(function() {
    // signInCallback defined in step 6.
    retrieveGoogleMyBusinessAccounts($('#accessToken').val());
  });




function signInCallback(authResult) {
    //the 'code' field from the response, used to retrieve access token and bearer token
  if (authResult['code']) {
    // Hide the sign-in button now that the user is authorized, for example:
    $('#signinButton').attr('style', 'display: none');
    authCode = authResult['code'];

    $("#accessTokenButton").attr( "disabled", false );

    //Pretty print response
    var e = document.createElement("pre")
    e.innerHTML = JSON.stringify(authResult, undefined, 2);
    document.body.appendChild(e);

    //autofill authorization code input
    $('#authorizationCode').val(authResult['code'])

    
  } else {
    // There was an error.
  }
}

//WARNING: THIS FUNCTION IS DISPLAYED FOR DEMONSTRATION PURPOSES ONLY. YOUR CLIENT_SECRET SHOULD NEVER BE EXPOSED ON THE CLIENT SIDE!!!!
function retrieveAccessTokenAndRefreshToken(code) {
      $.post('https://www.googleapis.com/oauth2/v4/token',
      { //the headers passed in the request
        'code' : code,
        'client_id' : 'YOUR_CLIENT_ID.apps.googleusercontent.com',
        'client_secret' : 'YOUR_CLIENT_SECRET',
        'redirect_uri' : 'http://localhost:8000',
        'grant_type' : 'authorization_code'
      },
      function(returnedData) {
        console.log(returnedData);
        //pretty print JSON response
        var e = document.createElement("pre")
        e.innerHTML = JSON.stringify(returnedData, undefined, 2);
        document.body.appendChild(e);
        $('#refreshToken').val(returnedData['refresh_token'])
      });
}

//WARNING: THIS FUNCTION IS DISPLAYED FOR DEMONSTRATION PURPOSES ONLY. YOUR CLIENT_SECRET SHOULD NEVER BE EXPOSED ON THE CLIENT SIDE!!!!
function retrieveAccessTokenFromRefreshToken(refreshToken) {
    $.post('https://www.googleapis.com/oauth2/v4/token', 
        { // the headers passed in the request
        'refresh_token' : refreshToken,
        'client_id' : 'YOUR_CLIENT_ID.apps.googleusercontent.com',
        'client_secret' : 'YOUR_CLIENT_SECRET',
        'redirect_uri' : 'http://localhost:8000',
        'grant_type' : 'refresh_token'
      },
      function(returnedData) {
        var e = document.createElement("pre")
        e.innerHTML = JSON.stringify(returnedData, undefined, 2);
        document.body.appendChild(e);
        $('#accessToken').val(returnedData['access_token'])
      });
}

function retrieveGoogleMyBusinessAccounts(accessToken) {
    $.ajax({
        type: 'GET',
        url: 'https://mybusinessaccountmanagement.googleapis.com/v1/accounts',
        headers: {
            'Authorization' : 'Bearer ' + accessToken
        },
        success: function(returnedData) {
            var e = document.createElement("pre")
            e.innerHTML = JSON.stringify(returnedData, undefined, 2);
            document.body.appendChild(e);
        }
    });
}
</script>
</body>
</html>

การเข้าถึงออนไลน์เท่านั้น

เพื่อการใช้งานที่ง่าย การเรียกใช้จาก Business Profile API อาจทำได้โดยไม่ต้องแคชโทเค็นการรีเฟรชของผู้ใช้ อย่างไรก็ตาม ผู้ใช้ต้องลงชื่อเข้าใช้แพลตฟอร์ม เพื่อทำการเรียก API ในฐานะผู้ใช้

ข้อมูลโค้ดต่อไปนี้แสดงการใช้งานกระบวนการลงชื่อเข้าใช้ของ Google และวิธีเรียก API ที่เจาะจงผู้ใช้ หลังจากที่ผู้ใช้ลงชื่อเข้าใช้ด้วยบัญชี Google ของตนและให้ความยินยอมสำหรับแอปพลิเคชันของคุณแล้ว ระบบจะให้สิทธิ์โทเค็นเพื่อการเข้าถึง โทเค็นเพื่อการเข้าถึงนี้จะระบุตัวตนผู้ใช้และจําเป็นต้องส่งเป็นส่วนหัวในคำขอ Business Profile API

หากต้องการเรียกใช้โค้ดนี้ โปรดดูเรียกใช้ตัวอย่าง

<!-- The top of file index.html -->
<html lang="en">
  <head>
    <meta name="google-signin-scope" content="profile email https://www.googleapis.com/auth/business.manage">
    <meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
    <script src="https://apis.google.com/js/platform.js" async defer></script>
  </head>
  <body>
    <div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
    <script>
      var gmb_api_version = 'https://mybusinessaccountmanagement.googleapis.com/v1';
      function onSignIn(googleUser) {
        // Useful data for your client-side scripts:
        var profile = googleUser.getBasicProfile();
        console.log('Full Name: ' + profile.getName());
        console.log("Email: " + profile.getEmail());
        var access_token = googleUser.getAuthResponse().access_token;

        //Using the sign in data to make a Business Profile APIs call
        var req = gmb_api_version + '/accounts';
        var xhr = new XMLHttpRequest();
        xhr.open('GET', req);
        xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);

        //Displaying the API response
        xhr.onload = function () {
          document.body.appendChild(document.createTextNode(xhr.responseText));
        }
        xhr.send();
      }
    </script>
  </body>
</html>

เรียกใช้ตัวอย่าง

ทำตามขั้นตอนต่อไปนี้เพื่อเรียกใช้โค้ดตัวอย่างที่ให้ไว้

  1. บันทึกข้อมูลโค้ดลงในไฟล์ชื่อ index.html ตรวจสอบว่าคุณได้ตั้งค่ารหัสไคลเอ็นต์ในไฟล์แล้ว
  2. เริ่มต้นเว็บเซิร์ฟเวอร์ด้วยคำสั่งต่อไปนี้จากไดเรกทอรีการทำงาน:

    Python 2.X

    python -m SimpleHTTPServer 8000

    Python 3.X

    python -m http.server 8000
  3. จากหน้าข้อมูลเข้าสู่ระบบในคอนโซล API ให้เลือกรหัสไคลเอ็นต์ที่ใช้

  4. ป้อน URL ของเว็บไซต์ในช่องต้นทาง JavaScript ที่ได้รับอนุญาต หากต้องการเรียกใช้โค้ดตัวอย่างในคู่มือนี้ คุณต้องเพิ่ม http://localhost:8000 ด้วย

  5. โหลด URL ต่อไปนี้ในเบราว์เซอร์

    http://localhost:8000/index.html