• Pat Patterson
  • SMARTIE
  • 1709 Points
  • Member since 2010
  • Developer Evangelist Architect
  • salesforce.com


  • Chatter
    Feed
  • 57
    Best Answers
  • 2
    Likes Received
  • 1
    Likes Given
  • 1
    Questions
  • 334
    Replies
Hi,

I am running into this error:
{
  error_description: "expired authorization code"
  error: "invalid_grant"
}
Currently trying to connect to my Sandbox 'Connected App' from a client server running PHP scripts and using OAuth 2.0 JWT Bearer Token Flow as the method of authentication. I have gone over and over this document (OAuth 2.0 JWT Bearer Token Flow (https://help.salesforce.com/apex/HTViewHelpDoc?id=remoteaccess_oauth_jwt_flow.htm&language=en_US#validate_token)) so many times but can not seem to understand why i am getting this error.

I've checked my connected App settings and provided full access already with no restrictions of IP address so I don't know why I get expired authorization code error. Maybe it is in my PHP coding from the client side requesting the 'Access Token'? Here is my Code.
 
// You need to set these three to the values for your own application
define('CONSUMER_KEY', 'abc123');
define('CONSUMER_SECRET', '1234');
define('LOGIN_BASE_URL', 'https://test.salesforce.com');

//Json Header
$h = array(
	"alg" => "RS256"	
);

$jsonH = json_encode(($h));	
$header = base64_encode($jsonH); 

//Create JSon Claim/Payload
$c = array(
	"iss" => CONSUMER_KEY, 
	"sub" => "myemail@email.com", 
	"aud" => LOGIN_BASE_URL, 
	"exp" => "1333685628"
);

$jsonC = (json_encode($c));	
$payload = base64_encode($jsonC);

//Sign the resulting string using SHA256 with RSA
$s = hash_hmac('sha256', $header.'.'.$payload, CONSUMER_SECRET);
$secret = base64_encode($s);


$token = $header . '.' . $payload . '.' . $secret;

$token_url = LOGIN_BASE_URL.'/services/oauth2/token';

$post_fields = array(
	'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
	'assertion' => $token
);

$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);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// Make the API call, and then extract the information from the response
    $token_request_body = curl_exec($ch) 
        or die("Call to get token from code failed: '$token_url' - ".print_r($post_fields, true));
Hope any one out there might be able to help me solve this!

Thanks.
Regards,
Joey
 
The identity provider requires a specific samlp tag to be included in the request. I can't see a way of achieving this.
  • There doesn't appear to be any way to specify this in the configurable single sign-on settings.
  • Creating a setting via "New Metadata from File" using the metadata from the identity provider doesn't help either.
Any ideas?

About the only thing I can think of manually modifying the metadata file to force addition of the tag - anyone done this before?
 
I have a web application where users log in using their login an password.
I'm creating a Salesforce Community for those users, for them to ask questions, read articles, start discussions, etc.

I have a scheduled process now that synchronizes the users I have in my application to Salesforce. I'm extending that process to create contacts and community users, so my users won't have to manually register into the community.

In the next step, I'm going to add a link to my application where the users can click and be logged into the community, in a new window. As the users are already logged into my application, I don't whan them to provide their login again to communities. How can I achieve that?

I read a lot of Salesforce documentation on loggin in using SAML and OAuth and couldn't find anything that suits my needs. OAuth is all about authenticating the user and giving me an access token, so my application can perform actions in the community on the behalf of my user. I don't want that. I only want to login the user.

A solution could be use SAML to single sign on, but then I would need to manage my user in a SSO provider and I don't want to do that. Is there any way to log my user into the communities using only its email or Salesforce Id, without requiring them to provide credentials? Can I provide some secret or key from my application and log in any user I want?

I found something close to that with OAuth 2.0 JWT Bearer Token Flow, but even then I would need a user first authentication to get an authorization token.

Thank you
I have a Force.com site set up, which will be used by un-authenticated users. My site automatically has two domians associated with it

http://mydomain.force.com
https://mydomain.secure.force.com

Since users will be making purchases (using a credit card) through this site, I would like to force them to use the secure version. The URL Redirect settings on the site don't allow me to do redirects at the domain level, however, and the documentation that I have found regarding forcing HTTPS refers to users who are logged in. 

Is there a way to redirect un-authenticated users to https://mydomain.secure.force.com when they attempt to access http://mydomain.force.com?
  • February 27, 2014
  • Like
  • 3
Hey  Guys, 

I have created a visualforce page which displays the list of records which meet the critiriea on the page. Along with this , there are some fields  which are performaing some calculations. I am trying to display error message when it doesn't mee the critirea. It is working fine when there is no calculation field but when I include the calculation field , it gives me this error. In short, If I remove the Highlighted line in apex code it works fine but I do want to include that line also. Please help.
Attempt to de-reference a null object
Error is in expression '{!FetchSPRec}' in component <apex:commandButton> in page trial_rfp_page


Calculation field :- MaxImpression

Apex code:

public class Fetchsiteplacement12{
public Site_Placements__c  sp{get;set;}
    public List<Site_Placements__c > spRec{get;set;}
    String matchString;
    String matchString1;
    public integer NumberOfSitePlacements {get;set;}
    public decimal SumOfImpressions{get;set;}
    public decimal MaxImpressions{get;set;}
   
    public Fetchsiteplacement12(){
        sp=new Site_Placements__c ();
        spRec = new List<Site_Placements__c>();
        matchString = '';
        matchString1 ='';
        }
       
            public void FillAggregates()
                 {
                       NumberOfSitePlacements = [ Select count()
                       FROM Site_Placements__c where ((Device_Type__c like :matchString) AND (Auto_Play__c like :matchString1))];
          
                       SumOfImpressions = (decimal)([ SELECT sum(Total_Impresions__c)
                       FROM Site_Placements__c Where ((Device_Type__c like :matchString) AND (Auto_Play__c like :matchString1))][0].get('expr0'));
                      
                       MaxImpressions = SumOfImpressions/NumberOfSitePlacements ;
                 }
  
 
        public void FetchSPRec(){
        matchString = '%'+sp.Device_Type__c+'%';
        matchString1 = '%'+sp.Auto_Play__c+ '%';
      
      
      
        spRec=[select Name, Site_Placement_ID__c, Site_Level_Max_Impressions__c from Site_Placements__c where
        ((Device_Type__c like :matchString) AND (Auto_Play__c like :matchString1) ) ORDER BY Site_Level_Max_Impressions__c DESC limit 10];
      
       if(spRec.size() == 0)
                  {
                   Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,''+'No records to Display"'));
                  }
                  FillAggregates();
                  }
      
       public pagereference CancelSPRec(){
    
    PageReference page = new PageReference('https://cs1.salesforce.com/a36/o');
    page.SetRedirect(true);
    return page;
    }}

