Salesforce php REST API 自动登录

6
我现在正在为此问题烦恼。我已经按照以下示例进行了操作:http://developer.force.com/cookbook/recipe/interact-with-the-forcecom-rest-api-from-php,但是这里的用户被发送到登录表单并需要登录。相反,我想在我的代码中发布这些数据,而不是让用户登录,而是让我的应用程序自动完成登录。如果有人能够提供如何使用oAuth进行此操作的示例,我将不胜感激,因为我不想使用那个臃肿的SOAP实现。
2个回答

12

经过一些尝试,似乎我的努力已经取得了成功:

$loginurl = "https://login.salesforce.com/services/oauth2/token";

$params = "grant_type=password"
. "&client_id=" . CLIENT_ID
. "&client_secret=" . CLIENT_SECRET
. "&username=" . USER_NAME
. "&password=" . PASSWORD;

$curl = curl_init($loginurl);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 200 ) {
    die("Error: call to URL failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}

curl_close($curl);

echo $json_response;

现在只需要将响应中的access_token和instance_url存储到会话变量中,然后就可以在我们的对象上进行操作了。

我希望以上内容能帮助遇到类似问题的其他人。


2
感谢您的代码!在某些设置中,我发现您需要生成一个安全令牌,然后将其附加到密码上,例如 "&password=" . PASSWORD . SECURITY_TOKEN。 - redgeoff
截至2016年,grant_type=password对我不再起作用。 - Allen Linatoc
好的,没问题。那你知道更新后的参数是什么吗?我已经有两年没接触这个了,所以无法查看。 - megachill

1

2018年的答案:

https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_understanding_username_password_oauth_flow.htm

使用以下内容进行POST请求:

  • grant_type: 对于此身份验证流,必须为password
  • client_id: 连接应用程序定义中的Consumer Key。
  • client_secret: 连接应用程序定义中的Consumer Secret。除非未启用连接应用程序定义中的Web服务器流设置,否则必填。
  • username: 最终用户的用户名。
  • password: 最终用户的密码。

示例:

grant_type=password&client_id=3MVG9lKcPoNINVBIPJjdw1J9LLM82Hn FVVX19KY1uA5mu0QqEWhqKpoW3svG3XHrXDiCQjK1mdgAvhCscA9GE&client_secret= 1955279925675241571&username=testuser%40salesforce.com&password=mypassword123456

请参考上面的链接获取更多详细信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接