Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

OAuth Token as Salesforce SessionId in SOAP API (PHP)

Sunday, October 7, 2012 by Aslam - The Alexendra
Hi All,
Most of the time developers who write applications in php/java or any other language, using salesforce soap APIs (partner wsdl or enterprise wsdl), they hard-code the username/password and security token in their code or in a property file. But there is one issue in this approach, anytime, if your org password or security token get change, your application may down. You have to update the credentials in your code or property file on server to get your application work.

One alternate solution for this issue is to use OAuth token in your code and write one automated code which will refresh your oauth token whenever it gets expired. The approach which i am going to tell in few moments has a benefit that you don't have to modify your code much. The place where you setting your sessionid, you just need to change that place, instead of getting sessionid from login method, you simply need to change with oauth token way.

Here is a complete process to achieve this:


1) Go to your org, Setup->Remote Access, make New remote access entry there for your application. Give return url for the file which will get oauth code returned. In my example, i used this url
http://localhost/oauthsample/tokenprint.php




You will notice that you will get Consumer key and Consumer secret.

2) Make one php file at this location oauthsample/tokenprint.php with below code. The purpose of this code is simply print the oauth code.
<?php var_dump($_REQUEST); ?>


3) Now use your browser, prepare this url and invoke from address bar of browser
https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=<your_consumer_key>&redirect_uri=http://localhost/oauthsample/tokenprint.php
 

As soon you invoke this url, you will see the generated oauth code on screen, copy the "GENERATED CODE" from the browser window.

4) Now use following html code, run it in your browser, by simply double click, fill the values in each field.


<form method="post" action="https://login.salesforce.com/services/oauth2/token"> <input type="hidden" name="grant_type" value="authorization_code"/> <table> <tr> <td> GENERATED CODE </td> <td> <input type="text" name="code" /> </td> </tr> <tr> <td> CONSUMER KEY </td> <td> <input type="text" name="client_id" value=""/> </td> </tr> <td> CONSUMER SECRET </Td> <td> <input type="text" name="client_secret" value=""/> </td> </tr> <tr> <td> REDIRECT URL </td> <td> <input type="text" name="redirect_uri" value="http://localhost/oauthsample/tokenprint.php"/> </td> </tr> </table> <input type="submit" /> </form>











5) After you execute this, you will get xml output on screen something like this:





Here you will get two important things, one Refresh Token and second "access token".

6) Now, in your PHP/Java code you need to replace your session id with this access token. There is another thing in your code "server url", this you need to hard code something like below (make sure to use instance url of your org) :

$mySoapClient = $sfConnection->createConnection('partner.wsdl'); $serverUrl = "https://ap1.salesforce.com/services/Soap/u/25.0/00D90000000Abcd"; $sessionId = "<<ACCESS TOKEN>>"; $mylogin = $sfConnection->attach($serverUrl, $sessionId);



7) Now, how to deal with expired token? For that you need to either make a separate method for it, or simply you need enclosed you code in try, catch block and look for INVALID SESSION exception. That exception will come whenever you try to access server contents and your token is expired. So the idea is, whenever that happen , simply catch that exception and use below code to get new access token. In below code, simply replace the different fields with your org info like consumer key, secret and important "REFRESH TOKEN" which we got in step #5.


<?php function getNewToken(){ try{ $url = 'https://login.salesforce.com/services/oauth2/token'; $fields = array( 'grant_type' => "refresh_token", 'client_id' => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 'client_secret' => "xxxxxxxxxxx", 'refresh_token' => "xxxxxxxxxxxxxxxxxxxxxxxxxxxx" ); foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; } $ch = curl_init($url); //set the url, number of POST vars, POST data curl_setopt($ch,CURLOPT_POST, true); curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //execute post $result = curl_exec($ch); //close connection curl_close($ch); $json_a=json_decode($result,true); return $json_a; }catch(Exception $e){ var_dump($e); } } ?>

You can simply call this method getNewToken() to make new token whenever needed.

You are now all set, now you don't have to worry about user credentials updation or revealing it.

Let me know if you face issue in any step.

Thanks
Aslam Bari

Showing Salesforce Images/Attachments on PHP/JSP page

Saturday, October 1, 2011 by Aslam - The Alexendra
Hi All,
Today I am going to demo you how to fetch images (attachments) from salesforce instance in to your PHP script and how you can show those imags on page as a portal or catalog way.

1) index.php script
The below code shows how you can query to attachment object in salesforce to fetch some attachment records. For example i have query the pics (attachment) for my two SFDC contact records in sample code. The concept is simple. You need to query the Id of attachment in your main page, then you will have one another php script which will fetch the SFDC attachment (image) binary data and show the image on screen as embedded. We can wrap/embed that image in <img /> tag directly.