VisualForce page:-

<apex:page controller="Fetchsiteplacement12" tabStyle="Site_Placements__c" sidebar="True">
    <apex:form >
        <apex:pageBlock >
        <apex:messages />
            <apex:pageBlockButtons location="Both">
         
            <apex:commandButton value="Fetch" action="{!FetchSPRec}"/>
            <apex:commandButton value="Cancel" action="{!CancelSPRec}"/>
            </apex:pageBlockButtons>
           
            <apex:pageBlockSection title="Please select the Critirea">
            
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Auto Play" for="autoplay"/>
                    <apex:inputField value="{!sp.Auto_Play__c}" id="autoplay"/>
                </apex:pageBlockSectionItem>
               
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Device Type" for="devicetype"/>
                    <apex:inputField value="{!sp.Device_Type__c}" id="devicetype"/>
                </apex:pageBlockSectionItem>
               
              
              <apex:pageBlockSection Title="Calculations">
          
                 <apex:pageBlockSectionItem > Number of site placements : {!NumberOfSitePlacements}<br/></apex:pageBlockSectionItem>
                 <apex:pageBlockSectionItem > Max Impressions : {!Maximpressions}<br/></apex:pageBlockSectionItem>
                 </apex:pageBlockSection>
            
              <apex:pageBlockSection title="Results">
            <apex:pageBlockSectionItem >
                <apex:pageBlockTable value="{!spRec}" var="site" >
                    <apex:column value="{!site.Name}"/>
                    <apex:column value="{!site.Site_Placement_ID__c}"/>
                    <apex:column value="{!site.Site_Level_Max_Impressions__c}"/>
                   
                 </apex:pageBlockTable>
                 </apex:pageBlockSectionItem>
                
           </apex:pageBlockSection>
         </apex:pageblock>
                
</apex:form>
</apex:page>

What happens if I don't provide the optional External Id parameter for a Database.Upsert call?

Will an insert be performed?

Thanks in advance
Can i create a custom object and add a functionality in Chatter Feed saying New "custom Object" like below ? Can i do this using Canvas app. Any tutorial or link will be greatly appreciated.
Thanks.


Add new chatter feed feature type ?
Hi,

I'm having a really annoying issue with the test class that I'm putting together that I can't figure out what I'm getting an error on so hoping someone in the community can point me in the right direction.

I have an Object Leave__c that I use to log holidays(nothing special just a link to employee records/start/return dates)
I have created a simple VF Page for adding leave:

