ใช้การให้สิทธิ์ฝั่งเซิร์ฟเวอร์

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

ดูข้อมูลเพิ่มเติมเกี่ยวกับการใช้งาน Google OAuth 2.0 ฝั่งเซิร์ฟเวอร์ได้ที่การใช้ OAuth 2.0 สำหรับแอปพลิเคชันเว็บเซิร์ฟเวอร์

เนื้อหา

สร้างรหัสไคลเอ็นต์และรหัสลับไคลเอ็นต์

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

  1. จากหน้าข้อมูลเข้าสู่ระบบ ให้คลิกสร้างข้อมูลเข้าสู่ระบบ > รหัสไคลเอ็นต์ OAuth เพื่อสร้างข้อมูลเข้าสู่ระบบ OAuth 2.0 หรือสร้างข้อมูลเข้าสู่ระบบ > คีย์บัญชีบริการเพื่อสร้างบัญชีบริการ
  2. หากสร้างรหัสไคลเอ็นต์ OAuth ให้เลือกประเภทแอปพลิเคชัน
  3. กรอกแบบฟอร์มและคลิกสร้าง

ตอนนี้รหัสไคลเอ็นต์และคีย์บัญชีบริการของแอปพลิเคชันจะแสดงอยู่ในหน้าข้อมูลเข้าสู่ระบบแล้ว โปรดคลิกรหัสไคลเอ็นต์เพื่อดูรายละเอียด พารามิเตอร์จะแตกต่างกันไปขึ้นอยู่กับประเภทรหัส แต่อาจรวมถึงอีเมล รหัสลับไคลเอ็นต์ ต้นทาง JavaScript หรือ URI การเปลี่ยนเส้นทาง

จดรหัสไคลเอ็นต์ไว้ เพราะคุณจะต้องเพิ่มรหัสนี้ลงในโค้ดในภายหลัง

การจัดการคำขอการให้สิทธิ์

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

ตรวจสอบสิทธิ์ผู้ใช้

การลงชื่อเข้าใช้ครั้งแรกนี้จะแสดงออบเจ็กต์ผลลัพธ์การให้สิทธิ์ที่มีรหัสการให้สิทธิ์ หากดำเนินการสำเร็จ

แลกเปลี่ยนรหัสการให้สิทธิ์เป็นโทเค็นเพื่อการเข้าถึง

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

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

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

Python

แทนที่ค่า CLIENTSECRETS_LOCATION ด้วยตำแหน่งของไฟล์ client_secrets.json

import logging
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
from apiclient.discovery import build
# ...


# Path to client_secrets.json which should contain a JSON document such as:
#   {
#     "web": {
#       "client_id": "[[YOUR_CLIENT_ID]]",
#       "client_secret": "[[YOUR_CLIENT_SECRET]]",
#       "redirect_uris": [],
#       "auth_uri": "https://accounts.google.com/o/oauth2/auth",
#       "token_uri": "https://accounts.google.com/o/oauth2/token"
#     }
#   }
CLIENTSECRETS_LOCATION = '<PATH/TO/CLIENT_SECRETS.JSON>'
REDIRECT_URI = '<YOUR_REGISTERED_REDIRECT_URI>'
SCOPES = [
    'https://www.googleapis.com/auth/gmail.readonly',
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile',
    # Add other requested scopes.
]

class GetCredentialsException(Exception):
  """Error raised when an error occurred while retrieving credentials.

  Attributes:
    authorization_url: Authorization URL to redirect the user to in order to
                       request offline access.
  """

  def __init__(self, authorization_url):
    """Construct a GetCredentialsException."""
    self.authorization_url = authorization_url


class CodeExchangeException(GetCredentialsException):
  """Error raised when a code exchange has failed."""


class NoRefreshTokenException(GetCredentialsException):
  """Error raised when no refresh token has been found."""


class NoUserIdException(Exception):
  """Error raised when no user ID could be retrieved."""


def get_stored_credentials(user_id):
  """Retrieved stored credentials for the provided user ID.

  Args:
    user_id: User's ID.
  Returns:
    Stored oauth2client.client.OAuth2Credentials if found, None otherwise.
  Raises:
    NotImplemented: This function has not been implemented.
  """
  # TODO: Implement this function to work with your database.
  #       To instantiate an OAuth2Credentials instance from a Json
  #       representation, use the oauth2client.client.Credentials.new_from_json
  #       class method.
  raise NotImplementedError()


def store_credentials(user_id, credentials):
  """Store OAuth 2.0 credentials in the application's database.

  This function stores the provided OAuth 2.0 credentials using the user ID as
  key.

  Args:
    user_id: User's ID.
    credentials: OAuth 2.0 credentials to store.
  Raises:
    NotImplemented: This function has not been implemented.
  """
  # TODO: Implement this function to work with your database.
  #       To retrieve a Json representation of the credentials instance, call the
  #       credentials.to_json() method.
  raise NotImplementedError()


def exchange_code(authorization_code):
  """Exchange an authorization code for OAuth 2.0 credentials.

  Args:
    authorization_code: Authorization code to exchange for OAuth 2.0
                        credentials.
  Returns:
    oauth2client.client.OAuth2Credentials instance.
  Raises:
    CodeExchangeException: an error occurred.
  """
  flow = flow_from_clientsecrets(CLIENTSECRETS_LOCATION, ' '.join(SCOPES))
  flow.redirect_uri = REDIRECT_URI
  try:
    credentials = flow.step2_exchange(authorization_code)
    return credentials
  except FlowExchangeError, error:
    logging.error('An error occurred: %s', error)
    raise CodeExchangeException(None)