<?php
error_reporting(E_ALL);
require_once ('soapclient/SforcePartnerClient.php');
require_once('connection.php');

$ids = array();
$ids[] = '00390000006IUVK';
$ids[] = '00390000001lwbd';
getPhotos(
$ids);


function getPhotos($contactids){
$mySforceConnection = getConnection();
$query = "SELECT Id, Name from Attachment Where ParentId in (";
foreach($contactids as $id){
$query .= "'". $id . "',";
}
$query = substr($query , 0, strlen($query) - 1);
$query .= ")";
$queryResult = $mySforceConnection->query($query);

$records = $queryResult->records;
if(count($records) > 0){
echo "<table cellspacing='5' cellpadding='5'><tr>";
foreach($records as $rec){
echo "<td style='text-align:center;font-size:12px;'>".
"<img src='image.php?id=".$rec->Id."' ".
"style='width:200px;height:200px;border:1px solid #ccc;padding:10px'/> <br/>"
. $rec->fields->Name.
"</td>";
}
echo "</table>";
}
return NULL;
}
?>


2) image.php script
This code simply accepts one Id of the attachment record and fetch the binary body of attachment, then it shows that image on the screen as image content. To view this image in other page you simply need to wrap/embed its call into <img /> html tag. Like below:

<img src="image.php?id=00P9000000185ioEAA" />


<?php
error_reporting(E_ALL);
header('content-type: image/jpeg');
require_once ('soapclient/SforcePartnerClient.php');
require_once('connection.php');

getPhotos(
$_GET['id']);


function getPhotos($id){
$mySforceConnection = getConnection();
$query = "SELECT Id, Name, Body from Attachment Where Id ='" .$id ."'";
$queryResult = $mySforceConnection->query($query);

$records = $queryResult->records;

print_r(base64_decode($records[0]->fields->Body));
return NULL;
}

?>



Here is the demo of the scripts where i am fetching two contact's images from Salesforce and showing on simple PHP page.

http://labs.aslambari.com/sfdc_photos_demo/


Thanks
Aslam Bari

SF Uploadify: File Uploading Utility for Salesforce

Tuesday, September 13, 2011 by Aslam - The Alexendra
Hi All,
I have created a very cool file uploading utility which can be integrated with any system, but mainly I focused on Salesforce. This utility is built using Uploadify Tool and PHP integration. You can find more info about Uploadify here. It supports multiple file uploading with progress bar and uploads the file to your external server (php server where your site or this utility is hosted.) Then it makes the Attachment record in salesforce and links to actual file on server. So you can directly (natively) access your files.


How it works:

  1. User opens any record in salesforce , lets say "Account" record.
  2. There will be a custom button (given in below code), user clicks on button
  3. One file uploading screen opens, click on 'Select Files" button and select multiple files at same time (using control button)
  4. As soon as, user select and close dialog, it starts uploading files with progress bar
  5. The files will be stored on the Server where this utility exists, for now it saves to my server.
  6. It will show finally a screen with close button.
  7. Click on close button , it will refresh the parent window (if not, manually refresh the parent record)
  8. Open the attachments section, you will find the new files (attachments created, which actually a link for actual files on the server)
  9. Click on any file and click on "View" link.
  10. And you will see it opens your uploaded actual file :)

More Details and Updates on my site:
http://www.aslambari.com/sf_uploadify.html

Installation:
1) Button code:
Make one custom button (detail screen button), on any object, for example , account object, see below code.
a. Behavior must be "Open in new window"
b. Content Source will be "URL"
The url for the button will be as below

http://labs.aslambari.com/sf_file_uploader/sf_setup_uploader.php?sessionid={!$Api.Session_ID}&serverurl={!$Api.Partner_Server_URL_220}&recordid={!Account.Id}

2) Utility Code:
The utility is on my server for now, it is in BETA, once all is tested and working , i will make it public :)

Note: For commercial use this tool, you first need to go to Uploadify site and check its license type if any. Because my tool uses the Uploadify internally.

See the screen cast how it works:
http://screencast.com/t/ibDqgMBbfQ

Hope you will like it. :)

Thanks
Aslam Bari