<apex:page standardcontroller="Leave__c" extensions="employee_leave_controller" showheader="false" sidebar="false">
<apex:stylesheet value="{!URLFOR($Resource.myStyles, 'employee.css')}"/>
    <div style="width:100%; height:100%">
        <a href="/apex/my_leave?"><button type="button">Back to My Leave List</button></a>
    </div>
    <apex:form >
        <apex:pageBlock title="Submit Leave for {!$User.FirstName}">
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton action="{!save}" value="Save"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="Leave Information">
                <apex:inputField value="{!Leave__c.Leave_Type__c}" required="true"/>
                    <span>Select your leave type</span>
                <apex:inputField value="{!Leave__c.Employee__c}" required="true"/>
                    <span>Is this you? If not contact IT</span>
                <apex:inputField value="{!Leave__c.Start_Date__c}" required="true"/>
                    <span>Enter the first day of your holiday</span>
                <apex:inputField value="{!Leave__c.Return_Date__c}" required="true"/>
                    <span>Enter the day before your return to work</span>
                <apex:inputField value="{!Leave__c.No_Of_Days__c}" onfocus="true" required="true"/>
                    <span>{!$ObjectType.Leave__c.fields.No_Of_Days__c.InlineHelpText}</span>               
                <apex:inputField value="{!Leave__c.Notes__c}"/>
                    <span>Any additional information about your abscense that will help your line manager quickly approve.</span>
            </apex:pageBlockSection>
       </apex:pageBlock>
    </apex:form>
</apex:page>

This is my apex extension:

public class employee_leave_controller { 
    private Leave__c leave;
    private ApexPages.StandardController stdController;
    public employee_leave_controller (ApexPages.StandardController controller) {
       
        //pre-populate Lost notes on load
        this.leave = (Leave__c)controller.getRecord();
        leave.Employee__c = [select id from employee__c where Salesforce_Account__r.id =: UserInfo.getUserID()].id;
        stdcontroller=controller;
       
    }
   
   
    public PageReference save()
    {
        //Custom Save Code
        upsert leave;
        PageReference pageRef=Page.my_leave;
        return pageRef;
     }
}

and this is my test class(note the system administrator i've only added now to check the error wasn't permissions related):