def get_user_info(credentials):
  """Send a request to the UserInfo API to retrieve the user's information.

  Args:
    credentials: oauth2client.client.OAuth2Credentials instance to authorize the
                 request.
  Returns:
    User information as a dict.
  """
  user_info_service = build(
      serviceName='oauth2', version='v2',
      http=credentials.authorize(httplib2.Http()))
  user_info = None
  try:
    user_info = user_info_service.userinfo().get().execute()
  except errors.HttpError, e:
    logging.error('An error occurred: %s', e)
  if user_info and user_info.get('id'):
    return user_info
  else:
    raise NoUserIdException()


def get_authorization_url(email_address, state):
  """Retrieve the authorization URL.

  Args:
    email_address: User's e-mail address.
    state: State for the authorization URL.
  Returns:
    Authorization URL to redirect the user to.
  """
  flow = flow_from_clientsecrets(CLIENTSECRETS_LOCATION, ' '.join(SCOPES))
  flow.params['access_type'] = 'offline'
  flow.params['approval_prompt'] = 'force'
  flow.params['user_id'] = email_address
  flow.params['state'] = state
  return flow.step1_get_authorize_url(REDIRECT_URI)


def get_credentials(authorization_code, state):
  """Retrieve credentials using the provided authorization code.

  This function exchanges the authorization code for an access token and queries
  the UserInfo API to retrieve the user's e-mail address.
  If a refresh token has been retrieved along with an access token, it is stored
  in the application database using the user's e-mail address as key.
  If no refresh token has been retrieved, the function checks in the application
  database for one and returns it if found or raises a NoRefreshTokenException
  with the authorization URL to redirect the user to.

  Args:
    authorization_code: Authorization code to use to retrieve an access token.
    state: State to set to the authorization URL in case of error.
  Returns:
    oauth2client.client.OAuth2Credentials instance containing an access and
    refresh token.
  Raises:
    CodeExchangeError: Could not exchange the authorization code.
    NoRefreshTokenException: No refresh token could be retrieved from the
                             available sources.
  """
  email_address = ''
  try:
    credentials = exchange_code(authorization_code)
    user_info = get_user_info(credentials)
    email_address = user_info.get('email')
    user_id = user_info.get('id')
    if credentials.refresh_token is not None:
      store_credentials(user_id, credentials)
      return credentials
    else:
      credentials = get_stored_credentials(user_id)
      if credentials and credentials.refresh_token is not None:
        return credentials
  except CodeExchangeException, error:
    logging.error('An error occurred during code exchange.')
    # Drive apps should try to retrieve the user and credentials for the current
    # session.
    # If none is available, redirect the user to the authorization URL.
    error.authorization_url = get_authorization_url(email_address, state)
    raise error
  except NoUserIdException:
    logging.error('No user ID could be retrieved.')
  # No refresh token has been retrieved.
  authorization_url = get_authorization_url(email_address, state)
  raise NoRefreshTokenException(authorization_url)

การให้สิทธิ์ด้วยข้อมูลเข้าสู่ระบบที่จัดเก็บไว้

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

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

การใช้ข้อมูลเข้าสู่ระบบ OAuth 2.0

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

สร้างอินสแตนซ์ออบเจ็กต์บริการ

ตัวอย่างโค้ดนี้แสดงวิธีสร้างอินสแตนซ์บริการออบเจ็กต์ จากนั้นให้สิทธิ์ออบเจ็กต์เพื่อสร้างคำขอ API

Python

from apiclient.discovery import build
# ...

def build_service(credentials):
  """Build a Gmail service object.

  Args:
    credentials: OAuth 2.0 credentials.

  Returns:
    Gmail service object.
  """
  http = httplib2.Http()
  http = credentials.authorize(http)
  return build('gmail', 'v1', http=http)

ส่งคำขอที่ได้รับอนุญาตและตรวจสอบข้อมูลเข้าสู่ระบบที่เพิกถอน

ข้อมูลโค้ดต่อไปนี้ใช้อินสแตนซ์บริการ Gmail ที่ได้รับอนุญาตเพื่อเรียกดูรายการข้อความ

หากเกิดข้อผิดพลาด โค้ดจะตรวจหารหัสสถานะ HTTP 401 ซึ่งควรจัดการโดยการเปลี่ยนเส้นทางผู้ใช้ไปยัง URL การให้สิทธิ์

การดำเนินการอื่นๆ ของ Gmail API บันทึกอยู่ในเอกสารอ้างอิง API

Python

from apiclient import errors
# ...

def ListMessages(service, user, query=''):
  """Gets a list of messages.

  Args:
    service: Authorized Gmail API service instance.
    user: The email address of the account.
    query: String used to filter messages returned.
           Eg.- 'label:UNREAD' for unread Messages only.

  Returns:
    List of messages that match the criteria of the query. Note that the
    returned list contains Message IDs, you must use get with the
    appropriate id to get the details of a Message.
  """
  try:
    response = service.users().messages().list(userId=user, q=query).execute()
    messages = response['messages']

    while 'nextPageToken' in response:
      page_token = response['nextPageToken']
      response = service.users().messages().list(userId=user, q=query,
                                         pageToken=page_token).execute()
      messages.extend(response['messages'])

    return messages
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
    if error.resp.status == 401:
      # Credentials have been revoked.
      # TODO: Redirect the user to the authorization URL.
      raise NotImplementedError()

ขั้นตอนถัดไป

เมื่อให้สิทธิ์คำขอ Gmail API แล้ว คุณก็พร้อมที่จะเริ่มจัดการข้อความ ชุดข้อความ และป้ายกำกับตามที่อธิบายไว้ในส่วน คู่มือนักพัฒนาซอฟต์แวร์

ดูข้อมูลเพิ่มเติมเกี่ยวกับเมธอด API ที่พร้อมใช้งานได้ในเอกสารอ้างอิง API