0

I'm trying to write a script which I can run daily (from a cron job), to fetch some report output and pipe into another system.

Currently I have a basic PHP script which work, but only from the browser, and that because of the oAuth2 authorization which is required to access the API.

In the command line, I'm stuck as I have to use a browser to authenticate, is there another way ?

the script can be found here https://gist.github.com/rabin-io/0849d698f879fa7f0f70f8038f527348

1

You can authenticate via SOAP's login() command, which requires a username, password, and possibly a security token; a session Id is interchangeable with an access token (they are roughly synonymous). Or, you can use an User-Agent OAuth flow that authenticates via browser once, then uses a refresh token to stay logged in perpetually, even if the username or password changes. This is how the Salesforce DX CLI operates. Other techniques are possible as well, but these are probably the two most common.

The login flow is pretty straight-forward:

$loginResult = $client->login($username, $password . $securityToken);
$sessionId = $loginResult.sessionId;

Of course, don't forget to check for errors and reset the endpoint, as well (it's in the documentation).

The OAuth flow is more involved, as it requires a page to direct the user to Salesforce to log in, then a second page to access the token after logging in. It's not complicated, but it's not trivial either (and more code than I would want to put in to an answer).

There's plenty of examples of this out there on the Internet in the form of documentation, Help topics, Knowledge Articles, blog posts, sample repos... It's everywhere, just look around and you'll find something that will help you.

  • 2
    Not all the OAuth flows require the redirect to a page -- see OAuth 2.0 Username-password flow. No browser involved. Effectively same as SOAP login. This could just be semantics on my part. – cropredy Jun 4 '18 at 1:20
  • @cropredy true, but it's not recommended for production usage. This is why I usually don't recommend it. – sfdcfox Jun 4 '18 at 1:22
  • 1
    But then how is the SOAP login() any more secure than OAuth 2.0 username-password flow? – cropredy Jun 4 '18 at 1:27
  • @cropredy I think it's generally recommended only for SOAP applications, but you could use it in a pinch for REST logins. I'd still prefer to use User-Client when or Web Server flows when possible. – sfdcfox Jun 4 '18 at 1:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.