@isTest
public class Test_Employee_Portal{
public static testMethod void TestMyLeaveRequest(){
        // set up user and manager
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        User u1 = new User(Alias = 'standt1', Email='demo1@randomdemodomain.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName='dprobertdemo1@camfed.org');
        insert u1;
        User u2 = new User(Alias = 'standt2', Email='demo2@randomdemodomain.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US', ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName='dprobertdemo2@camfed.org', ManagerID=u1.Id);
        insert u2;
        //add employee
        Employee__c emp=new Employee__C(Name='Demo Demo',First_Name__c='Demo',Last_Name__c='Demo',Salesforce_Account__c=u2.id);
        insert emp;
//add employee holiday allowance        
Employee_Holiday_Entitlement__c empent=new Employee_Holiday_Entitlement__c(Allowance__c=10,Employee__c=emp.id,Year__c='2014');
        insert empent;
       //test creating a new page
        System.runAs(u2){
            PageReference pageRef = Page.my_leave_request;
            Test.setCurrentPage(pageRef); 
             // leave details 
            Leave__c leav = new Leave__c(Employee__c=emp.id,Start_Date__c=system.today(),Return_Date__c=system.today(),No_of_days__c=5,Leave_Type__c='Holiday');
            insert leav;
       
            ApexPages.standardController controller = new ApexPages.standardController(leav);
           
            employee_leave_controller pag = new employee_leave_controller(controller);         
            pag.save();
        }
    }

the error that i'm getting is:

System.SObjectException: Field is not writeable: Leave__c.Employee__c
Class.employee_leave_controller.<init>: line 8, column 1
Class.Test_Employee_Portal.TestMyLeaveRequest: line 23, column 1

Anyone able to give me a steer on what i've got wrong.

many thanks
dan
So what stops someone from creating a Developer account and just adding users etc.,?

Assuming the company is small, couldn't they just do that?

Hi there,
I'm trying to add Test.StartTest() in my test class, but I kept getting this error message.

"Error: Compile Error: Variable test is used before it is declared. at line 4 column 46"

I then go back and check if I have any class called "test" that override the test method, but I can't find any. Do you guys happen to know where the error comes from? If you can kindly give me some advice I'll very much apprecaite. Thank you!

User-added image

Can the Community User credentials be used to login via the Salesforce1 mobile app or is that only available to users who have the full Salesforce license?

I have a question about the submission of our App for the Hackathon.  The Official Requirements state:

 

Build the most amazing mobile application using Salesforce Platform. Your submission must include:

  • A mobile application useable by the judges (see official rules for more details)
  • Login credentials to the Salesforce development environment used by the application (credentials should not be to a production environment or expose production data)
  • A 250 word description submitted in English of the application 
  • A maximum 2-minute demo video of the working application uploaded to your YouTube or Vimeo account, with a link to the demo video provided through the submission process (see official rules for more details) 
  • Link to the working source code; if the app is designed for a native platform it should include a complete working project that can be compiled.

Our app will be a Mobile Visualforce tab accessible inside the new Salesforce1 Mobile App that extends the functionality of Salesforce.com.  We make use of 3rd party API's as well as some custom code written on a LAMP stack hosted on Amazon EC2.  Are we only required to submit login credentials to our Developer Org.... or do we need to submit source code for the custom code hosted on our EC2 server?

 

Clarification is appreciated.

 

Thanks

I am using JQuery Mobile for an Apex/Visualforce page.

The problem is I am trying to section off 2 separate repeat tags, but when I adjust my repeat tags to certain divs,

 

I get the error message:

Description	Resource	Path	Location	Type
Save error: Unknown property 'InventoryExtension.product'	

 

Here is what I am trying:

 

<div data-role="page" data-theme="b" id="detailpage{!product.Id}">
		
		<!-- page header -->
		<div data-role="header"><!-- button for going back to mainpage -->
			<a href='#mainpage' id="backInventory" class='ui-btn-left'
			data-icon='home'> Home </a> <!-- page title -->
			<h1>Edit</h1>
		</div>
		
		<!-- page content -->
		<apex:repeat value="{!products}" var="product">
			<div id="#content" data-role="content">
				<h2 id="name"><label for="model{!product.Id}">
				<h2>Model</h2>
				</label> <input type="text" value="{!product.Model__c}"
				id="model{!product.Id}" /></h2>



			<div data-role="fieldcontain">
				<fieldset data-role="controlgroup">
					<apex:outputPanel rendered="{!product.checked_out__c}">
						<input checked="checked" data-mini="true" type="checkbox"
						name="checked_out" id="checked_out{!product.Id}"
						value="{!product.checked_out__c}" />
					</apex:outputPanel> 
					
					<apex:outputPanel rendered="{!!product.checked_out__c}">
						<input data-mini="true" type="checkbox" name="checked_out"
						id="checked_out{!product.Id}" value="{!product.checked_out__c}" />
					</apex:outputPanel> 
					<label for="checked_out{!product.Id}" data-inline="true">CheckedOut:</label>
				</fieldset>
			</div>



		<div data-role="fieldcontain"><label
			for="asset_tag{!product.Id}">Asset tag:</label> <input type="text"
			id="asset_tag{!product.Id}" value="{!product.Asset_Tag__c}" />
		</div>

		<div data-role="fieldcontain"><label
			for="operating_system{!product.Id}">Operating System:</label> <input
			type="text" id="operating_system{!product.Id}"
			value="{!product.Operating_System__c}" />
		</div>

		<div data-role="fieldcontain"><label
			for="serial_number{!product.Id}">Serial #:</label> <input type="text"
			id="serial_number{!product.Id}" value="{!product.Serial_Number__c}" />
		</div>

		<div data-role="fieldcontain"><label for="notes{!product.Id}">Notes:</label>
		<textarea id="notes{!product.Id}" value="{!product.Notes__c}">{!product.Notes__c}</textarea>
		</div>

		<div data-role="fieldcontain"><label for="hostname{!product.Id}">Host
		Name:</label> <input type="text" id="hostname{!product.Id}"
			value="{!product.Hostname__c}" />
		</div>

		<div data-role="fieldcontain"><label
			for="memory_size{!product.Id}">Memory Size:</label> <input
			type="text" id="memory_size{!product.Id}"
			value="{!product.Memory_Size__c}" />
		</div>



		<a href="#" data-role="button" data-id="{!product.Id}"
			class="updateButton" data-theme="b"> Update </a>
	
	</div>
</apex:repeat>
	</div>

 

I don't get any errors if I wrap the repeat tags around the entire div like so:

<apex:repeat value="{!products}" var="product">
	<div data-role="page" data-theme="b" id="detailpage{!product.Id}">
		
		<!-- page header -->
		<div data-role="header"><!-- button for going back to mainpage -->
			<a href='#mainpage' id="backInventory" class='ui-btn-left'
			data-icon='home'> Home </a> <!-- page title -->
			<h1>Edit</h1>
		</div>
		
		<!-- page content -->
		
			<div id="#content" data-role="content">
				<h2 id="name"><label for="model{!product.Id}">
				<h2>Model</h2>
				</label> <input type="text" value="{!product.Model__c}"
				id="model{!product.Id}" /></h2>



			<div data-role="fieldcontain">
				<fieldset data-role="controlgroup">
					<apex:outputPanel rendered="{!product.checked_out__c}">
						<input checked="checked" data-mini="true" type="checkbox"
						name="checked_out" id="checked_out{!product.Id}"
						value="{!product.checked_out__c}" />
					</apex:outputPanel> 
					
					<apex:outputPanel rendered="{!!product.checked_out__c}">
						<input data-mini="true" type="checkbox" name="checked_out"
						id="checked_out{!product.Id}" value="{!product.checked_out__c}" />
					</apex:outputPanel> 
					<label for="checked_out{!product.Id}" data-inline="true">CheckedOut:</label>
				</fieldset>
			</div>



		<div data-role="fieldcontain"><label
			for="asset_tag{!product.Id}">Asset tag:</label> <input type="text"
			id="asset_tag{!product.Id}" value="{!product.Asset_Tag__c}" />
		</div>

		<div data-role="fieldcontain"><label
			for="operating_system{!product.Id}">Operating System:</label> <input
			type="text" id="operating_system{!product.Id}"
			value="{!product.Operating_System__c}" />
		</div>

		<div data-role="fieldcontain"><label
			for="serial_number{!product.Id}">Serial #:</label> <input type="text"
			id="serial_number{!product.Id}" value="{!product.Serial_Number__c}" />
		</div>

		<div data-role="fieldcontain"><label for="notes{!product.Id}">Notes:</label>
		<textarea id="notes{!product.Id}" value="{!product.Notes__c}">{!product.Notes__c}</textarea>
		</div>

		<div data-role="fieldcontain"><label for="hostname{!product.Id}">Host
		Name:</label> <input type="text" id="hostname{!product.Id}"
			value="{!product.Hostname__c}" />
		</div>

		<div data-role="fieldcontain"><label
			for="memory_size{!product.Id}">Memory Size:</label> <input
			type="text" id="memory_size{!product.Id}"
			value="{!product.Memory_Size__c}" />
		</div>



		<a href="#" data-role="button" data-id="{!product.Id}"
			class="updateButton" data-theme="b"> Update </a>
	
	</div>

	</div>

</apex:repeat>

 

Any ideas? I really would like to have to separate sections within the same page-section.

Hi,

 

I am unable to load a hybrid_remote application that is pointing to a remote visual force page on Android.  Here are the steps I followed 

 

1) I installed the following visual force examples into  my DE

