如何用PHP通过Service Account创建并共享Google Sheet?
使用Service Account创建并共享Google Sheets(全程无需用户授权)
前提准备
确保已安装所需依赖包:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
同时拥有有效的Service Account密钥文件(JSON格式),并已启用Google Sheets API和Google Drive API。
1. 创建新的Google Sheet
通过Sheets API直接创建,全程由Service Account完成,无需用户授权:
from google.oauth2 import service_account from googleapiclient.discovery import build # 加载Service Account密钥 SERVICE_ACCOUNT_FILE = 'path/to/your/service-account-key.json' # 声明所需权限:创建Sheet + 管理Drive权限 SCOPES = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'] credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) # 初始化Sheets API客户端 sheets_service = build('sheets', 'v4', credentials=credentials) # 定义Sheet基础属性 spreadsheet_body = { 'properties': { 'title': '自定义Sheet标题' } } # 发送创建请求 response = sheets_service.spreadsheets().create( body=spreadsheet_body, fields='spreadsheetId' ).execute() spreadsheet_id = response.get('spreadsheetId') sheet_access_url = f"https://docs.google.com/spreadsheets/d/{spreadsheet_id}/edit" print(f"新Sheet ID: {spreadsheet_id}") print(f"直接访问链接: {sheet_access_url}")
2. 共享给指定用户
利用Drive API管理文件权限,直接给目标邮箱添加访问权限:
# 初始化Drive API客户端 drive_service = build('drive', 'v3', credentials=credentials) # 配置共享参数 permission_settings = { 'type': 'user', 'role': 'writer', # 可选权限:reader/owner 'emailAddress': 'target-user@example.com' # 目标用户邮箱 } # 添加共享权限 drive_service.permissions().create( fileId=spreadsheet_id, body=permission_settings, sendNotificationEmail=True # 是否给用户发送共享通知邮件,可设为False关闭 ).execute() print(f"已成功共享给 {permission_settings['emailAddress']}")
关键注意事项
- Service Account创建的Sheet默认由该账号拥有,因此有权直接修改其共享权限
- 若无需发送通知邮件,将
sendNotificationEmail设为False即可 - 生成的
sheet_access_url在完成共享后,目标用户可直接打开访问
内容的提问来源于stack exchange,提问作者StripyTiger
相关产品推荐
相关产品推荐

