我已经创建了一个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进行交互。
答案 0 :(得分:0)
如果您只有OAuth访问令牌,则可以通过以下方式调用http GET 来查询有关用户的详细信息:
https://login.salesforce.com/services/oauth2/userinfo用于PROD或 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",
...
}
答案 1 :(得分:0)
在accessToken足够的地方,您不需要userId即可获取用户信息。我已经安装了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
});
});