Skip to content

Instantly share code, notes, and snippets.

@harryward
Created August 27, 2013 20:33
Show Gist options
  • Save harryward/6358786 to your computer and use it in GitHub Desktop.
Save harryward/6358786 to your computer and use it in GitHub Desktop.
php sales force
<?php
session_start();
echo '<form id="queryFilter" action="" method="GET">';
if(isset($_REQUEST['market'])) $_SESSION['market'] = $_REQUEST['market'];
else $_SESSION['market'] = 'Buffalo';
echo '<select name="market" id="market">';
$markets = array( "Abilene","Albany","Amarillo","Atlantic City","Augusta","Bangor","Billings","Binghamton","Bismarck","Bozeman","Buffalo","Casper","Cheyenne","Corporate","Duluth","El Paso","Evansville/Owensboro","Flint","Fort Collins","Grand Junction","Grand Rapids","Killeen","Lafayette","Lake Charles","Laramie","Lawton","Lubbock","Lufkin","Missoula","New Bedford","NJ-Shore","NJ-Trenton","Odessa-Midland","Oneonta","Presque Isle","Quincy-Hannibal","San Angelo","Sedalia","Shelby","Shreveport","Sioux Falls","St. Cloud","Texarkana","Tri Cities WA","Tuscaloosa","Twin Falls","Tyler","Utica","Victoria","Wichita Falls","Yakima" );
foreach($markets as $market) {
if ($market==$_SESSION['market']) echo '<option value="' . $market . '" selected="selected">' . $market . '</option>';
else echo '<option value="' . $market . '">' . $market . '</option>';
}
echo '</select>';
if(isset($_REQUEST['timeline'])) $_SESSION['timeline'] = $_REQUEST['timeline'];
else $_SESSION['timeline'] = 'THIS_MONTH';
$timelines = array( "THIS_MONTH","LAST_MONTH","LAST_90_DAYS","THIS_QUARTER","THIS_YEAR");
echo '<select name="timeline" id="timeline">';
foreach($timelines as $timeline) {
if ($timeline==$_SESSION['timeline']) echo '<option value="' . $timeline . '" selected="selected">' . $timeline . '</option>';
else echo '<option value="' . $timeline . '">' . $timeline . '</option>';
}
echo '</select>';
echo '</form>';
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="jquery.dataTables.css" media="screen" />
<link rel="stylesheet" type="text/css" href="jquery.dataTables_themeroller.css" media="screen" />
<link rel="stylesheet" type="text/css" href="styles.css" media="screen" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript" language="javascript" src="/media/js/jquery.js"></script>
<script class="jsbin" src="https://datatables.net/download/build/jquery.dataTables.nightly.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#salesforce').dataTable();
$('#market, #timeline').change(function() {
$(this).closest('form').submit();
});
$('#download').click(function(event) {
event.prevent();
$(this).closest('form').submit();
});
});
</script>
<?php
$login_base_url = 'https://login.salesforce.com';
$token_url = $login_base_url . '/services/oauth2/token';
$consumer_key = '3MVG9PzgLRblCnyWKgaMnIbL4IsId1mO0eiYn3V2otrCrebB_wFV3dG_aM63MV4S48VbiGXEaIDu9Wc3RsJFE';
$consumer_secret = '6034660535356229843';
$redirect_uri = 'https://townsquarelab.com/salesforce_api/curl.php';
$username = 'harry.ward@townsquaremedia.com';
$password = 'Mrhankey5Zp3nYUoHko3HzEVjCkwo8WeT';
/* flow without username and pass
if(!isset($_REQUEST['code'])) {
$auth_url = $login_base_url
.'/services/oauth2/authorize?response_type=code'
.'&client_id='.$consumer_key
.'&redirect_uri='.urlencode($redirect_uri);
header('Location: '.$auth_url);
exit();
}
$post_fields = array(
'code' => $_REQUEST['code'],
'grant_type' => 'authorization_code',
'client_id' => $consumer_key,
'client_secret' => $consumer_secret,
'redirect_uri' => $redirect_uri
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$token_request_body = curl_exec($ch)
or die("Call to get token from code failed: '$token_url' - ".print_r($post_fields, true));
*/
$post_fields = array(
'grant_type' => 'password',
'client_id' => $consumer_key,
'client_secret' => $consumer_secret,
'redirect_uri' => $redirect_uri,
'username' => $username,
'password' => $password,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$token_request_body = curl_exec($ch)
or die("Call to get token from code failed: '$token_url' - ".print_r($post_fields, true));
//print_r($token_request_body);
// safe
$token_request_data = json_decode($token_request_body, true);
$_SESSION['access_token'] = $token_request_data['access_token'];
$_SESSION['instance_url'] = $token_request_data['instance_url'];
$query_url = $_SESSION['instance_url'].'/services/data/v20.0/query';
$query_url .= '?q='.urlencode('SELECT Radio_Rep__c,Radio_Market__c,Opportunity.Name,Description,StageName,Sales_Channel__c,LeadSource,Date_Received__c,CloseDate,Amount,Demo_Ran_Date__c FROM Opportunity WHERE Radio_Market__c = \'' . $_SESSION['market']. '\' AND CreatedDate = ' . $_SESSION['timeline']. ' AND LeadSource LIKE \'REFERRAL RADIO REP%\' ORDER BY Demo_Ran_Date__c DESC NULLS LAST LIMIT 500');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $query_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: OAuth '.$_SESSION['access_token']));
$query_request_body = curl_exec($ch)
or die("Query API call failed: '$query_url'");
//print_r($query_request_body);
// safe
$data = json_decode($query_request_body, true);
// presentation
// should be later removed
$table_fields = array();
foreach($data['records'] as $record) {
foreach($record as $field_name => $field_value) {
if($field_name!='attributes') $table_fields[] = $field_name;
}
}
$table_fields = array_unique($table_fields);
$table_data = array();
$stack = '<table id="salesforce" width="100%">';
$stack .= '<thead>';
$stack .= '<tr>';
foreach($table_fields as $field_name) $stack .= '<th>' . $field_name . '</th>';
$stack .= '</tr>';
$stack .= '</thead>';
$stack .= '<tbody>';
foreach($data['records'] as $i => $record) {
$stack .= '<tr>';
$table_data[$i] = array();
foreach($table_fields as $field_name) {
if (!isset($record[$field_name])) $record[$field_name] = '';
$stack .= '<td>' . $record[$field_name] . '</td>';
$table_data[$i][$field_name] = $record[$field_name];
}
$stack .= '</tr>';
}
$stack .= '</tbody>';
$stack .= '</table>';
echo $stack;
/* file export */
function csv_filter($string) {
//return str_replace("\r\n", "\n", $string);
return trim(preg_replace('/\s+/', ' ', $string));
}
$csv = '';
$csv .= implode(",", $table_fields) . "\r\n";
foreach($table_data as $record) $csv .= csv_filter(implode(",", $record)) . "\r\n";
echo '<form action="file.php" method="POST">';
echo '<textarea name="data" style="display:none;">' . $csv . '</textarea>';
echo '<button class="ui-button" id="download" href="file.php" target="_blank">Download Results As Spreadsheet</button>';
echo '</form>';
?>
<script>
$('#salesforce').dataTable( {
"bPaginate": true,
"bLengthChange": false,
"bFilter": true,
"bSort": true,
"bInfo": true,
"bjQueryUI:" true,
"aaSorting": [[ 4, "desc" ]],
"bStateSave": true,
"aaSorting": [ [0,'asc'], [1,'asc'] ],
"iDisplayLength": 100,
"bAutoWidth": true } );</script>
<script>
var oTable = $('#salesforce').dataTable();
// Get the data from the first row in the table
var data = oTable._('tr:first');
// Do something useful with the data
var oTable = $('#salesforce').dataTable();
// Filter to 'Webkit' and get all data for
var data = oTable._('tr', {"filter": "applied"});
oTable.fnFilter("Amanda Tunis");
// Do something with the data
$('#salesforce_filter input').click(function(){
$('#' + aePicker).hide('explode');
});
$('#salesforce_filter input').keypress(function(e){
if(e.which == 13) {
$('#salesforce_filter').append("<div id='" + "Amanda Tunis" + "'></div>" + data.length + " leads submitted </div>" );
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment