无法在C#中连接到SalesForce

时间:2013-07-26 16:33:44

标签: c# api salesforce salesforce-service-cloud

我正在关注本教程http://wiki.developerforce.com/page/Integrating_Force.com_with_Microsoft_.NET

但是,我收到此错误:

  

LOGIN_MUST_USE_SECURITY_TOKEN:用户名,密码,安全性无效   令牌;或用户被锁定。你在新的位置吗?访问时   Salesforce - 通过桌面客户端或API - 来自外部   贵公司的可信网络,您必须为您的公司添加安全令牌   要登录的密码。要接收新的安全令牌,请登录   salesforce.com在http://login.salesforce.com,然后单击设置|我的   个人信息|重置安全令牌。

这是我的控制台应用程序中的代码:

static void Main(string[] args)
        {
            string userName;
            string password;
            userName = "me@myWebsite.com";
            password = "myPassword";

            SforceService SfdcBinding = null;
            LoginResult CurrentLoginResult = null;
            SfdcBinding = new SforceService();
            try
            {
                CurrentLoginResult = SfdcBinding.login(userName, password);
            }
            catch (System.Web.Services.Protocols.SoapException e)
            {
                // This is likley to be caused by bad username or password
                SfdcBinding = null;
                throw (e);
            }
            catch (Exception e)
            {
                // This is something else, probably comminication
                SfdcBinding = null;
                throw (e);
            }

        }

错误说明我需要一个安全令牌,但文档似乎从未提及它,我不知道如何获得它。

2 个答案:

答案 0 :(得分:7)

我必须做的事情(文档中没有)是这里:

https://na15.salesforce.com/_ui/system/security/ResetApiTokenConfirm?retURL=%2Fui%2Fsetup%2FSetup%3Fsetupid%3DPersonalInfo&setupid=ResetApiToken

然后,重置我的令牌。然后,将其附加到我的密码末尾,如:

  

如果您的密码=“mypassword”

     

您的安全令牌=“XXXXXXXXXX”

     

您必须输入“mypasswordXXXXXXXXXX”代替密码

参考。 http://docs.servicerocket.com/pages/viewpage.action?pageId=83099770

答案 1 :(得分:2)

使用这样的SOAP API,您需要首先通过提供用户名和密码来验证服务。他们的回复应该返回一段有效期为一段时间的授权令牌。然后在随后的通信中,您将此令牌传递给API,以便它知道您是谁。

获取授权令牌:

SforceService SfdcBinding = null;
LoginResult CurrentLoginResult = null;
SfdcBinding = new SforceService();
try 
{
   CurrentLoginResult = SfdcBinding.login(userName, password);
}
catch (System.Web.Services.Protocols.SoapException e) 
{
   // This is likely to be caused by bad username or password
   SfdcBinding = null;
   throw (e);
}
catch (Exception e) 
{
   // This is something else, probably communication
   SfdcBinding = null;
   throw (e);
}

设置会话:

//Change the binding to the new endpoint
SfdcBinding.Url = CurrentLoginResult.serverUrl;

//Create a new session header object and set the session id to that returned by the login
SfdcBinding.SessionHeaderValue = new SessionHeader();
SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId;

执行查询:

QueryResult queryResult = null;
String SOQL = "select FirstName, LastName, Phone from Lead where email = 'john.smith@salesforce.com'";
queryResult = SfdcBinding.query(SOQL);