   - http://bit.ly/mobile_vf_phonebook

   - and the example mentioned in http://www2.developerforce.com/en/mobile/getting-started/html5#backbone

2) using forcedroid create command I created a hybrid_remote application, I pointed the start page as /apex/PhoneBook or /apex/MobileSample_Backbone (neither pages worked) 

3) I editied oauthRedirectURI (testsfdc:///mobilesdk/detect/oauth/done) and consumerkey in the bootconfig.json.

 

I use ecllipse for building and launching my application, when i launched the app (either on device or simulator) the app simply shows a blank screen.

 

I was expecting it to show a sfdc login screen followed by permission screen and upon clicking allow it would take me to my remote visual force page, but that dint work.

 

Could someone let me know if there is an issue with my configuration ? 

 

Thanks,

 

Nikhil

I have an equipment inventory app.

I'd like to use a select list to change the 'Category':

 

 $("#categories").on("change", function(){
                alert(this.value);
                InventoryExtension.getEquipment(this.value,handleUpdate );
               //$("#equipmentList").listview('refresh');
               $("#equipmentList").trigger('create');
                
});

 The Apex method is getting called, the parameter 'this.value' from the click shows in the Apex method as well.

It comes in as 'Laptop' or 'desktop', fine.

 

Here is the Apex method:

 public static List<Equipment__c> getEquipment(String myCategory){
             
             
                if(myCategory== null){
                    products = [SELECT Id, Model__c,checked_out__c,Operating_System__c,Serial_Number__c,
                    Asset_Tag__c,Hostname__c,Notes__c,Memory_Size__c  from Equipment__c];   
                }else{
                	System.debug('My Category: '+myCategory);
                 	products = [SELECT Id, Model__c,checked_out__c,Operating_System__c,Serial_Number__c,
                    Asset_Tag__c,Hostname__c,Notes__c,Memory_Size__c  from Equipment__c 
                                    where RecordType.Name =: myCategory];      
                }
                
                return products;
               
            }

 

 

I can see that the data is coming back from the post correctly. If I choose 'Laptop' I am getting laptop data.

 

I don't understand how to update the view of the listview??

Can someone shed some light on this?

 

 Here is the server plain text response:

Response from server: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

 

 

Hi Everyone,

I created the class and exposed has. WSDL and I am able to get the session id and and the result,

I need to send as JSON response for third party Application.

 

How do parse the JSON and how to send the response?

 

global class AccountServices
{
    webService static String hello(String Name,String Phone,String Website)
    {
    
      Account accounts = [SELECT id, name,phone,website FROM Account LIMIT 1];
      return 'Hello '+accounts.name+' '+accounts.Phone+' '+accounts.Website+' ! :D';
   
    }
}

  • September 25, 2013
  • Like
  • 0

Hey folks. 

 

Our team needs to be keep records in synch between our app and Salesforce.  We will be updating PersonAccounts and Cases.  

 

We're considering using the REST API to update the records using a foreign key from our app.

 

Can anyone think of any drawbacks to using foreign keys with the REST API?  Are there things we won't be able to do?  Would it be more advantageous for us to store the Salesforce record ID in our app?

 

Thanks in advanced.

HI...

I am developing a web application integrated with salesforce. I used REST API and SOAP API (PHP Toolkit) for integration. The application creates a custom field on Contact.  This field must be shown on the Contact detail page hence must be added to Contact's layout. I am able to create the field by using metadata api by PHP coding but the problem is now how to add the field to the Contact's Layout. I read php toolkit documentations but did not found any help. Any one there got any Idea how to do this?

  • September 09, 2013
  • Like
  • 0

Hi all. I'm having a problem accessing the REST API from a VF page. Basically, the request performs OK, except for the parameters, which are not being set/do not arrive on the endpoint.

 

I'm using forcetk to avoid the cross domain issue. This is the relevant VF code:

 

<apex:page showHeader="false" sidebar="false" standardStylesheets="false">

    <apex:includeScript value="{!URLFOR($Resource.MyResource, 'jquery-1.9.1.min.js')}"/>
    <apex:includeScript value="{!URLFOR($Resource.MyResource, 'forcetk.js')}"/>
    
    <script type="text/javascript">
        $(document).ready(function() {

            var forceTKClient = new forcetk.Client();
            forceTKClient.setSessionToken('{!$Api.Session_ID}');
            
            forceTKClient.apexrest(
                '/MyRestResource',
                function(data, textStatus, jqXHR) {
                    console.log('SUCCESS - ' + data);
                },
                function(jqXHR, textStatus, errorThrown) {
                    console.log('ERROR - ' + textStatus);
                },
                'GET',
                {'myParameter':'myValue'},
                null,
                false
            );
        });
    </script>
    
</apex:page>

 

And this is the Apex controller for the REST resource:

 

@RestResource(urlMapping='/MyRestResource')
global with sharing class MyRestResource {
    
    @HttpGet
    global static Map<String, String> doGet() {

        Map<String,String> res = new Map<String,String> {
            'received' => 'yes'
        };      
        
        res.putAll(RestContext.request.params);
        return res;
    }

}

 

My custom REST method is reached correctly, and the response from it is returned correctly, but the parameters do never get to my custom REST method. I.e., the response received on the JS callback is

 

{received: "yes"}

 whereas it should be

 

{received: "yes", myParameter: "myValue"}

Inspecting the request sent from the browser I see that the endpoint is

 

https://c.na11.visual.force.com/services/proxy?_=1368023886976

 

 

"myParameter" isn't present anywhere on the browser request.

 

Any hint?

 

Thanks in advance,

Antonio

 

 

We now have Mobile Packs for jQuery Mobile, Backbone.js and AngularJS, with (safe harbor!!!) Knockout.js in the pipeline. What other client-side framework(s) are you using? We've heard from fans of Ember.js and Sencha, but we need your help in prioritizing the next set of Mobile Packs.

 

Let us know here what you're looking for...

We now have Mobile Packs for jQuery Mobile, Backbone.js and AngularJS, with (safe harbor!!!) Knockout.js in the pipeline. What other client-side framework(s) are you using? We've heard from fans of Ember.js and Sencha, but we need your help in prioritizing the next set of Mobile Packs.

 

Let us know here what you're looking for...

I wonder if Delegated Authentication can be enabled for a specific set of users in addition to Social Sign on. The idea is that a specific set of users can login to Salesforce either by providing username/password (which is going to be validated via Delegated Authentication) or by using their Facebook credentials.

All the examples that I saw so far were showing that Delegated authentication and Social sign-on can be enabled in Salesforce. My question is if they can be enabled together for the same set of users.

Federal authentication is not an option for multiple reasons.

Thanks
  • December 09, 2015
  • Like
  • 0
Hi,
We have a login form in a visualforce page and it has an actionFunction that verifies if the credentials the user provides are correct, the problem is that if the page is loaded under http the server throws an error "No 'Access-Control-Allow-Origin' header is present on the requested resource", I'm guessing the error is due to the fact that the form has forceSSL set to true so it creates an https call from an http page, but if we remove the forceSSL parameter and we try to login the server throws "This form must be secure. Use the 'forceSSL' attribute and set it to 'true.'", so my question is how can we configure the site so it does not demand forceSSL set to true when trying to log in? Thanks.
Hi,

I am running into this error:
{
  error_description: "expired authorization code"
  error: "invalid_grant"
}
Currently trying to connect to my Sandbox 'Connected App' from a client server running PHP scripts and using OAuth 2.0 JWT Bearer Token Flow as the method of authentication. I have gone over and over this document (OAuth 2.0 JWT Bearer Token Flow (https://help.salesforce.com/apex/HTViewHelpDoc?id=remoteaccess_oauth_jwt_flow.htm&language=en_US#validate_token)) so many times but can not seem to understand why i am getting this error.

I've checked my connected App settings and provided full access already with no restrictions of IP address so I don't know why I get expired authorization code error. Maybe it is in my PHP coding from the client side requesting the 'Access Token'? Here is my Code.
 
// You need to set these three to the values for your own application
define('CONSUMER_KEY', 'abc123');
define('CONSUMER_SECRET', '1234');
define('LOGIN_BASE_URL', 'https://test.salesforce.com');

//Json Header
$h = array(
	"alg" => "RS256"	
);

$jsonH = json_encode(($h));	
$header = base64_encode($jsonH); 

//Create JSon Claim/Payload
$c = array(
	"iss" => CONSUMER_KEY, 
	"sub" => "myemail@email.com", 
	"aud" => LOGIN_BASE_URL, 
	"exp" => "1333685628"
);

$jsonC = (json_encode($c));	
$payload = base64_encode($jsonC);

//Sign the resulting string using SHA256 with RSA
$s = hash_hmac('sha256', $header.'.'.$payload, CONSUMER_SECRET);
$secret = base64_encode($s);


$token = $header . '.' . $payload . '.' . $secret;

$token_url = LOGIN_BASE_URL.'/services/oauth2/token';

$post_fields = array(
	'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
	'assertion' => $token
);

$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);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// Make the API call, and then extract the information from the response
    $token_request_body = curl_exec($ch) 
        or die("Call to get token from code failed: '$token_url' - ".print_r($post_fields, true));
Hope any one out there might be able to help me solve this!

Thanks.
Regards,
Joey
 
Hi everyone,
I am now trying to build an OData 4 service so that Salesforce can access the external data.
So far I was able to get the list view of the external objects with pagination. However when I am trying to access a particular object
I get an HTTP error "400 Bad request". When I inspect the used URL I see that the key property "id" is set to '/x' (%2Fx if encoded) instead of the real id, which can even be seen in the list view.
Here is the decoded URL: https://ecme.empolis.com/oauth/LegoService/LegoService.svc/events?$top=2&$filter=id eq '%2Fx'&$count=true&$select=description,id,sensorId,severity,timestamp,unitId,value
I tried some sample oData4 services provided by odata.org and there the key property is set to its actial value in the same situation.
What can be the reason? How can I fix it?

 
The identity provider requires a specific samlp tag to be included in the request. I can't see a way of achieving this.
  • There doesn't appear to be any way to specify this in the configurable single sign-on settings.
  • Creating a setting via "New Metadata from File" using the metadata from the identity provider doesn't help either.
Any ideas?

About the only thing I can think of manually modifying the metadata file to force addition of the tag - anyone done this before?
 
I have a web application where users log in using their login an password.
I'm creating a Salesforce Community for those users, for them to ask questions, read articles, start discussions, etc.

I have a scheduled process now that synchronizes the users I have in my application to Salesforce. I'm extending that process to create contacts and community users, so my users won't have to manually register into the community.

In the next step, I'm going to add a link to my application where the users can click and be logged into the community, in a new window. As the users are already logged into my application, I don't whan them to provide their login again to communities. How can I achieve that?

I read a lot of Salesforce documentation on loggin in using SAML and OAuth and couldn't find anything that suits my needs. OAuth is all about authenticating the user and giving me an access token, so my application can perform actions in the community on the behalf of my user. I don't want that. I only want to login the user.

A solution could be use SAML to single sign on, but then I would need to manage my user in a SSO provider and I don't want to do that. Is there any way to log my user into the communities using only its email or Salesforce Id, without requiring them to provide credentials? Can I provide some secret or key from my application and log in any user I want?

I found something close to that with OAuth 2.0 JWT Bearer Token Flow, but even then I would need a user first authentication to get an authorization token.

Thank you
Currently I have a trigger which auto-follows specific groups in our organization when a new user is brought onboard.  The auto-follow trigger feature works great!  However, we have quite a few groups we would like these users to follow, based on various departments, which means that the user will get emails for each of the groups they are added to.  I would like to turn off email notifications during this process.

To do this, I found Database.DMLOptions.triggerUserEmail.  This seems to be exactly what I am looking for, however the sending of th email persists.  Below is the short function which is called by the trigger.  As you can see, I tried adding the options to both the cand ChatterGroupMember object and to the database.insert.  Using only one of these email header option sections also continues to send the email - as if it is being completely ignored.

Any assistance would be greatly appreciated.

public static void AddToGroups(Set<Id> userIds)
    {
        List<User> users = [select Id, Username from User where Id in :userIds];             
        Set<Id> updateUsers = new Set<Id>();
        // set up the groups that the user should be added to
        /*  All Users should be changed to the correct name of the group containing the department list */
        List<CollaborationGroup> chatterGroups=[select id, Name from CollaborationGroup where name like :ANNOUNCEMENT_GROUPS];

        // Start a new list that we can add new members to for the single update call.
        List<CollaborationGroupMember> chatterGroupMembers=new List<CollaborationGroupMember>();
              
        // loop the users - do not recheck for the flag, it may have already been updated!
        for (User user : users) {
            // loop the groups
            for (CollaborationGroup chatterGroup : chatterGroups) {
                // if is not already member, add the user to the group
                if(IsMember(chatterGroup.id, user.Id) == false) {

                    CollaborationGroupMember cand =
                        new CollaborationGroupMember(CollaborationGroupId=chatterGroup.id, MemberId = user.Id);

                    // Do not send an email to the users about the groups they're joining.
                    Database.DMLOptions dlo = new Database.DMLOptions();
                    dlo.EmailHeader.triggerAutoResponseEmail = false;
                    dlo.EmailHeader.triggerUserEmail = false;
                   
                    // Set the email options on the user we're working with
                    cand.setOptions(dlo);

                    // Now add the user to the group list
                    chatterGroupMembers.add(cand);

                    // why did I do this?
                    updateUsers.add(user.Id);
                }
            }
        }
        // Only run the insert if needed
        System.Debug(chatterGroupMembers);

        // Do not send an email to the users about the groups they're joining.
        Database.DMLOptions dlo = new Database.DMLOptions();
        dlo.EmailHeader.triggerAutoResponseEmail = false;
        dlo.EmailHeader.triggerUserEmail = false;
       
        Database.insert( chatterGroupMembers, dlo);    
    }


I'm following this (https://developer.salesforce.com/page/Tksample.php) tutorial and trying to performing a simple query with my SforcePartnerClient object...
$query = "SELECT Id, FirstName FROM Contact"
$response = $mySforceConnection->query($query);
foreach ($response->records as $record)
{
	echo $record->fields->FirstName;
}
...but the above code doesn't output anything. Looking at it in the debugger shows that "fields" is null. It DOES, however, seem to have the proper SOAP results inside "$record->any".

Any idea what might be wrong?
Any idea why this is not rendering the page on Salesforce1?

<apex:page >
  <script>
      if ( (typeof sforce != 'undefined') && (sforce != null) ) {
          sforce.one.navigateToList('00BG0000008Wtyc', 'AllOpenLeads', 'Lead');
      }
  </script>
</apex:page>

I just want to redirect to the all open leads list view.

Hi All,

I am getting below exception when downloading the force.com project.

 

below is the message:

 

Exception happened when resolving component type(s), so no component

will be added to the package manifest editor for these types.

*SamlSsoConfig

See log for detail exception message.

 


Thanks,

I'm writing middleware in WCF and trying to obtain an authorization token from salesforce for OAuth.

I'm posting to https://login.salesforce.com/services/oauth2/token with the following data:

 

string postData = "client_id=" + key + "&client_secret=" + secret + "&redirect_url=http://localhost:1670/myservice.svc/callback" + "&grant_type=authorization_code";

 

SF keeps telling me "400 Bad Request"

 

Does anyone have any experience with this?

  • February 01, 2011
  • Like
  • 0

Hi,

 

I try this code:

http://developer.force.com/cookbook/recipe/interact-with-the-forcecom-rest-api-from-php

 

And when I execute, get a Salesforce.com Login, I put my login and when back to my computer (a localhost), get this error:

   https://login.salesforce.com/services/oauth2/token failed with status 0

 

Anyone can explain whats append?!!!

 

Best Regards,

LB

  • December 22, 2010
  • Like
  • 0

Salesforce.com loves developers. And it’s amazing to see how quickly our developer community builds next-generation apps on the Salesforce Platform. So we thought we’d cook up a little surprise. OK, a huge surprise. How about the world’s first hackathon with a single $1 million prize?

It’s on. Come to Dreamforce. Build a next-generation mobile app, and change the world. And win a million bucks. Really. What better way to say thank you to our developers than to put on the biggest on-site hackathon in history. Today, we are thrilled to launch the Salesforce $1 Million Hackathon!

 

Read the full announcement at: http://blogs.developerforce.com/developer-relations/2013/10/salesforce-one-million-dollar-hackathon.html

 

Get the full details at: www.dreamforce.com/hackathon

 

Use this board to form teams, ask questions, and connect with your fellow developers!