我创建了一个Azure Web App Bot,并添加了一个OAuth连接设置,它将用户带到Salesforce。一切正常,我能够通过我的机器人对用户进行身份验证,而且,我可以从 Salesforce 获取访问令牌。
问题有人可以帮助我从Salesforce获取用户信息吗?因为,我能够单独获取访问令牌,但不确定如何从 Salesforce 获取用户 ID。
我写了下面的代码,
var salesforce = {};
salesforce.signin = (connector, session, callback) => {
builder.OAuthCard.create(connector,
session,
connectionName,
"Sign in to your Salesforce account",
"Sign in",
(createSignInErr, createSignInRes) => {
if (createSignInErr) {
callback({
status: 'failure',
data: createSignInErr.message
});
return;
}
callback({
status: 'success',
data: createSignInRes
});
});
};
salesforce.getUserToken = (connector, session, callback) => {
connector.getUserToken(session.message.address,
connectionName,
undefined,
(userTokenErr, userTokenResponse) => {
if (userTokenErr) {
callback({
status: 'failure',
data: userTokenErr.message
});
return;
}
callback({
status: 'success',
data: userTokenResponse
});
});
};
salesforce.accessToken = (connector, session, callback) => {
salesforce.getUserToken(connector, session, (userTokenResponse) => {
if (userTokenResponse.status == 'failure') {
// If the user token is failed, then trigger the sign in card to the user.
salesforce.signin(connector, session, (signinResponse) => {
// If the sign in is failed, then let the user know about it.
if (signinResponse.status == 'failure') {
session.send('Something went wrong, ', signinResponse.message);
return;
}
// If the sign in is success then get the user token and send it to the user.
salesforce.getUserToken(connector, session, (newUserTokenResponse) => {
if (newUserTokenResponse.status == 'failure') {
session.send('Something went wrong, ', newUserTokenResponse.message);
return;
}
callback(newUserTokenResponse);
return;
});
});
}
callback(userTokenResponse);
});
};
我可以在这里得到userTokenResponse
。但我需要 Salesforce 用户 ID,以便我可以代表用户开始与 Salesforce 交互。
如果您只有 OAuth 访问令牌,您可以通过对以下对象调用 httpGET来查询有关用户的详细信息:
https://login.salesforce.com/services/oauth2/userinfo 用于生产或 沙盒 https://test.salesforce.com/services/oauth2/userinfo
仅将Authorization: Bearer Y0UR0AUTHTOKEN
添加到 http GET 请求的标头中。
根据我最近的测试,从服务器返回的结果如下所示:
{
"sub": "https://test.salesforce.com/id/[organizationid]/[userId]",
"user_id": "000",
"organization_id": "000",
"preferred_username": "me@mycompany.com",
"nickname": "myNick",
"name": "name lastname",
"urls": {
...
},
"active": true,
"user_type": "STANDARD",
...
}
您不需要 userId 来获取用户信息,而 accessToken 就足够了。我已经安装了jsforce并使用以下代码来获取身份信息。
通过实践解决,
const jsforce = require('jsforce');
var connection = new jsforce.Connection({
instanceUrl: instanceUrl,
sessionId: accessToken
});
connection.identity((error, response) => {
if(error) {
callback({
status: 'failure',
message: error.message
});
return;
}
callback({
staus: 'success',
data: response
});
});