如何在注册过程中获取多个谷歌凭据(Gmail API、Pub/Sub、联系人)

Posted

技术标签:

【中文标题】如何在注册过程中获取多个谷歌凭据(Gmail API、Pub/Sub、联系人)【英文标题】:How to get multiple google credentials (Gmail API, Pub/Sub, Contacts) during signup process 【发布时间】:2018-09-21 08:54:30 【问题描述】:

我正在开发一个基于 Python 的项目,该项目可以访问各种 Google API,例如 Google Contacts API、Pub/Sub API、Gmail API 等。

目前,通过 Google API 控制台使用 OAuth 2.0 为这些 API 获取相关令牌和凭据是高度手动的。对于愿意让我通过上述 API(不仅仅是 Gmail API)管理他们的 gmail 邮箱的多个用户,我想自动执行此操作。

如何在注册过程中获取所有这些 API 的凭据,以便我可以将凭据 json 文件保存在 db 中,然后管理邮箱? “使用 Google 注册”功能仅生成一个基本凭据,我无法弄清楚如何将用户路由到相关页面,在该页面中我请求他/她允许使用 API(Google 联系人、Gmail 和发布/订阅 API)。然后我打算以编程方式在我的 Python 脚本中使用这个凭据(对象)..

这是我通过 get_credentials() 创建凭据的脚本。如您所见,我首先需要在 API 控制台上手动获取 client-secret-file,然后使用以下脚本生成凭证 wrt 范围(这是我需要在注册过程中自动化并获取其他几个凭证的地方)

SCOPES = 'https://www.googleapis.com/auth/gmail.modify'
CLIENT_SECRET_FILE = "client_secret_pubsub.json"
APPLICATION_NAME = "pub-sub-project-te"

def get_credentials():
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
    os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
                               'gmail-python-quickstart.json')

store = oauth2client.file.Storage(credential_path)

credentials = store.get()
if not credentials or credentials.invalid:
    flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
    flow.user_agent = APPLICATION_NAME
    print('Storing credentials to ' + credential_path)
return credentials


def pull_emails_from_mailbox(credentials_obj):

credentials = get_credentials()

http = credentials.authorize(Http())

GMAIL=discovery.build('gmail', 'v1', http=http)

user_id =  'me'
label_id_one = 'INBOX'
label_id_two = 'UNREAD'

# Getting all the unread messages from Inbox
# labelIds can be changed accordingly
messages = GMAIL.users().messages().list(userId=user_id, maxResults=1000).execute()
#unread_msgs = GMAIL.users().messages().list(userId='me',labelIds=[label_id_one,label_id_two]).execute()

# We get a dictonary. Now reading values for the key 'messages'

mssg_list = messages['messages']

print ("Total messages in inbox: ", str(len(mssg_list)))

final_list = []

new_messages=[]
for mssg in mssg_list:
    m_id = mssg['id'] # get id of individual message
    new_messages.append(GMAIL.users().messages().get(userId=user_id, id=m_id).execute()) # fetch the message using API

return new_messages


def prepare_raw_db (raw_messages):

messageId=[]
historyId=[]
raw=[]

print ("Total number of emails to be parsed:", len(raw_messages))

for msg in raw_messages:
    messageId.append(msg["id"])
    historyId.append(msg['historyId'])
    raw.append(msg)

        #'addLabelIds': ['UNREAD']
    GMAIL.users().messages().modify(userId="me", id=msg["id"],body= 'removeLabelIds': ['UNREAD'] ).execute() 

msg_dict="messageId":messageId, "historyId":historyId, "raw":raw

df=pd.DataFrame(msg_dict)

df.raw=df.raw.astype(str)

return df

谢谢

【问题讨论】:

你到底想用 PubSub API 做什么? 【参考方案1】:

你必须让网络服务器做同样的事情。流程将遵循 -

    用户访问您的网络应用程序。 用户点击使用 Google 登录。 用户将被重定向到具有所需范围的 Goole OAuth2 url(在您的情况下,它是 Google Contacts API、Pub/Sub API、Gmail API 等) 用户将授予对在 Google 开发者控制台上创建的您的应用程序的访问权限。 它将根据 OAuth2 请求返回具有所需访问权限的应用程序的令牌/代码。 您可以将其存储在某个数据库中,并可以按照 OAuth2 使用它。

上面的过程是一步一步给出的here。

【讨论】:

Thx Vivek.. 我已经尝试过这种方法,并且仍在尝试在 Python 中使用 API。一旦完成,我会在这里更新.. 再次感谢【参考方案2】:

让你的范围成为一个列表,然后像这样添加它们,例如

SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/spreadsheets']

这对我有用,所以我希望它有所帮助

【讨论】:

以上是关于如何在注册过程中获取多个谷歌凭据(Gmail API、Pub/Sub、联系人)的主要内容,如果未能解决你的问题,请参考以下文章

需要让用户使用多个凭据登录,与使用 Gmail 服务中的其他帐户功能登录相同 - Laravel

Google(gmail)如何在出发前了解航班详情

有没有使用谷歌注册安卓集成获取用户密码的方法

Google OAuth 登录错误:凭据无效

Gmail 的 XOAuth2 错误凭据无效

注册gmail邮箱-谷歌邮箱-谷歌帐号时遭遇“此电话号码无法用于进行验证”的解决方法