text
stringlengths 24
5.1k
|
---|
(). auth.logindiscoveryexception throw this exception to indicate that an error occurred when executing the login discovery handler. for an example, see logindiscoveryhandler example implementation. to get the error message and write it to debug log, use the string getmessage(). auth.verificationexception throw this exception to trigger verification based on the passed-in policy. you can throw this exception in an apex trigger or visualforce controller. the system automatically sends you to the verification endpoint, if possible. note: you can’t catch this exception. the exception immediately triggers the verification. examples this example uses authproviderpluginexception to throw a custom exception in a custom authentication provider implementation. use this exception if you want the end user to see a specific message, passing in the error message as a parameter. if you use another exception, users see a standard salesforce error message. global override auth.oauthrefreshresult refresh(map<string,string> authproviderconfiguration,string refreshtoken){ httprequest req = new httprequest(); string accesstoken = null; string error = null; try { // developer todo: make a refresh token flow using refreshtoken passed // in as an argument to get the new access token // accesstoken = ... } catch (system.calloutexception e) { error = e.getmessage(); } 175apex reference guide cache namespace catch(exception e) { error = e.getmessage(); throw new auth.authproviderpluginexception('my custom error'); } return new auth.oauthrefreshresult(accesstoken,refreshtoken, error); } this example uses auth.verificationexception to trigger verification if a user attempts to create an account without a high assurance session. trigger testtrigger on account (before insert) { map<string, string> sessionmap = auth.sessionmanagement.getcurrentsession(); if(!sessionmap.get('sessionsecuritylevel').equals('high_assurance')) { throw new auth.verificationexception( auth.verificationpolicy.high_assurance, 'insert account'); } } cache namespace the cache namespace contains methods for managing the platform cache. the following are the classes in the cache namespace. in this section: cachebuilder interface an interface for safely retrieving and removing values from a session or org cache. use the interface to generate a value that you want to store in the cache. the interface checks for cache misses, which means you no longer need to check for null cache values yourself. org class use the cache.org class to add, retrieve, and manage values in the org cache. unlike the session cache, the org cache is not tied to any session and is available to the organization across requests and to all users. orgpartition class contains methods to manage cache values in the org cache of a specific partition. unlike the session cache, the org cache is not tied to any session. it’s available to the organization across requests and to all users. partition class base class of cache.orgpartition and cache.sessionpartition. use the subclasses to manage the cache partition for org caches and session caches. session class use the cache.session class to add, retrieve, and manage values in the session cache. the session cache is active as long as the user’s salesforce session is valid (the user is logged in, and the session is not expired). sessionpartition class contains methods to manage cache values in the session cache of a specific partition. cache exceptions the cache namespace contains exception classes. 176apex reference guide cachebuilder interface visibility enum use the cache.visibility enumeration in the cache.session or cache.org methods to indicate whether a cached value is visible only in the value’s namespace or in all namespaces. see also: apex developer guide: platform cache cachebuilder interface an interface for safely retrieving and removing values from a session or org cache. use the interface to generate a value that you want to store in the cache. the interface checks for cache misses, which means you no longer need to check for null cache values yourself. namespace cache in this section: cachebuilder methods cachebuilder example implementation see also: apex developer guide: safely cache values with the cachebuilder interface cachebuilder methods the following are methods for cachebuilder. in this section: doload(var) contains the logic that builds a cached value. you don’t call this method directly. instead, it’s called indirectly when you reference the class that implements |
the cachebuilder interface. doload(var) contains the logic that builds a cached value. you don’t call this method directly. instead, it’s called indirectly when you reference the class that implements the cachebuilder interface. signature public object doload(string var) parameters var type: string 177apex reference guide org class a case-sensitive string value used to build a cached value. this parameter is also used as part of the unique key that identifies the cached value. return value type: object the value that was cached. cast the return value to the appropriate type. cachebuilder example implementation this example creates a class called userinfocache that implements the cachebuilder interface. the class caches the results of a soql query run against the user object. class userinfocache implements cache.cachebuilder { public object doload(string userid) { user u = (user)[select id, isactive, username from user where id =: userid]; return u; } } this example gets a cached user record based on a user id. if the value exists in the org cache, it is returned. if the value doesn’t exist, the doload(string var) method is re-executed, and the new value is cached and returned. user batman = (user) cache.org.get(userinfocache.class, ‘00541000000ek4c'); org class use the cache.org class to add, retrieve, and manage values in the org cache. unlike the session cache, the org cache is not tied to any session and is available to the organization across requests and to all users. namespace cache usage cache key format this table lists the format of the key parameter that some methods in this class take, such as put, get, and contains. key format description namespace.partition.key fully qualified key name. key refers to a partition marked as default when the namespace.partition prefix is omitted. local.partition.key use the local prefix to refer to the org’s namespace when the org doesn’t have a namespace defined. if the org has a namespace defined, the local prefix also refers to that org’s namespace. 178apex reference guide org class note: • if no default partition is specified in the org, calling a cache method without fully qualifying the key name causes a cache.org.orgcacheexception to be thrown. • the local prefix in an installed managed package refers to the namespace of the subscriber org and not the package’s namespace. the cache put calls aren’t allowed in a partition that the invoking class doesn’t own. example this class is the controller for a sample visualforce page (shown in the subsequent code sample). the cached values are initially added to the cache by the init() method, which the visualforce page invokes when it loads through the action attribute. the cache keys don’t contain the namespace.partition prefix. they all refer to the default partition in your org. to run this sample, create a partition and mark it as default. the visualforce page contains four output components. these components call get methods on the controller that returns the following values from the cache: a date, data based on the mydata inner class, a counter, a text value, and a list. the size of the list is also returned. the visualforce page also contains two buttons. the rerender button invokes the go() method on the controller. this method increases the values of the counter and the custom data in the cache. when you click rerender, the two counters increase by one each time. the go() method retrieves the values of these counters from the cache, increments their values by one, and stores them again in the cache. the remove datetime key button deletes the date-time value (with key datetime) from the cache. as a result, the value next to cached datetime: is cleared on the page. note: if another user logs in and runs this sample, this user gets the cache values that were last added or updated by the previous user. for example, if the counter value was five, the next user sees the counter value as increased to six. public class orgcachecontroller { // inner class. // used as the data type of a cache value. class mydata { public string value { get; set; } public integer counter { get; set; } public mydata(string value) { this.value = value; this.counter = 0; } public void inc() { |
counter++; } override public string tostring() { return this.value + ':' + this.counter; } } // apex list. // used as the data type of a cached value. private list<string> numbers = new list<string> { 'one', 'two', 'three', 'four', 'five' }; 179apex reference guide org class // constructor of the controller for the visualforce page. public orgcachecontroller() { } // adds various values to the cache. // this method is called when the visualforce page loads. public void init() { // all key values are not qualified by the namespace.partition // prefix because they use the default partition. // add counter to the cache with initial value of 0 // or increment it if it's already there. if (!cache.org.contains('counter')) { cache.org.put('counter', 0); } else { cache.org.put('counter', getcounter() + 1); } // add the datetime value to the cache only if it's not already there. if (!cache.org.contains('datetime')) { datetime dt = datetime.now(); cache.org.put('datetime', dt); } // add the custom data to the cache only if it's not already there. if (!cache.org.contains('data')) { cache.org.put('data', new mydata('some custom value')); } // add a list of number to the cache if not already there. if (!cache.org.contains('list')) { cache.org.put('list', numbers); } // add a string value to the cache if not already there. if (!cache.org.contains('output')) { cache.org.put('output', 'cached text value'); } } // return counter from the cache. public integer getcounter() { return (integer)cache.org.get('counter'); } // return datetime value from the cache. public string getcacheddatetime() { datetime dt = (datetime)cache.org.get('datetime'); return dt != null ? dt.format() : null; } // return cached value whose type is the inner class mydata. public string getcacheddata() { 180apex reference guide org class mydata mydata = (mydata)cache.org.get('data'); return mydata != null ? mydata.tostring() : null; } // return output from the cache. public string getoutput() { return (string)cache.org.get('output'); } // return list from the cache. public list<string> getlist() { return (list<string>)cache.org.get('list'); } // method invoked by the rerender button on the visualforce page. // updates the values of various cached values. // increases the values of counter and the mydata counter if those // cache values are still in the cache. public pagereference go() { // increase the cached counter value or set it to 0 // if it's not cached. if (cache.org.contains('counter')) { cache.org.put('counter', getcounter() + 1); } else { cache.org.put('counter', 0); } // get the custom data value from the cache. mydata d = (mydata)cache.org.get('data'); // only if the data is already in the cache, update it. if (cache.org.contains('data')) { d.inc(); cache.org.put('data', d); } return null; } // method invoked by the remove button on the visualforce page. // removes the datetime cached value from the org cache. public pagereference remove() { cache.org.remove('datetime'); return null; } } this is the visualforce page that corresponds to the orgcachecontroller class. <apex:page controller="orgcachecontroller" action="{!init}"> <apex:outputpanel id="output"> <br/>cached datetime: <apex:outputtext value="{!cacheddatetime}"/> <br/>cached data: <apex:outputtext value="{!cacheddata}"/> <br/>cached counter: <apex:outputtext value="{! |
counter}"/> 181apex reference guide org class <br/>output: <apex:outputtext value="{!output}"/> <br/>repeat: <apex:repeat var="item" value="{!list}"> <apex:outputtext value="{!item}"/> </apex:repeat> <br/>list size: <apex:outputtext value="{!list.size}"/> </apex:outputpanel> <br/><br/> <apex:form > <apex:commandbutton id="go" action="{!go}" value="rerender" rerender="output"/> <apex:commandbutton id="remove" action="{!remove}" value="remove datetime key" rerender="output"/> </apex:form> </apex:page> this is the output of the page after clicking the rerender button twice. the counter value could differ in your case if a key named counter was already in the cache before running this sample. cached datetime:8/11/2015 1:58 pm cached data:some custom value:2 cached counter:2 output:cached text value repeat:one two three four five list size:5 in this section: org constants the org class provides a constant that you can use when setting the time-to-live (ttl) value. org methods see also: apex developer guide: platform cache org constants the org class provides a constant that you can use when setting the time-to-live (ttl) value. constant description max_ttl_secs represents the maximum amount of time, in seconds, to keep the cached value in the org cache. org methods the following are methods for org. all methods are static. 182 |
apex reference guide org class in this section: contains(key) returns true if the org cache contains a cached value corresponding to the specified key. contains(keys) returns true if the org cache contains values for the specified key entries. contains(setofkeys) returns true if the org cache contains values for a specified set of keys. get(key) returns the cached value corresponding to the specified key from the org cache. get(cachebuilder, key) returns the cached value corresponding to the specified key from the org cache. use this method if your cached value is a class that implements the cachebuilder interface. get(keys) returns the cached values corresponding to the specified set of keys from the org cache. getavggetsize() returns the average item size of all the keys fetched from the org cache, in bytes. getavggettime() returns the average time taken to get a key from the org cache, in nanoseconds. getavgvaluesize() deprecated and available only in api versions 49.0 and earlier. returns the average item size for keys in the org cache, in bytes. getcapacity() returns the percentage of org cache capacity that has been used. getkeys() returns a set of all keys that are stored in the org cache and visible to the invoking namespace. getmaxgetsize() returns the maximum item size of all the keys fetched from the org cache, in bytes. getmaxgettime() returns the maximum time taken to get a key from the org cache, in nanoseconds. getmaxvaluesize() deprecated and available only in api versions 49.0 and earlier. returns the maximum item size for keys in the org cache, in bytes. getmissrate() returns the miss rate in the org cache. getname() returns the name of the default cache partition. getnumkeys() returns the total number of keys in the org cache. getpartition(partitionname) returns a partition from the org cache that corresponds to the specified partition name. 183apex reference guide org class put(key, value) stores the specified key/value pair as a cached entry in the org cache. the put method can write only to the cache in your org’s namespace. put(key, value, visibility) stores the specified key/value pair as a cached entry in the org cache and sets the cached value’s visibility. put(key, value, ttlsecs) stores the specified key/value pair as a cached entry in the org cache and sets the cached value’s lifetime. put(key, value, ttlsecs, visibility, immutable) stores the specified key/value pair as a cached entry in the org cache. this method also sets the cached value’s lifetime, visibility, and whether it can be overwritten by another namespace. remove(key) deletes the cached value corresponding to the specified key from the org cache. remove(cachebuilder, key) deletes the cached value corresponding to the specified key from the org cache. use this method if your cached value is a class that implements the cachebuilder interface. contains(key) returns true if the org cache contains a cached value corresponding to the specified key. signature public static boolean contains(string key) parameters key type: string a case-sensitive string value that uniquely identifies a cached value. for information about the format of the key name, see usage. return value type: boolean true if a cache entry is found. othewise, false. contains(keys) returns true if the org cache contains values for the specified key entries. signature public static list<boolean> contains(list<string> keys) parameters keys type: list<string> 184apex reference guide org class a list of keys that identifies cached values. for information about the format of the key name, see usage. return value type: list<boolean> true if the key entries are found. othewise, false. contains(setofkeys) returns true if the org cache contains values for a specified set of keys. signature public static map <string, boolean> contains (set<string> keys) parameters setofkeys type: set <string> a set of keys that uniquely identifies cached values. for information about the format of the key name, see usage return value type: map <string, boolean> returns the cache key and corresponding boolean value indicating that the key entry exists. the boolean value is |
false if the key entry doesn't exist. usage the number of input keys cannot exceed the maximum limit of 10. example in this example, the code checks for the presence of multiple keys on the default partition. it fetches the cache key and the corresponding boolean value for the key entry from the org cache of the default partition. set<string> keys = new set<string>{'key1','key2','key3','key4','key5'}; map<string,boolean> result = cache.org.contains(keys); for(string key : result.keyset()) { system.debug('key: ' + key); system.debug('is key present in the cache : ' + result.get(key)); } in this example, the code checks for the presence of multiple keys on different partitions. it fetches the cache key and the corresponding boolean value for the key entry from the org cache of different partitions. // assuming there are three partitions p1, p2, p3 with default 'local' namespace set<string> keys = new set<string>{'local.p1.key','local.p2.key', 'local.p3.key'}; map<string,boolean> result = cache.org.contains(keys); for(string key : result.keyset()) { 185apex reference guide org class system.debug('key: ' + key); system.debug('is key present in the cache : + result.get(key)); } get(key) returns the cached value corresponding to the specified key from the org cache. signature public static object get(string key) parameters key type: string a case-sensitive string value that uniquely identifies a cached value. for information about the format of the key name, see usage. return value type: object the cached value as a generic object type. cast the returned value to the appropriate type. usage because cache.org.get() returns an object, cast the returned value to a specific type to facilitate use of the returned value. // get a cached value object obj = cache.org.get('ns1.partition1.orderdate'); // cast return value to a specific data type datetime dt2 = (datetime)obj; if a cache.org.get() call doesn’t find the referenced key, it returns null. get(cachebuilder, key) returns the cached value corresponding to the specified key from the org cache. use this method if your cached value is a class that implements the cachebuilder interface. signature public static object get(system.type cachebuilder, string key) parameters cachebuilder type: system.type the apex class that implements the cachebuilder interface. 186apex reference guide org class key type: string a case-sensitive string value that, combined with the class name corresponding to the cachebuilder parameter, uniquely identifies a cached value. return value type: object the cached value as a generic object type. cast the returned value to the appropriate type. usage because cache.org.get(cachebuilder, key) returns an object, cast the returned value to a specific type to facilitate use of the returned value. return ((datetime)cache.org.get(datecache.class, 'datetime')).format(); get(keys) returns the cached values corresponding to the specified set of keys from the org cache. signature public static map <string, object> get (set <string> keys) parameters keys type: set <string> a set of keys that uniquely identify cached values. for information about the format of the key name, see usage. return value type: map <string, object> returns the cache key and corresponding value. returns null when no corresponding value is found for an input key. usage the number of input keys cannot exceed the maximum limit of 10. examples fetch multiple keys from the org cache of the default partition. set<string> keys = new set<string>{'key1','key2','key3','key4','key5'}; map<string,object> result = cache.org.get(keys); for(string key : result.keyset()) { system.debug('key: ' + key); system.debug('value: ' + result.get(key)); } 187apex reference guide org class fetch multiple keys from the org cache of different partitions. // assuming there are three partitions p1, p2, p3 with default 'local' namespace set< |
string> keys = new set<string>{'local.p1.key','local.p2.key', 'local.p3.key'}; map<string,object> result = cache.org.get(keys); for(string key : result.keyset()) { system.debug('key: ' + key); system.debug('value: ' + result.get(key)); } getavggetsize() returns the average item size of all the keys fetched from the org cache, in bytes. signature public static long getavggetsize() return value type: long example in this example the following keys and their corresponding value sizes are inserted. the code then fetches the keys: key 1, key 2, key 3 and key 4 and returns the average item size of the fetched keys. key key value size key 1 42 key 2 42 key 3 58 key 4 36 key 5 36 // inserting keys key1, key2, key3, key4, key5 cache.org.put('key1', 'value1'); cache.org.put('key2', 'value2'); cache.org.put('key3', 'this is a big value !!!'); cache.org.put('key4', 4); cache.org.put('key5', 5); // fetching keys - key1, key2, key3, key4 object v1 = cache.org.get('key1'); object v2 = cache.org.get('key2'); object v3 = cache.org.get('key3'); object v4 = cache.org.get('key4'); 188apex reference guide org class // fetching average get size long val = cache.org.getavggetsize(); // avg item size returned is 44 ( average of 42(key1), 42(key2), 58(key3) and 36(key4) keys that were fetched ) system.debug('avg get size :' + val); getavggettime() returns the average time taken to get a key from the org cache, in nanoseconds. signature public static long getavggettime() return value type: long getavgvaluesize() deprecated and available only in api versions 49.0 and earlier. returns the average item size for keys in the org cache, in bytes. signature public static long getavgvaluesize() return value type: long getcapacity() returns the percentage of org cache capacity that has been used. signature public static double getcapacity() return value type: double used cache as a percentage number. getkeys() returns a set of all keys that are stored in the org cache and visible to the invoking namespace. 189apex reference guide org class signature public static set<string> getkeys() return value type: set<string> a set containing all cache keys. getmaxgetsize() returns the maximum item size of all the keys fetched from the org cache, in bytes. signature public static long getmaxgetsize() return value type: long example in this example the following keys and their corresponding value sizes are inserted. the code fetches the keys: key 1, key 2 and key 4 and returns the maximum key value size from the fetched keys. key key value size key 1 42 key 2 42 key 3 58 key 4 36 key 5 36 // inserting keys key1, key2, key3, key4, key5 cache.org.put('key1', 'value1'); cache.org.put('key2', 'value2'); cache.org.put('key3', 'this is a big value !!!'); cache.org.put('key4', 4); cache.org.put('key5', 5); // fetching keys - key1, key2, key4 object v1 = cache.org.get('key1'); object v2 = cache.org.get('key2'); object v4 = cache.org.get('key4'); // fetching max get size 190apex reference guide org class long val = cache.org.getmaxgetsize(); // max item size returned is 42 ( max of 42(key1), 42(key2), and 36(key4) keys that were fetched ) system.debug('max get size :' + val); getmaxgettime() returns the maximum time taken to get a key from the org |
cache, in nanoseconds. signature public static long getmaxgettime() return value type: long getmaxvaluesize() deprecated and available only in api versions 49.0 and earlier. returns the maximum item size for keys in the org cache, in bytes. signature public static long getmaxvaluesize() return value type: long getmissrate() returns the miss rate in the org cache. signature public static double getmissrate() return value type: double getname() returns the name of the default cache partition. signature public string getname() 191apex reference guide org class return value type: string the name of the default cache partition. getnumkeys() returns the total number of keys in the org cache. signature public static long getnumkeys() return value type: long getpartition(partitionname) returns a partition from the org cache that corresponds to the specified partition name. signature public static cache.orgpartition getpartition(string partitionname) parameters partitionname type: string a partition name that is qualified by the namespace, for example, namespace.partition. return value type: cache.orgpartition example after you get the org partition, you can add and retrieve the partition’s cache values. // get partition cache.orgpartition orgpart = cache.org.getpartition('myns.mypartition'); // retrieve cache value from the partition if (orgpart.contains('booktitle')) { string cachedtitle = (string)orgpart.get('booktitle'); } // add cache value to the partition orgpart.put('orderdate', date.today()); // or use dot notation to call partition methods string cachedauthor = (string)cache.org.getpartition('myns.mypartition').get('bookauthor'); 192apex reference guide org class put(key, value) stores the specified key/value pair as a cached entry in the org cache. the put method can write only to the cache in your org’s namespace. signature public static void put(string key, object value) parameters key type: string a case-sensitive string value that uniquely identifies a cached value. for information about the format of the key name, see usage. value type: object the value to store in the cache. the cached value must be serializable. return value type: void put(key, value, visibility) stores the specified key/value pair as a cached entry in the org cache and sets the cached value’s visibility. signature public static void put(string key, object value, cache.visibility visibility) parameters key type: string a case-sensitive string value that uniquely identifies a cached value. for information about the format of the key name, see usage. value type: object the value to store in the cache. the cached value must be serializable. visibility type: cache.visibility indicates whether the cached value is available only to apex code that is executing in the same namespace or to apex code executing from any namespace. return value type: void 193apex reference guide org class put(key, value, ttlsecs) stores the specified key/value pair as a cached entry in the org cache and sets the cached value’s lifetime. signature public static void put(string key, object value, integer ttlsecs) parameters key type: string a case-sensitive string value that uniquely identifies a cached value. for information about the format of the key name, see usage. value type: object the value to store in the cache. the cached value must be serializable. ttlsecs type: integer the amount of time, in seconds, to keep the cached value in the org cache. the maximum is 172,800 seconds (48 hours). the minimum value is 300 seconds or 5 minutes. the default value is 86,400 seconds (24 hours). return value type: void put(key, value, ttlsecs, visibility, immutable) stores the specified key/value pair as a cached entry in the org cache. this method also sets the cached value’s lifetime, visibility, and whether it can be overwritten by another namespace. signature public static void put(string key, object value, integer ttlsecs, cache.visibility visibility, boolean immutable) parameters key type: string |
a case-sensitive string value that uniquely identifies a cached value. for information about the format of the key name, see usage. value type: object the value to store in the cache. the cached value must be serializable. ttlsecs type: integer the amount of time, in seconds, to keep the cached value in the org cache. the maximum is 172,800 seconds (48 hours). the minimum value is 300 seconds or 5 minutes. the default value is 86,400 seconds (24 hours). 194apex reference guide org class visibility type: cache.visibility indicates whether the cached value is available only to apex code that is executing in the same namespace or to apex code executing from any namespace. immutable type: boolean indicates whether the cached value can be overwritten by another namespace (false) or not (true). return value type: void remove(key) deletes the cached value corresponding to the specified key from the org cache. signature public static boolean remove(string key) parameters key type: string a case-sensitive string value that uniquely identifies a cached value. for information about the format of the key name, see usage. return value type: boolean true if the cache value was successfully removed. otherwise, false. remove(cachebuilder, key) deletes the cached value corresponding to the specified key from the org cache. use this method if your cached value is a class that implements the cachebuilder interface. signature public static boolean remove(system.type cachebuilder, string key) parameters cachebuilder type: system.type the apex class that implements the cachebuilder interface. key type: string 195apex reference guide orgpartition class a case-sensitive string value that, combined with the class name corresponding to the cachebuilder parameter, uniquely identifies a cached value. return value type: boolean true if the cache value was successfully removed. otherwise, false. orgpartition class contains methods to manage cache values in the org cache of a specific partition. unlike the session cache, the org cache is not tied to any session. it’s available to the organization across requests and to all users. namespace cache usage this class extends cache.partition and inherits all its non-static methods. utility methods for creating and validating keys aren’t supported and can be called only from the cache.partition parent class. for a list of cache.partition methods, see partition methods. to get an org partition, call cache.org.getpartition and pass in a fully qualified partition name, as follows. cache.orgpartition orgpartition = cache.org.getpartition('namespace.mypartition'); see cache key format for partition methods. example this class is the controller for a sample visualforce page (shown in the subsequent code sample). the controller shows how to use the methods of cache.orgpartition to manage a cache value on a particular partition. the controller takes inputs from the visualforce page for the partition name, key name for a counter, and initial counter value. the controller contains default values for these inputs. when you click rerender on the visualforce page, the go() method is invoked and increases the counter by one. when you click remove key, the counter key is removed from the cache. the counter value gets reset to its initial value when it’s re-added to the cache. note: if another user logs in and runs this sample, the user gets the cache values that were last added or updated by the previous user. for example, if the counter value was five, the next user sees the counter value as increased to six. public class orgpartitioncontroller { // name of a partition string partitioninput = 'local.mypartition'; // name of the key string counterkeyinput = 'counter'; // key initial value integer counterinitvalue = 0; // org partition object cache.orgpartition orgpartition; // constructor of the controller for the visualforce page. public orgpartitioncontroller() { 196apex reference guide orgpartition class } // adds counter value to the cache. // this method is called when the visualforce page loads. public void init() { // create the partition instance based on the partition name orgpartition = getpartition(); // create the partition instance based on the partition name // given in the visualforce page or the default value. orgpartition = cache.org.getpartition(partitioninput); // add counter to the cache with an |
initial value // or increment it if it's already there. if (!orgpartition.contains(counterkeyinput)) { orgpartition.put(counterkeyinput, counterinitvalue); } else { orgpartition.put(counterkeyinput, getcounter() + 1); } } // returns the org partition based on the partition name // given in the visualforce page or the default value. private cache.orgpartition getpartition() { if (orgpartition == null) { orgpartition = cache.org.getpartition(partitioninput); } return orgpartition; } // return counter from the cache. public integer getcounter() { return (integer)getpartition().get(counterkeyinput); } // invoked by the submit button to save input values // supplied by the user. public pagereference save() { // reset the initial key value in the cache getpartition().put(counterkeyinput, counterinitvalue); return null; } // method invoked by the rerender button on the visualforce page. // updates the values of various cached values. // increases the values of counter and the mydata counter if those // cache values are still in the cache. public pagereference go() { // get the org partition object orgpartition = getpartition(); // increase the cached counter value or set it to 0 197apex reference guide orgpartition class // if it's not cached. if (orgpartition.contains(counterkeyinput)) { orgpartition.put(counterkeyinput, getcounter() + 1); } else { orgpartition.put(counterkeyinput, counterinitvalue); } return null; } // method invoked by the remove button on the visualforce page. // removes the datetime cached value from the org cache. public pagereference remove() { getpartition().remove(counterkeyinput); return null; } // get and set methods for accessing variables // that correspond to the input text fields on // the visualforce page. public string getpartitioninput() { return partitioninput; } public string getcounterkeyinput() { return counterkeyinput; } public integer getcounterinitvalue() { return counterinitvalue; } public void setpartitioninput(string partition) { this.partitioninput = partition; } public void setcounterkeyinput(string keyname) { this.counterkeyinput = keyname; } public void setcounterinitvalue(integer countervalue) { this.counterinitvalue = countervalue; } } this is the visualforce page that corresponds to the orgpartitioncontroller class. <apex:page controller="orgpartitioncontroller" action="{!init}"> <apex:form > <br/>partition with namespace prefix: <apex:inputtext value="{!partitioninput}"/> <br/>counter key name: <apex:inputtext value="{!counterkeyinput}"/> <br/>counter initial value: <apex:inputtext value="{!counterinitvalue}"/> 198apex reference guide partition class <apex:commandbutton action="{!save}" value="save key input values"/> </apex:form> <apex:outputpanel id="output"> <br/>cached counter: <apex:outputtext value="{!counter}"/> </apex:outputpanel> <br/> <apex:form > <apex:commandbutton id="go" action="{!go}" value="rerender" rerender="output"/> <apex:commandbutton id="remove" action="{!remove}" value="remove key" rerender="output"/> </apex:form> </apex:page> see also: apex developer guide: platform cache partition class base class of cache.orgpartition and cache.sessionpartition. use the subclasses to manage the cache partition for org caches and session caches. namespace cache cache key format for partition methods after you obtain the partition object (an instance of cache.orgpartition or cache.sessionpartition), the methods to add, retrieve, and manage the cache values in a partition take the key name. the key name that you supply to these methods (get(), put(), remove(), and contains()) doesn’t include the namespace.partition prefix. in this section: partition methods see also: org |
partition class sessionpartition class apex developer guide: platform cache partition methods the following are methods for partition. 199apex reference guide partition class in this section: contains(key) returns true if the cache partition contains a cached value corresponding to the specified key. contains(setofkeys) returns true if the cache partition contains values for a specified set of keys. createfullyqualifiedkey(namespace, partition, key) generates a fully qualified key from the passed-in key components. the format of the generated key string is namespace.partition.key. createfullyqualifiedpartition(namespace, partition) generates a fully qualified partition name from the passed-in namespace and partition. the format of the generated partition string is namespace.partition. get(key) returns the cached value corresponding to the specified key from the cache partition. get(keys) returns the cached values corresponding to the specified set of keys from the cache partition. get(cachebuilder, key) returns the cached value corresponding to the specified key from the partition cache. use this method if your cached value is a class that implements the cachebuilder interface. getavggetsize() returns the average item size of all the keys fetched from the partition, in bytes. getavggettime() returns the average time taken to get a key from the partition, in nanoseconds. getavgvaluesize() deprecated and available only in api versions 49.0 and earlier. returns the average item size for keys in the partition, in bytes. getcapacity() returns the percentage of cache used of the total capacity for this partition. getkeys() returns a set of all keys that are stored in the cache partition and visible to the invoking namespace. getmaxgetsize() returns the maximum item size of all the keys fetched from the partition, in bytes. getmaxgettime() returns the maximum time taken to get a key from the partition, in nanoseconds. getmaxvaluesize() deprecated and available only in api versions 49.0 and earlier. returns the maximum item size for keys in the partition, in bytes. getmissrate() returns the miss rate in the partition. getname() returns the name of this cache partition. getnumkeys() returns the total number of keys in the partition. 200apex reference guide partition class isavailable() returns true if the salesforce session is available. only applies to cache.sessionpartition. the session cache isn’t available when an active session isn’t present, such as in asynchronous apex or code called by asynchronous apex. for example, if batch apex causes an apex trigger to execute, the session cache isn’t available in the trigger because the trigger runs in asynchronous context. put(key, value) stores the specified key/value pair as a cached entry in the cache partition. the put method can write only to the cache in your org’s namespace. put(key, value, visibility) stores the specified key/value pair as a cached entry in the cache partition and sets the cached value’s visibility. put(key, value, ttlsecs) stores the specified key/value pair as a cached entry in the cache partition and sets the cached value’s lifetime. put(key, value, ttlsecs, visibility, immutable) stores the specified key/value pair as a cached entry in the cache partition. this method also sets the cached value’s lifetime, visibility, and whether it can be overwritten by another namespace. remove(key) deletes the cached value corresponding to the specified key from this cache partition. remove(cachebuilder, key) deletes the cached value corresponding to the specified key from the partition cache. use this method if your cached value is a class that implements the cachebuilder interface. validatecachebuilder(cachebuilder) validates that the specified class implements the cachebuilder interface. validatekey(isdefault, key) validates a cache key. this method throws a cache.invalidparamexception if the key is not valid. a valid key is not null and contains alphanumeric characters. validatekeyvalue(isdefault, key, value) validates a cache key and ensures that the cache value is non-null. this method throws a cache.invalidparamexception if the key or value is not valid. a valid key is not null and contains alphanumeric characters. validatekeys(isdefault, keys) validates the specified cache keys. this method throws a cache.invalidparamexception if |
the key is not valid. a valid key is not null and contains alphanumeric characters. validatepartitionname(name) validates the partition name — for example, that it is not null. contains(key) returns true if the cache partition contains a cached value corresponding to the specified key. signature public boolean contains(string key) 201apex reference guide partition class parameters key type: string a case-sensitive string value that uniquely identifies a cached value. return value type: boolean true if a cache entry is found. othewise, false. contains(setofkeys) returns true if the cache partition contains values for a specified set of keys. signature public map <string, boolean> contains (set<string> keys) parameters setofkeys type: set <string> a set of keys that uniquely identifies cached values. for information about the format of the key name, see usage. return value type: map <string, boolean> returns the cache key and corresponding boolean value indicating that the key entry exists. the boolean value is false if the key entry doesn't exist. usage the number of input keys cannot exceed the maximum limit of 10. example in this example, the code checks for the presence of multiple keys on a partition. it fetches the cache key and the corresponding boolean value for the key entry from the org cache of the partition. // assuming there is a partition p1 in the default 'local' namespace set<string> keys = new set<string>{'key1','key2','key3','key4','key5'}; cache.orgpartition orgpart = cache.org.getpartition('local.p1'); map<string,boolean> result = orgpart.contains(keys); for(string key : result.keyset()) { system.debug('key: ' + key); system.debug('is key present in the cache:' + result.get(key)); } 202apex reference guide partition class in this example, the code checks for the presence of multiple keys on a partition. it fetches the cache key and the corresponding boolean value for the key entry from the session cache of the partition. // assuming there are three partitions p1, p2, p3 with default 'local' namespace set<string> keys = new set<string>{'key1','key2','key3','key4','key5'}; cache.sessionpartition sessionpart = cache.session.getpartition('local.p1'); map<string,boolean> result = sessionpart.contains(keys); for(string key : result.keyset()) { system.debug('key: ' + key); system.debug('value: ' + result.get(key)); } createfullyqualifiedkey(namespace, partition, key) generates a fully qualified key from the passed-in key components. the format of the generated key string is namespace.partition.key. signature public static string createfullyqualifiedkey(string namespace, string partition, string key) parameters namespace type: string the namespace of the cache key. partition type: string the partition of the cache key. key type: string the name of the cache key. return value type: string createfullyqualifiedpartition(namespace, partition) generates a fully qualified partition name from the passed-in namespace and partition. the format of the generated partition string is namespace.partition. signature public static string createfullyqualifiedpartition(string namespace, string partition) 203apex reference guide partition class parameters namespace type: string the namespace of the cache key. partition type: string the partition of the cache key. return value type: string get(key) returns the cached value corresponding to the specified key from the cache partition. signature public object get(string key) parameters key type: string a case-sensitive string value that uniquely identifies a cached value. return value type: object the cached value as a generic object type. cast the returned value to the appropriate type. get(keys) returns the cached values corresponding to the specified set of keys from the cache partition. signature public map <string, object> get (set <string> keys) parameters keys type: set <string> a set of keys that uniquely identify cached values. for information about the format of the key name, see usage. return value |
type: map <string, object> 204apex reference guide partition class returns the cache key and corresponding value. returns null when no corresponding value is found for an input key. usage the number of input keys cannot exceed the maximum limit of 10. examples fetch multiple keys from the org cache of a partition. // assuming there is a partition p1 in the default 'local' namespace set<string> keys = new set<string>{'key1','key2','key3','key4','key5'}; cache.orgpartition orgpart = cache.org.getpartition('local.p1'); map<string,object> result = orgpart.get(keys); for(string key : result.keyset()) { system.debug('key: ' + key); system.debug('value: ' + result.get(key)); } fetch multiple keys from the session cache of a partition. // assuming there is a partition p1 in the default 'local' namespace set<string> keys = new set<string>{'key1','key2','key3','key4','key5'}; cache.sessionpartition sessionpart = cache.session.getpartition('local.p1'); map<string,object> result = sessionpart.get(keys); for(string key : result.keyset()) { system.debug('key: ' + key); system.debug('value: ' + result.get(key)); } get(cachebuilder, key) returns the cached value corresponding to the specified key from the partition cache. use this method if your cached value is a class that implements the cachebuilder interface. signature public object get(system.type cachebuilder, string key) parameters cachebuilder type: system.type the apex class that implements the cachebuilder interface. key type: string a case-sensitive string value that, combined with the class name corresponding to the cachebuilder parameter, uniquely identifies a cached value. 205apex reference guide partition class return value type: object the cached value as a generic object type. cast the returned value to the appropriate type. getavggetsize() returns the average item size of all the keys fetched from the partition, in bytes. signature public long getavggetsize() return value type: long getavggettime() returns the average time taken to get a key from the partition, in nanoseconds. signature public long getavggettime() return value type: long getavgvaluesize() deprecated and available only in api versions 49.0 and earlier. returns the average item size for keys in the partition, in bytes. signature public long getavgvaluesize() return value type: long getcapacity() returns the percentage of cache used of the total capacity for this partition. signature public double getcapacity() 206apex reference guide partition class return value type: double used partition cache as a percentage number. getkeys() returns a set of all keys that are stored in the cache partition and visible to the invoking namespace. signature public set<string> getkeys() return value type: set<string> a set containing all cache keys. getmaxgetsize() returns the maximum item size of all the keys fetched from the partition, in bytes. signature public long getmaxgetsize() return value type: long getmaxgettime() returns the maximum time taken to get a key from the partition, in nanoseconds. signature public long getmaxgettime() return value type: long getmaxvaluesize() deprecated and available only in api versions 49.0 and earlier. returns the maximum item size for keys in the partition, in bytes. signature public long getmaxvaluesize() 207apex reference guide partition class return value type: long getmissrate() returns the miss rate in the partition. signature public double getmissrate() return value type: double getname() returns the name of this cache partition. signature public string getname() return value type: string the name of this cache partition. getnumkeys() returns the total number of keys in the partition. signature public long getnumkeys() return value type: long isavailable() returns true if the salesforce session is available. only applies to cache.sessionpartition. the session cache isn’t available when an active session isn’t present, |
such as in asynchronous apex or code called by asynchronous apex. for example, if batch apex causes an apex trigger to execute, the session cache isn’t available in the trigger because the trigger runs in asynchronous context. signature public boolean isavailable() 208apex reference guide partition class return value type: boolean put(key, value) stores the specified key/value pair as a cached entry in the cache partition. the put method can write only to the cache in your org’s namespace. signature public void put(string key, object value) parameters key type: string a case-sensitive string value that uniquely identifies a cached value. value type: object the value to store in the cache. the cached value must be serializable. return value type: void put(key, value, visibility) stores the specified key/value pair as a cached entry in the cache partition and sets the cached value’s visibility. signature public void put(string key, object value, cache.visibility visibility) parameters key type: string a case-sensitive string value that uniquely identifies a cached value. value type: object the value to store in the cache. the cached value must be serializable. visibility type: cache.visibility indicates whether the cached value is available only to apex code that is executing in the same namespace or to apex code executing from any namespace. 209apex reference guide partition class return value type: void put(key, value, ttlsecs) stores the specified key/value pair as a cached entry in the cache partition and sets the cached value’s lifetime. signature public void put(string key, object value, integer ttlsecs) parameters key type: string a case-sensitive string value that uniquely identifies a cached value. value type: object the value to store in the cache. the cached value must be serializable. ttlsecs type: integer the amount of time, in seconds, to keep the cached value in the cache. return value type: void put(key, value, ttlsecs, visibility, immutable) stores the specified key/value pair as a cached entry in the cache partition. this method also sets the cached value’s lifetime, visibility, and whether it can be overwritten by another namespace. signature public void put(string key, object value, integer ttlsecs, cache.visibility visibility, boolean immutable) parameters key type: string a case-sensitive string value that uniquely identifies a cached value. value type: object the value to store in the cache. the cached value must be serializable. ttlsecs type: integer 210apex reference guide partition class the amount of time, in seconds, to keep the cached value in the cache. visibility type: cache.visibility indicates whether the cached value is available only to apex code that is executing in the same namespace or to apex code executing from any namespace. immutable type: boolean indicates whether the cached value can be overwritten by another namespace (false) or not (true). return value type: void remove(key) deletes the cached value corresponding to the specified key from this cache partition. signature public boolean remove(string key) parameters key type: string a case-sensitive string value that uniquely identifies a cached value. return value type: boolean true if the cache value was successfully removed. otherwise, false. remove(cachebuilder, key) deletes the cached value corresponding to the specified key from the partition cache. use this method if your cached value is a class that implements the cachebuilder interface. signature public boolean remove(system.type cachebuilder, string key) parameters cachebuilder type: system.type the apex class that implements the cachebuilder interface. key type: string 211apex reference guide partition class a case-sensitive string value that, combined with the class name corresponding to the cachebuilder parameter, uniquely identifies a cached value. return value type: boolean true if the cache value was successfully removed. otherwise, false. validatecachebuilder(cachebuilder) validates that the specified class implements the cachebuilder interface. signature public static void validatecachebuilder(system.type cachebuilder) parameters cachebuilder type: system.type the class to validate. return value type: void validatekey(isdefault, key) validates a cache key |
. this method throws a cache.invalidparamexception if the key is not valid. a valid key is not null and contains alphanumeric characters. signature public static void validatekey(boolean isdefault, string key) parameters isdefault type: boolean set to true if the key references a default partition. otherwise, set to false. key type: string the key to validate. return value type: void 212apex reference guide partition class validatekeyvalue(isdefault, key, value) validates a cache key and ensures that the cache value is non-null. this method throws a cache.invalidparamexception if the key or value is not valid. a valid key is not null and contains alphanumeric characters. signature public static void validatekeyvalue(boolean isdefault, string key, object value) parameters isdefault type: boolean set to true if the key references a default partition. otherwise, set to false. key type: string the key to validate. value type: object the cache value to validate. return value type: void validatekeys(isdefault, keys) validates the specified cache keys. this method throws a cache.invalidparamexception if the key is not valid. a valid key is not null and contains alphanumeric characters. signature public static void validatekeys(boolean isdefault, set<string> keys) parameters isdefault type: boolean set to true if the key references a default partition. otherwise, set to false. keys type: set<string> a set of key string values to validate. return value type: void 213apex reference guide session class validatepartitionname(name) validates the partition name — for example, that it is not null. signature public static void validatepartitionname(string name) parameters name type: string the name of the partition to validate. return value type: void session class use the cache.session class to add, retrieve, and manage values in the session cache. the session cache is active as long as the user’s salesforce session is valid (the user is logged in, and the session is not expired). namespace cache usage cache key format this table lists the format of the key parameter that some methods in this class take, such as put, get, and contains. key format description namespace.partition.key fully qualified key name. key refers to a partition marked as default when the namespace.partition prefix is omitted. local.partition.key use the local prefix to refer to the org’s namespace when the org doesn’t have a namespace defined. if the org has a namespace defined, the local prefix also refers to that org’s namespace. note: • if no default partition is specified in the org, calling a cache method without fully qualifying the key name causes a cache.session.sessioncacheexception to be thrown. • the local prefix in an installed managed package refers to the namespace of the subscriber org and not the package’s namespace. the cache put calls are not allowed in a partition that the invoking class doesn’t own. 214apex reference guide session class example this class is the controller for a sample visualforce page (shown in the subsequent code sample). the cached values are initially added to the cache by the init() method, which the visualforce page invokes when it loads through the action attribute. the cache keys don’t contain the namespace.partition prefix. they all refer to a default partition in your org. the visualforce page expects a partition named mypartition. to run this sample, create a default partition in your org with the name mypartition. the visualforce page contains four output components. the first three components call get methods on the controller that return the following values from the cache: a date, data based on the mydata inner class, and a counter. the next output component uses the $cache.session global variable to get the cached string value for the key named output. next, the $cache.session global variable is used again in the visualforce page to iterate over the elements of a cached value of type list. the size of the list is also returned. the visualforce page also contains two buttons. the rerender button invokes the go() method on the controller. this method increases the values of the counter and the custom data in the cache. if you click rerender, the two counters increase by one each time. the go() method retrieves the values of these counters from the |
cache, increments their values by one, and stores them again in the cache. the remove button deletes the date-time value (with key datetime) from the cache. as a result, the value next to cached datetime: is cleared on the page. public class sessioncachecontroller { // inner class. // used as the data type of a cache value. class mydata { public string value { get; set; } public integer counter { get; set; } public mydata(string value) { this.value = value; this.counter = 0; } public void inc() { counter++; } override public string tostring() { return this.value + ':' + this.counter; } } // apex list. // used as the data type of a cached value. private list<string> numbers = new list<string> { 'one', 'two', 'three', 'four', 'five' }; // constructor of the controller for the visualforce page. public sessioncachecontroller() { } // adds various values to the cache. // this method is called when the visualforce page loads. public void init() { 215apex reference guide session class // all key values are not qualified by the namespace.partition // prefix because they use the default partition. // add counter to the cache with initial value of 0 // or increment it if it's already there. if (!cache.session.contains('counter')) { cache.session.put('counter', 0); } else { cache.session.put('counter', getcounter() + 1); } // add the datetime value to the cache only if it's not already there. if (!cache.session.contains('datetime')) { datetime dt = datetime.now(); cache.session.put('datetime', dt); } // add the custom data to the cache only if it's not already there. if (!cache.session.contains('data')) { cache.session.put('data', new mydata('some custom value')); } // add a list of number to the cache if not already there. if (!cache.session.contains('list')) { cache.session.put('list', numbers); } // add a string value to the cache if not already there. if (!cache.session.contains('output')) { cache.session.put('output', 'cached text value'); } } // return counter from the cache. public integer getcounter() { return (integer)cache.session.get('counter'); } // return datetime value from the cache. public string getcacheddatetime() { datetime dt = (datetime)cache.session.get('datetime'); return dt != null ? dt.format() : null; } // return cached value whose type is the inner class mydata. public string getcacheddata() { mydata mydata = (mydata)cache.session.get('data'); return mydata != null ? mydata.tostring() : null; } // method invoked by the rerender button on the visualforce page. // updates the values of various cached values. // increases the values of counter and the mydata counter if those // cache values are still in the cache. 216apex reference guide session class public pagereference go() { // increase the cached counter value or set it to 0 // if it's not cached. if (cache.session.contains('counter')) { cache.session.put('counter', getcounter() + 1); } else { cache.session.put('counter', 0); } // get the custom data value from the cache. mydata d = (mydata)cache.session.get('data'); // only if the data is already in the cache, update it. if (cache.session.contains('data')) { d.inc(); cache.session.put('data', d); } return null; } // method invoked by the remove button on the visualforce page. // removes the datetime cached value from the session cache. public pagereference remove() { cache.session.remove('datetime'); return null; } } this is the visualforce page that corresponds to the sessioncachecontroller class. <apex:page controller="sessioncachecontroller" action="{!init}"> <apex:outputpanel id |
="output"> <br/>cached datetime: <apex:outputtext value="{!cacheddatetime}"/> <br/>cached data: <apex:outputtext value="{!cacheddata}"/> <br/>cached counter: <apex:outputtext value="{!counter}"/> <br/>output: <apex:outputtext value="{!$cache.session.local.mypartition.output}"/> <br/>repeat: <apex:repeat var="item" value="{!$cache.session.local.mypartition.list}"> <apex:outputtext value="{!item}"/> </apex:repeat> <br/>list size: <apex:outputtext value="{!$cache.session.local.mypartition.list.size}"/> </apex:outputpanel> <br/><br/> <apex:form > <apex:commandbutton id="go" action="{!go}" value="rerender" rerender="output"/> <apex:commandbutton id="remove" action="{!remove}" value="remove datetime key" rerender="output"/> </apex:form> </apex:page> 217apex reference guide session class this is the output of the page after clicking the rerender button twice. the counter value could differ in your case if a key named counter was already in the cache before running this sample. cached datetime:8/11/2015 1:58 pm cached data:some custom value:2 cached counter:2 output:cached text value repeat:one two three four five list size:5 in this section: session constants the session class provides a constant that you can use when setting the time-to-live (ttl) value. session methods see also: apex developer guide: platform cache session constants the session class provides a constant that you can use when setting the time-to-live (ttl) value. constant description max_ttl_secs represents the maximum amount of time, in seconds, to keep the cached value in the session cache. session methods the following are methods for session. all methods are static. in this section: contains(key) returns true if the session cache contains a cached value corresponding to the specified key. contains(setofkeys) returns true if the cache contains values for a specified set of keys. get(key) returns the cached value corresponding to the specified key from the session cache. get(keys) returns the cached values corresponding to the specified set of keys from the session cache. get(cachebuilder, key) returns the cached value corresponding to the specified key from the session cache. use this method if your cached value is a class that implements the cachebuilder interface. 218apex reference guide session class getavggetsize() returns the average item size of all the keys fetched from the session cache, in bytes. getavggettime() returns the average time taken to get a key from the session cache, in nanoseconds. getavgvaluesize() deprecated and available only in api versions 49.0 and earlier. returns the average item size for keys in the session cache, in bytes. getcapacity() returns the percentage of session cache capacity that has been used. getkeys() returns all keys that are stored in the session cache and visible to the invoking namespace. getmaxgetsize() returns the maximum item size of all the keys fetched from the session cache, in bytes. getmaxgettime() returns the maximum time taken to get a key from the session cache, in nanoseconds. getmaxvaluesize() deprecated and available only in api versions 49.0 and earlier. returns the maximum item size for keys in the session cache, in bytes. getmissrate() returns the miss rate in the session cache. getname() returns the name of the default cache partition. getnumkeys() returns the total number of keys in the session cache. getpartition(partitionname) returns a partition from the session cache that corresponds to the specified partition name. isavailable() returns true if the session cache is available for use. the session cache isn’t available when an active session isn’t present, such as in asynchronous apex or code called by asynchronous apex. for example, if batch apex causes an apex trigger to execute, the session cache isn’t available in the trigger |
because the trigger runs in asynchronous context. put(key, value) stores the specified key/value pair as a cached entry in the session cache. the put method can write only to the cache in your org’s namespace. put(key, value, visibility) stores the specified key/value pair as a cached entry in the session cache and sets the cached value’s visibility. put(key, value, ttlsecs) stores the specified key/value pair as a cached entry in the session cache and sets the cached value’s lifetime. put(key, value, ttlsecs, visibility, immutable) stores the specified key/value pair as a cached entry in the session cache. this method also sets the cached value’s lifetime, visibility, and whether it can be overwritten by another namespace. 219apex reference guide session class remove(key) deletes the cached value corresponding to the specified key from the session cache. remove(cachebuilder, key) deletes the cached value corresponding to the specified key from the session cache. use this method if your cached value is a class that implements the cachebuilder interface. contains(key) returns true if the session cache contains a cached value corresponding to the specified key. signature public static boolean contains(string key) parameters key type: string a case-sensitive string value that uniquely identifies a cached value. for information about the format of the key name, see usage. return value type: boolean true if a cache entry is found. othewise, false. contains(setofkeys) returns true if the cache contains values for a specified set of keys. signature public static map <string, boolean> contains (set<string> keys) parameters setofkeys type: set <string> a set of keys that uniquely identifies cached values. for information about the format of the key name, see usage. return value type: map <string, boolean> returns the cache key and corresponding boolean value indicating that the key entry exists. the boolean value is false if the key entry doesn't exist. usage the number of input keys cannot exceed the maximum limit of 10. 220apex reference guide session class example in this example, the code checks for the presence of multiple keys on the default partition. it fetches the cache key and the corresponding boolean value for the key entry from the session cache of the default partition. set<string> keys = new set<string>{'key1','key2','key3','key4','key5'}; map<string,boolean> result = cache.session.contains(keys); for(string key : result.keyset()) { system.debug('key: ' + key); system.debug('is key present in the cache : ' + result.get(key)); } in this example, the code checks for the presence of multiple keys on different partitions. it fetches the cache key and the corresponding boolean value for the key entry from the session cache of different partitions. // assuming there are three partitions p1, p2, p3 with default 'local' namespace set<string> keys = new set<string>{'local.p1.key','local.p2.key', 'local.p3.key'}; map<string,boolean> result = cache.session.contains(keys); for(string key : result.keyset()) { system.debug('key: ' + key); system.debug('is key present in the cache : + result.get(key)); } get(key) returns the cached value corresponding to the specified key from the session cache. signature public static object get(string key) parameters key type: string a case-sensitive string value that uniquely identifies a cached value. for information about the format of the key name, see usage. return value type: object the cached value as a generic object type. cast the returned value to the appropriate type. usage because cache.session.get() returns an object, we recommend that you cast the returned value to a specific type to facilitate use of the returned value. // get a cached value object obj = cache.session.get('ns1.partition1.orderdate'); // cast return value to a specific data type datetime dt2 = (datetime)obj; 221apex reference guide session class if a cache.session.get() call doesn’t find the referenced key, it returns null. get(keys) returns the cached values corresponding to the specified set |
of keys from the session cache. signature public static map <string, object> get (set <string> keys) parameters keys type: set <string> a set of keys that uniquely identify cached values. for information about the format of the key name, see usage. return value type: map <string, object> returns the cache key and corresponding value. returns null when no corresponding value is found for an input key. usage the number of input keys cannot exceed the maximum limit of 10. example fetch multiple keys from the session cache of the default partition. set<string> keys = new set<string>{'key1','key2','key3','key4','key5'}; map<string,object> result = cache.session.get(keys); for(string key : result.keyset()) { system.debug('key: ' + key); system.debug('value: ' + result.get(key)); } fetch multiple keys from the session cache of different partitions. // assuming there are three partitions p1, p2, p3 with default 'local' namespace set<string> keys = new set<string>{'local.p1.key','local.p2.key', 'local.p3.key'}; map<string,object> result = cache.session.get(keys); for(string key : result.keyset()) { system.debug('key: ' + key); system.debug('value: ' + result.get(key)); } get(cachebuilder, key) returns the cached value corresponding to the specified key from the session cache. use this method if your cached value is a class that implements the cachebuilder interface. 222apex reference guide session class signature public static object get(system.type cachebuilder, string key) parameters cachebuilder type: system.type the apex class that implements the cachebuilder interface. key type: string a case-sensitive string value that, combined with the class name corresponding to the cachebuilder parameter, uniquely identifies a cached value. return value type: object the cached value as a generic object type. cast the returned value to the appropriate type. usage because cache.session.get(cachebuilder, key) returns an object, cast the returned value to a specific type to facilitate use of the returned value. return ((datetime)cache.session.get(datecache.class, 'datetime')).format(); getavggetsize() returns the average item size of all the keys fetched from the session cache, in bytes. signature public static long getavggetsize() return value type: long getavggettime() returns the average time taken to get a key from the session cache, in nanoseconds. signature public static long getavggettime() return value type: long 223apex reference guide session class getavgvaluesize() deprecated and available only in api versions 49.0 and earlier. returns the average item size for keys in the session cache, in bytes. signature public static long getavgvaluesize() return value type: long getcapacity() returns the percentage of session cache capacity that has been used. signature public static double getcapacity() return value type: double used cache as a percentage number. getkeys() returns all keys that are stored in the session cache and visible to the invoking namespace. signature public static set<string> getkeys() return value type: set<string> a set containing all cache keys. getmaxgetsize() returns the maximum item size of all the keys fetched from the session cache, in bytes. signature public static long getmaxgetsize() return value type: long 224apex reference guide session class getmaxgettime() returns the maximum time taken to get a key from the session cache, in nanoseconds. signature public static long getmaxgettime() return value type: long getmaxvaluesize() deprecated and available only in api versions 49.0 and earlier. returns the maximum item size for keys in the session cache, in bytes. signature public static long getmaxvaluesize() return value type: long getmissrate() returns the miss rate in the session cache. signature public static double getmissrate() return value type: double getname() returns the name of the default cache partition. signature public string getname() return value type: string |
the name of the default cache partition. 225apex reference guide session class getnumkeys() returns the total number of keys in the session cache. signature public static long getnumkeys() return value type: long getpartition(partitionname) returns a partition from the session cache that corresponds to the specified partition name. signature public static cache.sessionpartition getpartition(string partitionname) parameters partitionname type: string a partition name that is qualified by the namespace, for example, namespace.partition. return value type: cache.sessionpartition example after you get the session partition, you can add and retrieve the partition’s cache values. // get partition cache.sessionpartition sessionpart = cache.session.getpartition('myns.mypartition'); // retrieve cache value from the partition if (sessionpart.contains('booktitle')) { string cachedtitle = (string)sessionpart.get('booktitle'); } // add cache value to the partition sessionpart.put('orderdate', date.today()); // or use dot notation to call partition methods string cachedauthor = (string)cache.session.getpartition('myns.mypartition').get('bookauthor'); 226apex reference guide session class isavailable() returns true if the session cache is available for use. the session cache isn’t available when an active session isn’t present, such as in asynchronous apex or code called by asynchronous apex. for example, if batch apex causes an apex trigger to execute, the session cache isn’t available in the trigger because the trigger runs in asynchronous context. signature public static boolean isavailable() return value type: boolean true if the session cache is available. otherwise, false. put(key, value) stores the specified key/value pair as a cached entry in the session cache. the put method can write only to the cache in your org’s namespace. signature public static void put(string key, object value) parameters key type: string a string that uniquely identifies the value to be cached. for information about the format of the key name, see usage. value type: object the value to store in the cache. the cached value must be serializable. return value type: void put(key, value, visibility) stores the specified key/value pair as a cached entry in the session cache and sets the cached value’s visibility. signature public static void put(string key, object value, cache.visibility visibility) parameters key type: string 227apex reference guide session class a string that uniquely identifies the value to be cached. for information about the format of the key name, see usage. value type: object the value to store in the cache. the cached value must be serializable. visibility type: cache.visibility indicates whether the cached value is available only to apex code that is executing in the same namespace or to apex code executing from any namespace. return value type: void put(key, value, ttlsecs) stores the specified key/value pair as a cached entry in the session cache and sets the cached value’s lifetime. signature public static void put(string key, object value, integer ttlsecs) parameters key type: string a string that uniquely identifies the value to be cached. for information about the format of the key name, see usage. value type: object the value to store in the cache. the cached value must be serializable. ttlsecs type: integer the amount of time, in seconds, to keep the cached value in the session cache. the cached values remain in the cache as long as the salesforce session hasn’t expired. the maximum value is 28,800 seconds or eight hours. the minimum value is 300 seconds or five minutes. return value type: void put(key, value, ttlsecs, visibility, immutable) stores the specified key/value pair as a cached entry in the session cache. this method also sets the cached value’s lifetime, visibility, and whether it can be overwritten by another namespace. 228apex reference guide session class signature public static void put(string key, object value, integer ttlsecs, cache.visibility visibility, boolean immutable) parameters key type: string a string that uniquely identifies the value to be cached. for information about the format of the key name, see usage |
. value type: object the value to store in the cache. the cached value must be serializable. ttlsecs type: integer the amount of time, in seconds, to keep the cached value in the session cache. the cached values remain in the cache as long as the salesforce session hasn’t expired. the maximum value is 28,800 seconds or eight hours. the minimum value is 300 seconds or five minutes. visibility type: cache.visibility indicates whether the cached value is available only to apex code that is executing in the same namespace or to apex code executing from any namespace. immutable type: boolean indicates whether the cached value can be overwritten by another namespace (false) or not (true). return value type: void remove(key) deletes the cached value corresponding to the specified key from the session cache. signature public static boolean remove(string key) parameters key type: string a case-sensitive string value that uniquely identifies a cached value. for information about the format of the key name, see usage. return value type: boolean 229apex reference guide sessionpartition class true if the cache value was successfully removed. otherwise, false. remove(cachebuilder, key) deletes the cached value corresponding to the specified key from the session cache. use this method if your cached value is a class that implements the cachebuilder interface. signature public static boolean remove(system.type cachebuilder, string key) parameters cachebuilder type: system.type the apex class that implements the cachebuilder interface. key type: string a case-sensitive string value that, combined with the class name corresponding to the cachebuilder parameter, uniquely identifies a cached value. return value type: boolean true if the cache value was successfully removed. otherwise, false. sessionpartition class contains methods to manage cache values in the session cache of a specific partition. namespace cache usage this class extends cache.partition and inherits all of its non-static methods. utility methods for creating and validating keys are not supported and can be called only from the cache.partition parent class. for a list of cache.partition methods, see partition methods. to get a session partition, call cache.session.getpartition and pass in a fully qualified partition name, as follows. cache.sessionpartition sessionpartition = cache.session.getpartition('namespace.mypartition'); see cache key format for partition methods. 230apex reference guide sessionpartition class example this class is the controller for a sample visualforce page (shown in the subsequent code sample). the controller shows how to use the methods of cache.sessionpartition to manage a cache value on a particular partition. the controller takes inputs from the visualforce page for the partition name, key name for a counter, and initial counter value. the controller contains default values for these inputs. when you click rerender on the visualforce page, the go() method is invoked and increases the counter by one. when you click remove key, the counter key is removed from the cache. the counter value gets reset to its initial value when it’s re-added to the cache. public class sessionpartitioncontroller { // name of a partition in the local namespace string partitioninput = 'local.mypartition'; // name of the key string counterkeyinput = 'counter'; // key initial value integer counterinitvalue = 0; // session partition object cache.sessionpartition sessionpartition; // constructor of the controller for the visualforce page. public sessionpartitioncontroller() { } // adds counter value to the cache. // this method is called when the visualforce page loads. public void init() { // create the partition instance based on the partition name sessionpartition = getpartition(); // add counter to the cache with an initial value // or increment it if it's already there. if (!sessionpartition.contains(counterkeyinput)) { sessionpartition.put(counterkeyinput, counterinitvalue); } else { sessionpartition.put(counterkeyinput, getcounter() + 1); } } // returns the session partition based on the partition name // given in the visualforce page or the default value. private cache.sessionpartition getpartition() { if (sessionpartition == null) { sessionpartition = cache.session.getpartition(partitioninput); } return sessionpartition; } // return counter from the cache. |
public integer getcounter() { return (integer)getpartition().get(counterkeyinput); } 231apex reference guide sessionpartition class // invoked by the submit button to save input values // supplied by the user. public pagereference save() { // reset the initial key value in the cache getpartition().put(counterkeyinput, counterinitvalue); return null; } // method invoked by the rerender button on the visualforce page. // updates the values of various cached values. // increases the values of counter and the mydata counter if those // cache values are still in the cache. public pagereference go() { // get the partition object sessionpartition = getpartition(); // increase the cached counter value or set it to 0 // if it's not cached. if (sessionpartition.contains(counterkeyinput)) { sessionpartition.put(counterkeyinput, getcounter() + 1); } else { sessionpartition.put(counterkeyinput, counterinitvalue); } return null; } // method invoked by the remove button on the visualforce page. // removes the datetime cached value from the session cache. public pagereference remove() { getpartition().remove(counterkeyinput); return null; } // get and set methods for accessing variables // that correspond to the input text fields on // the visualforce page. public string getpartitioninput() { return partitioninput; } public string getcounterkeyinput() { return counterkeyinput; } public integer getcounterinitvalue() { return counterinitvalue; } public void setpartitioninput(string partition) { this.partitioninput = partition; } 232 |
apex reference guide cache exceptions public void setcounterkeyinput(string keyname) { this.counterkeyinput = keyname; } public void setcounterinitvalue(integer countervalue) { this.counterinitvalue = countervalue; } } this is the visualforce page that corresponds to the sessionpartitioncontroller class. <apex:page controller="sessionpartitioncontroller" action="{!init}"> <apex:form > <br/>partition with namespace prefix: <apex:inputtext value="{!partitioninput}"/> <br/>counter key name: <apex:inputtext value="{!counterkeyinput}"/> <br/>counter initial value: <apex:inputtext value="{!counterinitvalue}"/> <apex:commandbutton action="{!save}" value="save key input values"/> </apex:form> <apex:outputpanel id="output"> <br/>cached counter: <apex:outputtext value="{!counter}"/> </apex:outputpanel> <br/> <apex:form > <apex:commandbutton id="go" action="{!go}" value="rerender" rerender="output"/> <apex:commandbutton id="remove" action="{!remove}" value="remove key" rerender="output"/> </apex:form> </apex:page> see also: apex developer guide: platform cache cache exceptions the cache namespace contains exception classes. all exception classes support built-in methods for returning the error message and exception type. see exception class and built-in exceptions on page 3021 in the apex developer guide. the cache namespace contains these exceptions. exception thrown when cache.session.sessioncacheexception an error occurred while adding or retrieving a value in the session cache. cache.session.sessioncachenosessionexception an attempt is made to access the cache when the session cache isn’t available. 233apex reference guide visibility enum exception thrown when cache.org.orgcacheexception an attempt is made to access a partition that doesn’t exist or whose name is invalid. cache.invalidparamexception an invalid parameter value is passed into a method of cache.session or cache.org. this error occurs when: • the key referenced is null or empty or is not alphanumeric. • the key isn’t qualified with the namespace and partition in the format <namespace>.<partition>.<key>. • the key isn’t qualified in the format <key> for the default partition, or for a key inserted through the partition object. • the namespace referenced is null or empty. • the partition name is null or empty or is not alphanumeric. • another referenced value is null. cache.itemsizelimitexceededexception a cache put call is made with an item that exceeds the maximum size limit. to fix this error, break the item into multiple, smaller items. cache.bulkapikeyslimitexceededexception the number of key parameters passed into a bulk method - get(keys) or contains(setofkeys) exceeds the maximum limit of 10. cache.platformcacheinvalidoperationexception a cache put or remove call is made that is not allowed. for example, when calling put or remove inside a visualforce constructor. cache.cachebuilderexecutionexception this error occurs when the execution of the cachebuilder fails; this could be due to an error in parsing, a permissions error while accessing records, or an issue with apex callouts. cache.invalidcachebuilderexception a get(cachebuilder cb, string key), remove(cachebuilder cb, string key), or validatecachebuilder(cachebuilder cb) method is called but the cb parameter is a class that does not implement the cache.cachebuilder interface. visibility enum use the cache.visibility enumeration in the cache.session or cache.org methods to indicate whether a cached value is visible only in the value’s namespace or in all namespaces. enum values the following are the values of the cache.visibility enum. 234apex reference guide canvas namespace value description all the cached value is available to apex code executing from any namespace. this is the default state. namespace the cached value is available to apex code executing from the same namespace. if a key has the visibility.namespace attribute, a get method initiated from a different namespace returns null. |
canvas namespace the canvas namespace provides an interface and classes for canvas apps in salesforce. the following are the interfaces and classes in the canvas namespace. in this section: applicationcontext interface use this interface to retrieve application context information, such as the application version or url. canvaslifecyclehandler interface implement this interface to control context information and add custom behavior during the application render phase. contexttypeenum enum describes context data that can be excluded from canvas app context data. you specify which context types to exclude in the excludecontexttypes() method in your canvaslifecyclehandler implementation. environmentcontext interface use this interface to retrieve environment context information, such as the app display location or the configuration parameters. rendercontext interface a wrapper interface that is used to retrieve application and environment context information. test class contains methods for automated testing of your canvas classes. canvas exceptions the canvas namespace contains exception classes. applicationcontext interface use this interface to retrieve application context information, such as the application version or url. namespace canvas 235apex reference guide applicationcontext interface usage the applicationcontext interface provides methods to retrieve application information about the canvas app that’s being rendered. most of the methods are read-only. for this interface, you don’t need to create an implementation. use the default implementation that salesforce provides. in this section: applicationcontext methods applicationcontext methods the following are methods for applicationcontext. in this section: getcanvasurl() retrieves the fully qualified url of the canvas app. getdevelopername() retrieves the internal api name of the canvas app. getname() retrieves the name of the canvas app. getnamespace() retrieves the namespace prefix of the canvas app. getversion() retrieves the current version of the canvas app. setcanvasurlpath(newpath) overrides the url of the canvas app for the current request. getcanvasurl() retrieves the fully qualified url of the canvas app. signature public string getcanvasurl() return value type: string usage use this method to get the url of the canvas app, for example: http://instance.salesforce.com:8080/canvas_app_path/canvas_app.jsp. 236apex reference guide applicationcontext interface getdevelopername() retrieves the internal api name of the canvas app. signature public string getdevelopername() return value type: string usage use this method to get the api name of the canvas app. you specify this value in the api name field when you expose the canvas app by creating a connected app. getname() retrieves the name of the canvas app. signature public string getname() return value type: string usage use this method to get the name of the canvas app. getnamespace() retrieves the namespace prefix of the canvas app. signature public string getnamespace() return value type: string usage use this method to get the salesforce namespace prefix that’s associated with the canvas app. 237apex reference guide canvaslifecyclehandler interface getversion() retrieves the current version of the canvas app. signature public string getversion() return value type: string usage use this method to get the current version of the canvas app. this value changes after you update and republish a canvas app in an organization. if you are in a developer edition organization, using this method always returns the latest version. setcanvasurlpath(newpath) overrides the url of the canvas app for the current request. signature public void setcanvasurlpath(string newpath) parameters newpath type: string the url (not including domain) that you need to use to override the canvas app url. return value type: void usage use this method to override the url path and query string of the canvas app. do not provide a fully qualified url, because the provided url string will be appended to the original canvas url domain. for example, if the current canvas app url is https://myserver.com:6000/myapppath and you call setcanvasurlpath('/alternatepath/args?arg1=1&arg2=2'), the adjusted canvas app url will be https://myserver.com:6000/alternatepath/args?arg1=1&arg2=2. if the provided path results in a |
malformed url, or a url that exceeds 2,048 characters, a system.canvasexception will be thrown. this method overrides the canvas app url for the current request and does not permanently change the canvas app url as configured in the ui for the salesforce canvas app settings. canvaslifecyclehandler interface implement this interface to control context information and add custom behavior during the application render phase. 238apex reference guide canvaslifecyclehandler interface namespace canvas usage use this interface to specify what canvas context information is provided to your app by implementing the excludecontexttypes() method. use this interface to call custom code when the app is rendered by implementing the onrender() method. if you provide an implementation of this interface, you must implement excludecontexttypes() and onrender(). example implementation the following example shows a simple implementation of canvaslifecyclehandler that specifies that organization context information will be excluded and prints a debug message when the app is rendered. public class mycanvaslistener implements canvas.canvaslifecyclehandler{ public set<canvas.contexttypeenum> excludecontexttypes(){ set<canvas.contexttypeenum> excluded = new set<canvas.contexttypeenum>(); excluded.add(canvas.contexttypeenum.organization); return excluded; } public void onrender(canvas.rendercontext rendercontext){ system.debug('canvas lifecycle called.'); } } in this section: canvaslifecyclehandler methods canvaslifecyclehandler methods the following are methods for canvaslifecyclehandler. in this section: excludecontexttypes() lets the implementation exclude parts of the canvasrequest context, if the application does not need it. onrender(rendercontext) invoked when a canvas app is rendered. provides the ability to set and retrieve canvas application and environment context information during the application render phase. excludecontexttypes() lets the implementation exclude parts of the canvasrequest context, if the application does not need it. 239apex reference guide canvaslifecyclehandler interface signature public set<canvas.contexttypeenum> excludecontexttypes() return value type: set<canvas.contexttypeenum> this method must return null or a set of zero or more contexttypeenum values. returning null enables all attributes by default. contexttypeenum values that can be set are: • canvas.contexttypeenum.organization • canvas.contexttypeenum.record_detail • canvas.contexttypeenum.user see contexttypeenum on page 241 for more details on these values. usage implement this method to specify which attributes to disable in the context of the canvas app. a disabled attribute will set the associated canvas context information to null. disabling attributes can help improve performance by reducing the size of the signed request and canvas context. also, disabled attributes do not need to be retrieved by salesforce, which further improves performance. see the canvas developer guide for more information on context information in the context object that’s provided in the canvasrequest. example this example implementation specifies that the organization information will be disabled in the canvas context. public set<canvas.contexttypeenum> excludecontexttypes() { set<canvas.contexttypeenum> excluded = new set<canvas.contexttypeenum>(); excluded.add(canvas.contexttypeenum.organization); return excluded; } onrender(rendercontext) invoked when a canvas app is rendered. provides the ability to set and retrieve canvas application and environment context information during the application render phase. signature public void onrender(canvas.rendercontext rendercontext) parameters rendercontext type: canvas.rendercontext return value type: void 240apex reference guide contexttypeenum enum usage if implemented, this method is called whenever the canvas app is rendered. the implementation can set and retrieve context information by using the provided canvas.rendercontext. this method is called whenever signed request or context information is retrieved by the client. see the canvas developer guide for more information on signed request authentication. example this example implementation prints ‘canvas lifecycle called.’ to the debug log when the canvas app is rendered. public void onrender(canvas.rendercontext rendercontext) { system.debug('canvas lifecycle called.'); } contexttypeenum enum describes context data that can be excluded from |
canvas app context data. you specify which context types to exclude in the excludecontexttypes() method in your canvaslifecyclehandler implementation. namespace canvas enum values value description organization exclude context information about the organization in which the canvas app is running. record_detail exclude context information about the object record on which the canvas app appears. user exclude context information about the current user. environmentcontext interface use this interface to retrieve environment context information, such as the app display location or the configuration parameters. namespace canvas usage the environmentcontext interface provides methods to retrieve environment information about the current canvas app. for this interface, you don’t need to create an implementation. use the default implementation that salesforce provides. 241apex reference guide environmentcontext interface in this section: environmentcontext methods environmentcontext methods the following are methods for environmentcontext. in this section: addentityfield(fieldname) adds a field to the list of object fields that are returned in the signed request record object when the component appears on a visualforce page that’s placed on an object. addentityfields(fieldnames) adds a set of fields to the list of object fields that are returned in the signed request record object when the component appears on a visualforce page that’s placed on an object. getdisplaylocation() retrieves the display location where the canvas app is being called from. for example, a value of visualforce page. getentityfields() retrieves the list of object fields that are returned in the signed request record object when the component appears on a visualforce page that’s placed on an object. getlocationurl() retrieves the location url of the canvas app. getparametersasjson() retrieves the current custom parameters for the canvas app. parameters are returned as a json string. getsublocation() retrieves the display sublocation where the canvas app is being called from. setparametersasjson(jsonstring) sets the custom parameters for the canvas app. addentityfield(fieldname) adds a field to the list of object fields that are returned in the signed request record object when the component appears on a visualforce page that’s placed on an object. signature public void addentityfield(string fieldname) parameters fieldname type: string the object field name that you need to add to the list of returned fields., using ‘*’ adds all fields that the user has permission to view. 242apex reference guide environmentcontext interface return value type: void usage when you use the <apex:canvasapp> component to display a canvas app on a visualforce page, and that page is associated with an object (placed on the page layout, for example), you can specify fields to be returned from the related object. see the canvas developer guide for more information on the record object. use addentityfield() to add a field to the list of object fields that are returned in the signed request record object. by default the list of fields includes id. you can add fields by name or add all fields that the user has permission to view by calling addentityfield('*'). you can inspect the configured list of fields by using canvas.environmentcontext.getentityfields(). example this example adds the name and billingaddress fields to the list of object fields. this example assumes the canvas app will appear in a visualforce page that's associated with the account page layout. canvas.environmentcontext env = rendercontext.getenvironmentcontext(); // add name and billingaddress to fields (assumes we'll run from the account detail page) env.addentityfield('name'); env.addentityfield('billingaddress'); addentityfields(fieldnames) adds a set of fields to the list of object fields that are returned in the signed request record object when the component appears on a visualforce page that’s placed on an object. signature public void addentityfields(set<string> fieldnames) parameters fieldnames type: set<string> the set of object field names that you need to add to the list of returned fields. if an item in the set is ‘*’, all fields that the user has permission to view are added. return value type: void usage when you use the <apex:canvasapp> component to display a canvas app on a visualforce page, and that page is associated with an object (placed on the page layout, for example), you can specify fields |
to be returned from the related object. see the canvas developer guide for more information on the record object. 243apex reference guide environmentcontext interface use addentityfields() to add a set of one or more fields to the list of object fields that are returned in the signed request record object. by default the list of fields includes id. you can add fields by name or add all fields that the user has permission to view by adding a set that includes ‘*’ as one of the strings. you can inspect the configured list of fields by using canvas.environmentcontext.getentityfields(). example this example adds the name, billingaddress, and yearstarted fields to the list of object fields. this example assumes that the canvas app will appear in a visualforce page that’s associated with the account page layout. canvas.environmentcontext env = rendercontext.getenvironmentcontext(); // add name, billingaddress and yearstarted to fields (assumes we'll run from the account detail page) set<string> fields = new set<string>{'name','billingaddress','yearstarted'}; env.addentityfields(fields); getdisplaylocation() retrieves the display location where the canvas app is being called from. for example, a value of visualforce page. signature public string getdisplaylocation() return value type: string the return value can be one of the following strings: • chatter—the canvas app was called from the chatter tab. • chatterfeed—the canvas app was called from a chatter canvas feed item. • mobilenav—the canvas app was called from the navigation menu. • opencti—the canvas app was called from an open cti component. • pagelayout—the canvas app was called from an element within a page layout. if the displaylocation is pagelayout, one of the sublocation values might be returned. • publisher—the canvas app was called from a canvas custom quick action. • servicedesk—the canvas app was called from a salesforce console component. • visualforce—the canvas app was called from a visualforce page. • none—the canvas app was called from the canvas app previewer. usage use this method to obtain the display location for the canvas app. getentityfields() retrieves the list of object fields that are returned in the signed request record object when the component appears on a visualforce page that’s placed on an object. 244apex reference guide environmentcontext interface signature public list<string> getentityfields() return value type: list<string> usage when you use the <apex:canvasapp> component to display a canvas app on a visualforce page, and that page is associated with an object (placed on the page layout, for example), you can specify fields to be returned from the related object. see the canvas developer guide for more information on the record object. use getentityfields() to retrieve the list of object fields that are returned in the signed request record object. by default the list of fields includes id. the list of fields can be configured by using the canvas.environmentcontext.addentityfield(fieldname) or canvas.environmentcontext.addentityfields(fieldnames) methods. example this example gets the current list of object fields and retrieves each item in the list, printing each field name to the debug log. canvas.environmentcontext env = rendercontext.getenvironmentcontext(); list<string> entityfields = env.getentityfields(); for (string fieldval : entityfields) { system.debug('environment context entityfield: ' + fieldval); } if the canvas app that’s using this lifecycle code was run from the detail page of an account, the debug log output might look like: environment context entityfield: id getlocationurl() retrieves the location url of the canvas app. signature public string getlocationurl() return value type: string usage use this method to obtain the url of the page where the user accessed the canvas app. for example, if the user accessed your app by clicking a link on the chatter tab, this method returns the url of the chatter tab, which would be similar to ‘https://mydomainname.my.salesforce.com/_ui/core/chatter/ui/chatterpage’. 245apex reference guide environmentcontext interface getparametersasjson() retrieves the current custom parameters for the canvas app. parameters are returned as a json string. signature public |
string getparametersasjson() return value type: string usage use this method to get the current custom parameters for the canvas app. the parameters are returned in a json string that can be de-serialized by using the system.json.deserializeuntyped(jsonstring) method. custom parameters can be modified by using the canvas.environmentcontext.setparametersasjson(jsonstring) string. example this example gets the current custom parameters, de-serializes them into a map, and prints the results to the debug log. canvas.environmentcontext env = rendercontext.getenvironmentcontext(); // get current custom params map<string, object> currentparams = (map<string, object>) json.deserializeuntyped(env.getparametersasjson()); system.debug('environment context custom paramters: ' + currentparams); getsublocation() retrieves the display sublocation where the canvas app is being called from. signature public string getsublocation() return value type: string the return value can be one of the following strings: • s1mobilecardfullview—the canvas app was called from a mobile card. • s1mobilecardpreview—the canvas app was called from a mobile card preview. the user must click the preview to open the app. • s1recordhomepreview—the canvas app was called from a record detail page preview. the user must click the preview to open the app. • s1recordhomefullview—the canvas app was called from a page layout. 246apex reference guide environmentcontext interface usage use this method to obtain the display sublocation for the canvas app. use only if the primary display location can be displayed on mobile devices. setparametersasjson(jsonstring) sets the custom parameters for the canvas app. signature public void setparametersasjson(string jsonstring) parameters jsonstring type: string the custom parameters that you need to set, serialized into a json format string. return value type: void usage use this method to set the current custom parameters for the canvas app. the parameters must be provided in a json string. you can use the system.json.serialize(objecttoserialize) method to serialize a map into a json string. setting the custom parameters will overwrite the custom parameters that are set for the current request. if you need to modify the current custom parameters, first get the current set of custom parameters by using getparametersasjson(), modify the retrieved parameter set as needed, and then use this modified set in your call to setparametersasjson(). if the provided json string exceeds 32kb, a system.canvasexception will be thrown. example this example gets the current custom parameters, adds a new newcustomparam parameter with a value of ‘testvalue’, and sets the current custom parameters. canvas.environmentcontext env = rendercontext.getenvironmentcontext(); // get current custom params map<string, object> previousparams = (map<string, object>) json.deserializeuntyped(env.getparametersasjson()); // add a new custom param previousparams.put('newcustomparam','testvalue'); // now replace the parameters with the current parameters plus our new custom param env.setparametersasjson(json.serialize(previousparams)); 247apex reference guide rendercontext interface rendercontext interface a wrapper interface that is used to retrieve application and environment context information. namespace canvas usage use this interface to retrieve application and environment context information for your canvas app. for this interface, you don’t need to create an implementation. use the default implementation that salesforce provides. in this section: rendercontext methods rendercontext methods the following are methods for rendercontext. in this section: getapplicationcontext() retrieves the application context information. getenvironmentcontext() retrieves the environment context information. getapplicationcontext() retrieves the application context information. signature public canvas.applicationcontext getapplicationcontext() return value type: canvas.applicationcontext usage use this method to get the application context information for your canvas app. 248apex reference guide rendercontext interface example the following example implementation of the canvaslifecyclehandler onrender() method uses the provided rendercontext to retrieve the application context information and then checks the namespace, version, and app url. public void onrender(canvas.rendercontext rendercontext){ canvas.applicationcontext app = rendercontext.getapplicationcontext(); if (!'mynamespace |
'.equals(app.getnamespace())){ // this application is installed, add code as needed ... } // check the application version double currentversion = double.valueof(app.getversion()); if (currentversion <= 5){ // add version specific code as needed ... // tell the canvas application to operate in deprecated mode app.setcanvasurlpath('/canvas?deprecated=true'); } } getenvironmentcontext() retrieves the environment context information. signature public canvas.environmentcontext getenvironmentcontext() return value type: canvas.environmentcontext usage use this method to get the environment context information for your canvas app. example the following example implementation of the canvaslifecyclehandler onrender() method uses the provided rendercontext to retrieve the environment context information and then modifies the custom parameters. public void onrender(canvas.rendercontext rendercontext) { canvas.environmentcontext env = rendercontext.getenvironmentcontext(); // retrieve the custom params map<string, object> previousparams = (map<string, object>) json.deserializeuntyped(env.getparametersasjson()); previousparams.put('param1',1); previousparams.put('param2',3.14159); 249apex reference guide test class ... // now, add in some opportunity record ids opportunity[] o = [select id, name from opportunity]; previousparams.put('opportunities',o); // now, replace the parameters env.setparametersasjson(json.serialize(previousparams)); } test class contains methods for automated testing of your canvas classes. namespace canvas usage use this class to test your implementation of canvas.canvaslifecyclehandler with mock test data. you can create a test canvas.rendercontext with mock application and environment context data and use this data to verify that your canvaslifecyclehandler is being invoked correctly. in this section: test constants the test class provides constants that are used as keys when you set mock application and environment context data. test methods the test class provides methods for creating test contexts and invoking your canvaslifecyclehandler with mock data. test constants the test class provides constants that are used as keys when you set mock application and environment context data. when you call canvas.test.mockrendercontext(applicationcontexttestvalues, environmentcontexttestvalues), you need to provide maps of key-value pairs to represent your mock application and environment context data. the test class provides static constant strings that you can use as keys for various parts of the application and environment context. constant description key_canvas_url represents the canvas app url key in the applicationcontext. key_developer_name represents the canvas app developer or api name key in the applicationcontext. key_display_location represents the canvas app display location key in the environmentcontext. key_location_url represents the canvas app location url key in the environmentcontext. 250apex reference guide test class constant description key_name represents the canvas app name key in the applicationcontext. key_namespace represents the canvas app namespace key in the applicationcontext. key_sub_location represents the canvas app sublocation key in the environmentcontext. key_version represents the canvas app version key in the applicationcontext. test methods the test class provides methods for creating test contexts and invoking your canvaslifecyclehandler with mock data. the following are methods for test. all are static methods. in this section: mockrendercontext(applicationcontexttestvalues, environmentcontexttestvalues) creates and returns a test canvas.rendercontext based on the provided application and environment context parameters. testcanvaslifecycle(lifecyclehandler, mockrendercontext) calls the canvas test framework to invoke a canvaslifecyclehandler with the provided rendercontext. mockrendercontext(applicationcontexttestvalues, environmentcontexttestvalues) creates and returns a test canvas.rendercontext based on the provided application and environment context parameters. signature public static canvas.rendercontext mockrendercontext(map<string,string> applicationcontexttestvalues, map<string,string> environmentcontexttestvalues) parameters applicationcontexttestvalues type: map<string,string> specifies a map of key-value pairs that provide mock application context data. use constants that are provided by canvas.test as keys. if |
null is provided for this parameter, the canvas framework generates some default mock application context values. environmentcontexttestvalues type: map<string,string> specifies a map of key-value pairs that provide mock environment context data. use constants provided by canvas.test as keys. if null is provided for this parameter, the canvas framework generates some default mock environment context values. return value type: canvas.rendercontext 251apex reference guide test class usage use this method to create a mock canvas.rendercontext. use the returned rendercontext in calls to canvas.test.testcanvaslifecycle(lifecyclehandler, mockrendercontext) for testing canvas.canvaslifecyclehandler implementations. example the following example creates maps to represent mock application and environment context data and generates a test canvas.rendercontext. this test rendercontext can be used in a call to canvas.test.testcanvaslifecycle(lifecyclehandler, mockrendercontext). map<string,string> appvalues = new map<string,string>(); appvalues.put(canvas.test.key_namespace,'alternatenamespace'); appvalues.put(canvas.test.key_version,'3.0'); map<string,string> envvalues = new map<string,string>(); envvalues.put(canvas.test.key_display_location,'chatter'); envvalues.put(canvas.test.key_location_url,'https://mydomainname.my.salesforce.com/_ui/core/chatter/ui/chatterpage'); canvas.rendercontext mock = canvas.test.mockrendercontext(appvalues,envvalues); testcanvaslifecycle(lifecyclehandler, mockrendercontext) calls the canvas test framework to invoke a canvaslifecyclehandler with the provided rendercontext. signature public static void testcanvaslifecycle(canvas.canvaslifecyclehandler lifecyclehandler,canvas.rendercontext mockrendercontext) parameters lifecyclehandler type: canvas.canvaslifecyclehandler specifies the canvaslifecyclehandler implementation that you need to invoke. mockrendercontext type: canvas.rendercontext specifies the rendercontext information that you need to provide to the invoked canvaslifecyclehandler. if null is provided for this parameter, the canvas framework generates and uses a default mock rendercontext. return value type: void usage use this method to invoke an implementation of canvas.canvaslifecyclehandler.onrender(rendercontext) with a mock canvas.rendercontext that you provide. 252apex reference guide canvas exceptions example the following example creates maps to represent mock application and environment context data and generates a test canvas.rendercontext. this test rendercontext is then used to invoke a canvas.canvaslifecyclehandler. // set some application context data in a map map<string,string> appvalues = new map<string,string>(); appvalues.put(canvas.test.key_namespace,'alternatenamespace'); appvalues.put(canvas.test.key_version,'3.0'); // set some environment context data in a map map<string,string> envvalues = new map<string,string>(); envvalues.put(canvas.test.key_display_location,'chatter'); envvalues.put(canvas.test.key_location_url,'https://mydomainname.my.salesforce.com/_ui/core/chatter/ui/chatterpage'); // create a mock rendercontext using the test application and environment context data maps canvas.rendercontext mock = canvas.test.mockrendercontext(appvalues,envvalues); // set some custom params on the mock rendercontext mock.getenvironmentcontext().setparametersasjson('{\"param1\":1,\"boolparam\":true,\"stringparam\":\"test string\"}'); // use the mock rendercontext to invoke a canvaslifecyclehandler canvas.test.testcanvaslifecycle(handler,mock) canvas exceptions the canvas namespace contains exception classes. all exception classes support built-in methods for returning the error message and exception type. see exception class and built-in exceptions. the canvas namespace contains this exception: exception description canvas.canvasrenderexception use this class in your implementation of canvas.canvaslifecycle |
handler.onrender(rendercontext). to show an error to the user in your onrender() implementation, throw a canvas.canvasrenderexception, and the canvas framework will render the error message to the user. this exception will be managed only within the onrender() method. example the following example implementation of onrender() catches a canvasexception that was thrown because a canvas url was set with a string that exceeded the maximum length. a canvasrenderexception is created and thrown to display the error to the user. public class mycanvaslistener implements canvas.canvaslifecyclehandler { public void onrender(canvas.rendercontext rendercontext) { 253apex reference guide chatteranswers namespace canvas.applicationcontext app = rendercontext.getapplicationcontext(); // code to generate a url string that is too long // ... // try to set the canvas app url using the invalid url string try { app.setcanvasurlpath(aurlpaththatistoolong); } catch (canvasexception e) { // display error to user by throwing a new canvasrenderexception throw new canvas.canvasrenderexception(e.getmessage()); } } } see the canvas developer guide for additional examples that use canvasrenderexception. chatteranswers namespace the chatteranswers namespace provides an interface for creating account records. the following is the interface in the chatteranswers namespace. in this section: accountcreator interface creates account records that will be associated with chatter answers users. accountcreator interface creates account records that will be associated with chatter answers users. namespace chatteranswers usage the chatteranswers.accountcreator is specified in the registrationclassname attribute of a chatteranswers:registration visualforce component. this interface is called by chatter answers and allows for custom creation of account records used for portal users. to implement the chatteranswers.accountcreator interface, you must first declare a class with the implements keyword as follows: public class chatteranswersregistration implements chatteranswers.accountcreator { 254apex reference guide accountcreator interface next, your class must provide an implementation for the following method: public string createaccount(string firstname, string lastname, id siteadminid) { // your code here } the implemented method must be declared as global or public. in this section: accountcreator methods accountcreator example implementation accountcreator methods the following are methods for accountcreator. in this section: createaccount(firstname, lastname, siteadminid) accepts basic user information and creates an account record. the implementation of this method returns the account id. createaccount(firstname, lastname, siteadminid) accepts basic user information and creates an account record. the implementation of this method returns the account id. signature public string createaccount(string firstname, string lastname, id siteadminid) parameters firstname type: string the first name of the user who is registering. lastname type: string the last name of the user who is registering. siteadminid type: id the user id of the site administrator, used for notification if any exceptions occur. return value type: string 255apex reference guide commercepayments namespace accountcreator example implementation this is an example implementation of the chatteranswers.accountcreator interface. the createaccount method implementation accepts user information and creates an account record. the method returns a string value for the account id. public class chatteranswersregistration implements chatteranswers.accountcreator { public string createaccount(string firstname, string lastname, id siteadminid) { account a = new account(name = firstname + ' ' + lastname, ownerid = siteadminid); insert a; return a.id; } } this example tests the code above. @istest private class chatteranswerscreateaccounttest { static testmethod void validateaccountcreation() { user[] user = [select id, firstname, lastname from user where usertype='standard']; if (user.size() == 0) { return; } string firstname = user[0].firstname; string lastname = user[0].lastname; string userid = user[0].id; string accountid = new chatteranswersregistration().createaccount(firstname, lastname, userid); account acct = [select name |
, ownerid from account where id =: accountid]; system.assertequals(firstname + ' ' + lastname, acct.name); system.assertequals(userid, acct.ownerid); } } commercepayments namespace use the commercepayments namespace to provide a safe and customizable platform for managing customer payments and refunds. to review commercepayments use cases and walkthroughs, go to use cases for the commercepayments namespace. the following are the classes in the commercepayments namespace. in this section: abstractresponse class contains the normalized response fields from payment gateways that are common to all the other gateway responses. addressrequest class contains address request data that is sent to a gateway adapter during a service call. auditparamsrequest auditparamsrequest is used for audit parameters in a transaction request. this is an abstract request class that is extended by the baserequest class. 256apex reference guide commercepayments namespace abstracttransactionresponse class abstract class for storing normalized information sent from payment gateways about a payment transaction. holds the common response fields sent from payment gateways for authorization, sale, capture, and refund transactions. authapipaymentmethodrequest class sends information about a payment method to a gateway adapter during an authorization service call. authorizationreversalrequest class sends information about an authorization reversal request to a gateway adapter during a service call. authorizationreversalresponse class response sent by the payment gateway following a payment authorization reversal service. authorizationrequest class sends information about an authorization request to a gateway adapter during a service call. authorizationresponse class response sent by the payment gateway adapter for an authorization service. baseapipaymentmethodrequest class abstract class used to send information about a payment method to a gateway adapter during a service call. basenotification class abstract class for storing notification information sent from payment gateways. basepaymentmethodrequest class abstract class for storing information about payment methods. baserequest class baserequest is extended by all the request classes. capturenotification class when a payment gateway sends a notification for a capture transaction, the payment gateway adapter creates the capturenotification object to store information about the notification. capturerequest class represents a capture request. this class extends the baserequest class and inherits all its methods. captureresponse class the payment gateway adapter sends this response for the capture request type. this class extends abstractresponse and inherits its methods. cardcategory enum defines whether the payment method represents a credit card or a debit card. cardpaymentmethodrequest class sends data related to a card payment method to a gateway adapter during a service call. custommetadatatypeinfo class access information about custom metadata. the paymentgatewayadapter can send custommetadatatypeinfo to transaction requests through the response object’s salesforceresultcodeinfo. gatewayerrorresponse class use to respond with an error indication following errors from the paymentgateway adapter, such as request-forbidden responses, custom validation errors, or expired api tokens. 257apex reference guide commercepayments namespace gatewaynotificationresponse class when the payment gateway sends a notification to the payments platform, the platform responds with a gatewaynotificationresponse indicating whether the platform succeeded or failed at receiving the notification. gatewayresponse interface generic payment gateway response interface. this class extends the captureresponse on page 312, abstracttransactionresponse on page 268, and abstractresponse on page 259 classes and inherits all their properties. it has no unique methods or parameters. notificationclient class communicates with the payment platform regarding the gateway’s notification. notificationsaveresult class contains the result of the payment platform’s attempt to record data from the gateway’s notification. notificationstatus enum shows whether the payments platform successfully received the notification from the gateway. paymentgatewayadapter interface paymentgatewayadapters can implement this interface in order to process requests. paymentgatewayasyncadapter interface implement the interface to allow customers to process payments asynchronously. paymentgatewaycontext class wraps the information related to a payment request. paymentgatewaynotificationcontext class wraps the information related to a gateway notification. paymentmethodtokenizationrequest class stores data about a request to tokenize a card payment method. the tokenization process occurs in the payment gateway. this process replaces sensitive customer data, such as a card number or cvv, with unique identification symbols. the symbols are used while the data is handled by salesforce, the payment gateway, and the customer |
bank, allowing salesforce to store the token without storing sensitive customer data. paymentmethodtokenizationresponse class gateway response sent by payment gateway adapters for the payment method tokenization request. the response includes the payment method’s token id value. paymentgatewaynotificationrequest class contains the notification request data from the gateway. paymentshttp class makes an http request to start the interaction with the payment gateway. refundrequest class sends data related to a refund to the payment gateway adapter. referencedrefundnotification class when a payment gateway sends a notification for a refund transaction, the payment gateway adapter creates the referencedrefundnotification object to store information about notification. referencedrefundrequest access information about the referenced refund requests. extends the refundrequest class. referencedrefundresponse class the payment gateway adapter sends this response for the referencedrefund request type. 258apex reference guide abstractresponse class requesttype enum defines the type of payment transaction request made to the payment gateway. saleapipaymentmethodrequest class sends data related to a card payment method to a gateway adapter during a sale service call. salerequest class stores information about a sales request. saleresponse class response sent by payment gateway adapters for a sales service. salesforceresultcode enum defines the gateway call status values in salesforce based on the call status values that the payment gateway returned. salesforceresultcodeinfo stores salesforce result code information from payment gateway adapters. abstractresponse class contains the normalized response fields from payment gateways that are common to all the other gateway responses. namespace commercepayments usage you must specify the commercepayments namespace when creating an instance of this class. the constructor of this class takes no arguments. for example: commercepayments.abstractresponse abr = new commercepayments.abstractresponse(); this class can’t be instantiated on its own. this class implements the gatewayresponse class. other gatewayresponse classes extend this class to inherit common properties. in this section: abstractresponse methods abstractresponse methods the following are methods for abstractresponse. in this section: setgatewayavscode(gatewayavscode) sets the avs (address verification system) result code information that the gateway returned. maximum length of 64 characters. setgatewaydate(gatewaydate) sets the date that the transaction occurred. some gateways don’t send this value. setgatewaymessage(gatewaymessage) sets error messages that the gateway returned for the payment request. maximum length of 255 characters. 259apex reference guide abstractresponse class setgatewayresultcode(gatewayresultcode) sets a gateway-specific result code. the code may be mapped to a salesforce-specific result code. maximum length of 64 characters. setgatewayresultcodedescription(gatewayresultcodedescription) sets a description of the gateway-specific result code that a payment gateway returned. maximum length of 1000 characters. setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets the salesforce-specific result code information. payment gateways have many response codes for payment calls. salesforce uses the result code information to map payment gateway codes to a predefined set of standard salesforce result codes. setgatewayavscode(gatewayavscode) sets the avs (address verification system) result code information that the gateway returned. maximum length of 64 characters. signature global void setgatewayavscode(string gatewayavscode) parameters gatewayavscode type: string code sent by gateways that use an address verification system. return value type: void setgatewaydate(gatewaydate) sets the date that the transaction occurred. some gateways don’t send this value. signature global void setgatewaydate(datetime gatewaydate) parameters gatewaydate type: datetime date and time of the gateway communication. return value type: void setgatewaymessage(gatewaymessage) sets error messages that the gateway returned for the payment request. maximum length of 255 characters. 260apex reference guide abstractresponse class signature global void setgatewaymessage(string gatewaymessage) parameters gatewaymessage type: string information on error messages sent from the gateway. return value type: void setgatewayresultcode(gatewayresultcode) sets a gateway-specific result code. the code may be mapped to a salesforce-specific result code. |
maximum length of 64 characters. signature global void setgatewayresultcode(string gatewayresultcode) parameters gatewayresultcode type: string gateway-specific result code. must be used to map a salesforce-specific result code. return value type: void setgatewayresultcodedescription(gatewayresultcodedescription) sets a description of the gateway-specific result code that a payment gateway returned. maximum length of 1000 characters. signature global void setgatewayresultcodedescription(string gatewayresultcodedescription) parameters gatewayresultcodedescription type: string description of the gateway’s result code. use this field to learn more about why the gateway returned a certain result code. return value type: void 261apex reference guide addressrequest class setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets the salesforce-specific result code information. payment gateways have many response codes for payment calls. salesforce uses the result code information to map payment gateway codes to a predefined set of standard salesforce result codes. signature global void setsalesforceresultcodeinfo(commercepayments.salesforceresultcodeinfo salesforceresultcodeinfo) parameters salesforceresultcodeinfo type: commercepayments.salesforceresultcodeinfo on page 380 description of the salesforce result code value. return value type: void addressrequest class contains address request data that is sent to a gateway adapter during a service call. namespace commercepayments usage contains information about the payment method’s address. use this information in authorization, sale, and tokenization requests. the payment gateway adapter uses information in an addressrequest object to construct a json request to send to the payment gateway. the constructor of this class takes no arguments. for example: commercepayments.addressrequest adr = new commercepayments.addressrequest(); in this section: addressrequest constructors addressrequest properties addressrequest methods addressrequest constructors the following are constructors for addressrequest. 262apex reference guide addressrequest class in this section: addressrequest(street, city, state, country, postalcode) constructs a sample address. this constructor is intended for test usage and throws an exception if used outside of the apex test context. addressrequest(street, city, state, country, postalcode) constructs a sample address. this constructor is intended for test usage and throws an exception if used outside of the apex test context. signature global addressrequest(string street, string city, string state, string country, string postalcode) parameters street type: string street for the payment method's address. city type: string city for the payment method's address. state type: string state for the payment method's address. country type: string country for the payment method's address. postalcode type: string postal code for the payment method's address. addressrequest properties the following are properties for addressrequest. in this section: city city of the payment method address. companyname company name of the payment method address. country country for the payment method address. 263apex reference guide addressrequest class postalcode postal code for the payment method address. state state for the payment method address. street street for the payment method address. city city of the payment method address. signature global string city {get; set;} property value type: string companyname company name of the payment method address. signature global string companyname {get; set;} property value type: string country country for the payment method address. signature global string country {get; set;} property value type: string postalcode postal code for the payment method address. signature global string postalcode {get; set;} 264apex reference guide addressrequest class property value type: string state state for the payment method address. signature global string state {get; set;} property value type: string street street for the payment method address. signature global string street {get; set;} property value type: string addressrequest methods the following are methods for addressrequest. in this section: equals(obj) maintains the integrity of lists of type addressrequest by determining the equality of external objects in a list. this method is dynamic and is based on the equals method in java. hashcode() maintains the integrity of lists of type addressrequest. to |
string() converts a date to a string. equals(obj) maintains the integrity of lists of type addressrequest by determining the equality of external objects in a list. this method is dynamic and is based on the equals method in java. signature global boolean equals(object obj) 265apex reference guide auditparamsrequest parameters obj type: object external object whose key is to be validated. return value type: boolean hashcode() maintains the integrity of lists of type addressrequest. signature global integer hashcode() return value type: integer tostring() converts a date to a string. signature global string tostring() return value type: string auditparamsrequest auditparamsrequest is used for audit parameters in a transaction request. this is an abstract request class that is extended by the baserequest class. namespace commercepayments usage auditparamsrequest is an abstract class that holds attributes related to audit parameters such as email, ip address, mac address, and phone number. this class can't be instantiated on its own. all commercepayments request classes extend this class. 266apex reference guide auditparamsrequest in this section: auditparamsrequest constructors auditparamsrequest properties auditparamsrequest constructors the following are constructors for auditparamsrequest. in this section: auditparamsrequest(email, macaddress, ipaddress, phone) this constructor is intended for test usage and throws an exception if used outside of the apex test context. auditparamsrequest(email, macaddress, ipaddress, phone) this constructor is intended for test usage and throws an exception if used outside of the apex test context. signature auditparamsrequest(string email, string macaddress, string ipaddress, string phone) parameters email type: string email of the client that initiated the request. macaddress type: string mac address of the customer’s device. gateways often use this data in risk checks. ipaddress type: string the customer’s ip address. gateways often use this data in risk checks. phone type: string phone number of the client that initiated the request. auditparamsrequest properties the following are properties for auditparamsrequest. in this section: email email of the client that initiated the request. ipaddress the customer’s ip address. gateways often use this data in risk checks. 267apex reference guide abstracttransactionresponse class macaddress mac address of the customer’s device. gateways often use this data in risk checks. phone phone number of the client that initiated the request. email email of the client that initiated the request. property value type: string ipaddress the customer’s ip address. gateways often use this data in risk checks. property value type: string macaddress mac address of the customer’s device. gateways often use this data in risk checks. property value type: string phone phone number of the client that initiated the request. property value type: string abstracttransactionresponse class abstract class for storing normalized information sent from payment gateways about a payment transaction. holds the common response fields sent from payment gateways for authorization, sale, capture, and refund transactions. namespace commercepayments 268apex reference guide abstracttransactionresponse class usage specify the commercepayments namespace when creating an instance of this class. the constructor of this class takes no arguments. for example: commercepayments.abstracttransactionresponse atr = new commercepayments.abstracttransactionresponse(); in this section: abstracttransactionresponse methods abstracttransactionresponse methods the following are methods for abstracttransactionresponse. in this section: setamount(amount) sets the transaction amount. must be a non-negative value. setgatewayavscode(gatewayavscode) sets the avs (address verification system) result code that the gateway returned. maximum length of 64 characters. setgatewaydate(gatewaydate) sets the date that the notification occurred. some gateways don’t send this value. setgatewaymessage(gatewaymessage) sets error messages that the gateway returned for the notification request. maximum length of 255 characters. setgatewayreferencedetails(gatewayreferencedetails) sets the payment gateway’s reference details. setgatewayreferencenumber(gatewayreferencenumber) sets the payment gateway’s reference number. |
setgatewayresultcode(gatewayresultcode) sets a gateway-specific result code. you can map the result code to a salesforce-specific result code. maximum length of 64 characters. setgatewayresultcodedescription(gatewayresultcodedescription) sets a description of the gateway-specific result code that a payment gateway returned. maximum length of 1000 characters. setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets the salesforce-specific result code information. setamount(amount) sets the transaction amount. must be a non-negative value. signature global void setamount(double amount) 269apex reference guide abstracttransactionresponse class parameters amount type: double the amount of the transaction. return value type: void setgatewayavscode(gatewayavscode) sets the avs (address verification system) result code that the gateway returned. maximum length of 64 characters. signature global void setgatewayavscode(string gatewayavscode) parameters gatewayavscode type: string used to verify the address mapped to a payment method when the payments platform requests tokenization from the payment gateway. return value type: void setgatewaydate(gatewaydate) sets the date that the notification occurred. some gateways don’t send this value. signature global void setgatewaydate(datetime gatewaydate) parameters gatewaydate type: datetime the date that the transaction occurred. return value type: void setgatewaymessage(gatewaymessage) sets error messages that the gateway returned for the notification request. maximum length of 255 characters. 270apex reference guide abstracttransactionresponse class signature global void setgatewaymessage(string gatewaymessage) parameters gatewaymessage type: string the message that the gateway returned with the transaction request. contains additional information about the transaction. return value type: void setgatewayreferencedetails(gatewayreferencedetails) sets the payment gateway’s reference details. signature global void setgatewayreferencedetails(string gatewayreferencedetails) parameters gatewayreferencedetails type: string provides information about the gateway communication. return value type: void setgatewayreferencenumber(gatewayreferencenumber) sets the payment gateway’s reference number. signature global void setgatewayreferencenumber(string gatewayreferencenumber) parameters gatewayreferencenumber type: string unique transaction id created by the payment gateway. return value type: void 271apex reference guide abstracttransactionresponse class setgatewayresultcode(gatewayresultcode) sets a gateway-specific result code. you can map the result code to a salesforce-specific result code. maximum length of 64 characters. signature global void setgatewayresultcode(string gatewayresultcode) parameters gatewayresultcode type: string gateway-specific result code. must be mapped to a salesforce-specific result code. return value type: void setgatewayresultcodedescription(gatewayresultcodedescription) sets a description of the gateway-specific result code that a payment gateway returned. maximum length of 1000 characters. signature global void setgatewayresultcodedescription(string gatewayresultcodedescription) parameters gatewayresultcodedescription type: string provides additional information about the result code and why the gateway returned the specific code. descriptions vary between different gateways. return value type: void setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets the salesforce-specific result code information. signature global void setsalesforceresultcodeinfo(commercepayments.salesforceresultcodeinfo salesforceresultcodeinfo) parameters salesforceresultcodeinfo type: commercepayments.salesforceresultcodeinfo on page 380 272apex reference guide authapipaymentmethodrequest class payment gateways have many response codes for payment calls. salesforce uses the result code information to map payment gateway codes to a predefined set of standard salesforce result codes. return value type: void authapipaymentmethodrequest class sends information about a payment method to a gateway adapter during an authorization service call. namespace commercepayments usage contains information about the payment method that is used for an authorization request. it contains all available payment methods as fields, but populates only one field for each request. the gateway adapter uses this class when constructing an authorization request. an object of this class is available through the paymentmethod field on |
the authorizationrequest class object. in this section: authapipaymentmethodrequest constructors authapipaymentmethodrequest properties authapipaymentmethodrequest constructors the following are constructors for authapipaymentmethodrequest. in this section: authapipaymentmethodrequest(cardpaymentmethodrequest) constructs a sample cardpaymentmethodrequest. this constructor is intended for test usage and throws an exception if used outside of the apex test context. authapipaymentmethodrequest() constructor for authapipaymentmethodrequest. authapipaymentmethodrequest(cardpaymentmethodrequest) constructs a sample cardpaymentmethodrequest. this constructor is intended for test usage and throws an exception if used outside of the apex test context. signature global authapipaymentmethodrequest(commercepayments.cardpaymentmethodrequest cardpaymentmethodrequest) 273apex reference guide authorizationreversalrequest class parameters cardpaymentmethodrequest type: commercepayments.cardpaymentmethodrequest on page 318 contains information about the card payment method. used to send information to a gateway adapter during a service call. authapipaymentmethodrequest() constructor for authapipaymentmethodrequest. signature global authapipaymentmethodrequest() authapipaymentmethodrequest properties the following are properties for authapipaymentmethodrequest. in this section: cardpaymentmethod the card payment method object used in a payment method request. cardpaymentmethod the card payment method object used in a payment method request. signature global commercepayments.cardpaymentmethodrequest cardpaymentmethod {get; set;} property value type: commercepayments.cardpaymentmethodrequest on page 318 authorizationreversalrequest class sends information about an authorization reversal request to a gateway adapter during a service call. namespace commercepayments on page 256 example add your reversal classes to your payment gateway adapter. we recommend adding authorizationreversal as a possible requesttype value when calling processrequest on the gateway’s response. global commercepayments.gatewayresponse processrequest(commercepayments.paymentgatewaycontext gatewaycontext) { 274apex reference guide authorizationreversalrequest class commercepayments.requesttype requesttype = gatewaycontext.getpaymentrequesttype(); commercepayments.gatewayresponse response; try { //add other requesttype values here //.. else if (requesttype == commercepayments.requesttype.authorizationreversal) { response = createauthreversalresponse((commercepayments.authorizationreversalrequest)gatewaycontext.getpaymentrequest());} return response; then, add a class that sets the amount of the authorization reversal request, as well as gateway information and the salesforce result code. global commercepayments.gatewayresponse createauthreversalresponse(commercepayments.authorizationreversalrequest authreversalrequest) { commercepayments.authorizationreversalresponse authreversalresponse = new commercepayments.authorizationreversalresponse(); if(authreversalrequest.amount!=null ) { authreversalresponse.setamount(authreversalrequest.amount); } else { throw new salesforcevalidationexception('required field missing : amount'); } system.debug('response - success'); authreversalresponse.setgatewaydate(system.now()); authreversalresponse.setgatewayresultcode('00'); authreversalresponse.setgatewayresultcodedescription('transaction normal'); authreversalresponse.setgatewayreferencenumber('sf'+getrandomnumber(6)); authreversalresponse.setsalesforceresultcodeinfo(success_salesforce_result_code_info); return authreversalresponse; } in this section: authorizationreversalrequest constructors authorizationreversalrequest properties authorizationreversalrequest methods authorizationreversalrequest constructors the following are constructors for authorizationreversalrequest. 275apex reference guide authorizationreversalrequest class in this section: authorizationreversalrequest(amount, authorizationid) constructor for building the amount in an authorization reversal request. this constructor is intended for test usage and throws an exception if used outside of the apex test context. authorizationreversalrequest(amount, authorizationid) constructor for building the amount in |
an authorization reversal request. this constructor is intended for test usage and throws an exception if used outside of the apex test context. signature global authorizationreversalrequest(double amount, string authorizationid) parameters amount type: double the amount of the authorization reversal request. authorizationid type: string the authorization request to be reversed. authorizationreversalrequest properties the following are properties for authorizationreversalrequest. in this section: accountid references the customer account for the transaction where the authorization reversal was performed. amount the total amount of the authorization reversal request. can be positive or negative. paymentauthorizationid references the payment authorization to be reversed. accountid references the customer account for the transaction where the authorization reversal was performed. signature global string accountid {get; set;} property value type: string 276apex reference guide authorizationreversalrequest class amount the total amount of the authorization reversal request. can be positive or negative. signature global double amount {get; set;} property value type: double paymentauthorizationid references the payment authorization to be reversed. signature global string paymentauthorizationid {get; set;} property value type: string authorizationreversalrequest methods the following are methods for authorizationreversalrequest. in this section: equals(obj) maintains the integrity of lists of type authorizationreversalrequest by determining the equality of external objects in a list. this method is dynamic and based on the equals method in java. hashcode() maintains the integrity of lists of type authorizationreversalrequest by determining the uniqueness of the external object in a list. tostring() converts a date to a string. equals(obj) maintains the integrity of lists of type authorizationreversalrequest by determining the equality of external objects in a list. this method is dynamic and based on the equals method in java. signature global boolean equals(object obj) 277apex reference guide authorizationreversalresponse class parameters obj type: object external object whose key is to be validated. return value type: boolean hashcode() maintains the integrity of lists of type authorizationreversalrequest by determining the uniqueness of the external object in a list. signature global integer hashcode() return value type: integer tostring() converts a date to a string. signature global string tostring() return value type: string authorizationreversalresponse class response sent by the payment gateway following a payment authorization reversal service. namespace commercepayments usage the constructor of this class takes no arguments. for example: commercepayments.authorizationreversalresponse authrevres = new commercepayments.authorizationresponse(); 278apex reference guide authorizationreversalresponse class contains information about the payment gateway’s response following an authorization reversal transaction. the gateway adapter uses the payment gateway’s response to populate the authorizationreversalresponse fields. the payments platform uses the information from this class to construct the authorization gateway response shown to the user. example this class builds an authorization reversal response that contains the amount of the original reversal request, gateway information, and the salesforce result code. global commercepayments.gatewayresponse createauthreversalresponse(commercepayments.authorizationreversalrequest authreversalrequest) { commercepayments.authorizationreversalresponse authreversalresponse = new commercepayments.authorizationreversalresponse(); if(authreversalrequest.amount!=null ) { authreversalresponse.setamount(authreversalrequest.amount); } else { throw new salesforcevalidationexception('required field missing : amount'); } system.debug('response - success'); authreversalresponse.setgatewaydate(system.now()); authreversalresponse.setgatewayresultcode('00'); authreversalresponse.setgatewayresultcodedescription('transaction normal'); authreversalresponse.setgatewayreferencenumber('sf'+getrandomnumber(6)); authreversalresponse.setsalesforceresultcodeinfo(success_salesforce_result_code_info); return authreversalresponse; } in this section: authorizationreversalresponse methods authorizationreversalresponse methods the following are methods for authorizationreversalresponse. in this section: setamount(amount) |
contains the amount of the authorization reversal. must be a non-zero value. setgatewayavscode(gatewayavscode) sets the avs (address verification system) result code that the gateway returned. maximum length of 64 characters. setgatewaydate(gatewaydate) sets the date that the authorization reversal request occurred in the payment gateway. some gateways don't send this value. 279apex reference guide authorizationreversalresponse class setgatewaymessage(gatewaymessage) sets error messages that the gateway returned for the authorization reversal request. maximum length of 255 characters. setgatewayreferencedetails(gatewayreferencedetails) stores data that you can use for subsequent authorizations. you can use any data that isn’t normalized in financial entities. this field has a maximum length of 1000 characters and can store data as json or xml. setgatewayreferencenumber(gatewayreferencenumber) sets a unique gateway reference number for the transaction that the gateway returned. maximum length of 255 characters. setgatewayresultcode(gatewayresultcode) sets a gateway-specific result code. the code can be mapped to a salesforce-specific result code. maximum length of 64 characters. setgatewayresultcodedescription(gatewayresultcodedescription) sets a description of the gateway-specific result code that a payment gateway returned. maximum length of 1000 characters. setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets the salesforce-specific result code information. payment gateways have many response codes for payment calls. salesforce uses the result code information to map payment gateway codes to a predefined set of standard salesforce result codes. setamount(amount) contains the amount of the authorization reversal. must be a non-zero value. signature global void setamount(double amount) parameters amount type: double return value type: void setgatewayavscode(gatewayavscode) sets the avs (address verification system) result code that the gateway returned. maximum length of 64 characters. signature global void setgatewayavscode(string gatewayavscode) parameters gatewayavscode type: string used to verify the address mapped to a payment method when the payments platform requests tokenization from the payment gateway. 280apex reference guide authorizationreversalresponse class return value type: void setgatewaydate(gatewaydate) sets the date that the authorization reversal request occurred in the payment gateway. some gateways don't send this value. signature global void setgatewaydate(datetime gatewaydate) parameters gatewaydate type: datetime return value type: void setgatewaymessage(gatewaymessage) sets error messages that the gateway returned for the authorization reversal request. maximum length of 255 characters. signature global void setgatewaymessage(string gatewaymessage) parameters gatewaymessage type: string return value type: void setgatewayreferencedetails(gatewayreferencedetails) stores data that you can use for subsequent authorizations. you can use any data that isn’t normalized in financial entities. this field has a maximum length of 1000 characters and can store data as json or xml. signature global void setgatewayreferencedetails(string gatewayreferencedetails) parameters gatewayreferencedetails type: string 281apex reference guide authorizationreversalresponse class return value type: void setgatewayreferencenumber(gatewayreferencenumber) sets a unique gateway reference number for the transaction that the gateway returned. maximum length of 255 characters. signature global void setgatewayreferencenumber(string gatewayreferencenumber) parameters gatewayreferencenumber type: string unique reference id created by the payment gateway. return value type: void setgatewayresultcode(gatewayresultcode) sets a gateway-specific result code. the code can be mapped to a salesforce-specific result code. maximum length of 64 characters. signature global void setgatewayresultcode(string gatewayresultcode) parameters gatewayresultcode type: string gateway-specific result code. must be used to map a salesforce-specific result code. return value type: void setgatewayresultcodedescription(gatewayresultcodedescription) sets a description of the gateway-specific result code that a payment gateway returned. maximum length of 1000 characters. signature global void setgatewayresultcodedescription(string gatewayresultcodedescription) 282 |
apex reference guide authorizationrequest class parameters gatewayresultcodedescription type: string description of the gateway’s result code. use this field to learn more about why the gateway returned a certain result code. return value type: void setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets the salesforce-specific result code information. payment gateways have many response codes for payment calls. salesforce uses the result code information to map payment gateway codes to a predefined set of standard salesforce result codes. signature global void setsalesforceresultcodeinfo(commercepayments.salesforceresultcodeinfo salesforceresultcodeinfo) parameters salesforceresultcodeinfo type: salesforceresultcodeinfo description of the salesforce result code value. return value type: void authorizationrequest class sends information about an authorization request to a gateway adapter during a service call. namespace commercepayments usage this class contains information about a transaction authorization request. the gateway adapter reads fields from this class while constructing an authorization json request to send to the payment gateway. an object of this class is available by calling getpaymentrequest() in the paymentgatewaycontext class. 283apex reference guide authorizationrequest class example creating a buildauthrequest class to store information about the authorization request. private string buildauthrequest(commercepayments.authorizationrequest authrequest) { // multiply amount by 100.0 to convert to cents string requestbody = createrequestbody(string.valueof((authrequest.amount*100.0).intvalue()), authrequest); return requestbody; private string createrequestbody(string amount, commercepayments.authorizationrequest authrequest) { jsongenerator jsongeneratorinstance = json.creategenerator(true); string currencyiso = authrequest.currencyisocode; commercepayments.authapipaymentmethodrequest paymentmethod = authrequest.paymentmethod; commercepayments.gatewayerrorresponse error; // write data to the json string. jsongeneratorinstance.writestartobject(); jsongeneratorinstance.writestringfield('merchantaccount', '{!$credential.username}'); jsongeneratorinstance.writestringfield('reference', authrequest.comments == null ? 'randomstring' : authrequest.comments); if(currencyiso == null) { currencyiso = userinfo.getdefaultcurrency(); } jsongeneratorinstance.writefieldname('amount'); jsongeneratorinstance.writestartobject(); jsongeneratorinstance.writestringfield('value', amount); jsongeneratorinstance.writestringfield('currency', currencyiso); jsongeneratorinstance.writeendobject(); commercepayments.cardpaymentmethodrequest cardpaymentmethod; if(paymentmethod != null) { cardpaymentmethod = paymentmethod.cardpaymentmethod; if (cardpaymentmethod != null) { if (cardpaymentmethod.cardcategory != null) { if (commercepayments.cardcategory.creditcard == cardpaymentmethod.cardcategory) { jsongeneratorinstance.writefieldname('card'); jsongeneratorinstance.writestartobject(); if (cardpaymentmethod.cvv != null) jsongeneratorinstance.writestringfield('cvc', string.valueof(cardpaymentmethod.cvv)); if (cardpaymentmethod.cardholdername != null) jsongeneratorinstance.writestringfield('holdername', cardpaymentmethod.cardholdername); if (cardpaymentmethod.cardnumber != null) jsongeneratorinstance.writestringfield('number', cardpaymentmethod.cardnumber); if (cardpaymentmethod.expirymonth != null && cardpaymentmethod.expiryyear != null ) { string expmonth = 284apex reference guide authorizationrequest class ((string.valueof(cardpaymentmethod.expirymonth)).length() == 1 ? '0' : '') + string.valueof(cardpaymentmethod.expirymonth); jsongeneratorinstance.writestringfield('expirymonth', expmonth); jsongeneratorinstance.writestringfield('expiryyear', string.valueof(cardpaymentmethod.expiryyear)); } jsongeneratorinstance.writeendobject(); } else { //support for other card type } } else { throw new samplevalidationexception('required field missing : cardcategory'); } } else { throw new samplevalidationexception |
('required field missing : cardpaymentmethod'); } } else { throw new samplevalidationexception('required field missing : paymentmethod'); } jsongeneratorinstance.writeendobject(); return jsongeneratorinstance.getasstring(); } in this section: authorizationrequest constructors authorizationrequest properties authorizationrequest methods authorizationrequest constructors the following are constructors for authorizationrequest. in this section: authorizationrequest(amount) constructor for building the amount in an authorization request. this constructor is intended for test usage and throws an exception if used outside of the apex test context. authorizationrequest(amount) constructor for building the amount in an authorization request. this constructor is intended for test usage and throws an exception if used outside of the apex test context. signature global authorizationrequest(double amount) 285apex reference guide authorizationrequest class parameters amount type: double the amount of the authorization. authorizationrequest properties the following are properties for authorizationrequest. in this section: accountid the customer account where the authorization is performed. amount the total amount of the authorization. can be positive or negative. comments comments about the authorization. users can enter comments to provide additional information. currencyisocode the iso currency code for the authorization request. paymentmethod the payment method used to process the authorization in the authorization request. accountid the customer account where the authorization is performed. signature global string accountid {get; set;} property value type: string amount the total amount of the authorization. can be positive or negative. signature global double amount {get; set;} property value type: double 286apex reference guide authorizationrequest class comments comments about the authorization. users can enter comments to provide additional information. signature global string comments {get; set;} property value type: string currencyisocode the iso currency code for the authorization request. signature global string currencyisocode {get; set;} property value type: string paymentmethod the payment method used to process the authorization in the authorization request. signature global authapipaymentmethodrequest paymentmethod {get; set;} property value type: authapipaymentmethodrequest on page 273 authorizationrequest methods the following are methods for authorizationrequest. in this section: equals(obj) maintains the integrity of lists of type authorizationrequest by determining the equality of external objects in a list. this method is dynamic and based on the equals method in java. hashcode() maintains the integrity of lists of type authorizationrequest by determining the uniqueness of the external object in a list. tostring() converts a date to a string. 287apex reference guide authorizationresponse class equals(obj) maintains the integrity of lists of type authorizationrequest by determining the equality of external objects in a list. this method is dynamic and based on the equals method in java. signature global boolean equals(object obj) parameters obj type: object external object whose key is to be validated. return value type: boolean hashcode() maintains the integrity of lists of type authorizationrequest by determining the uniqueness of the external object in a list. signature global integer hashcode() return value type: integer tostring() converts a date to a string. signature global string tostring() return value type: string authorizationresponse class response sent by the payment gateway adapter for an authorization service. namespace commercepayments 288apex reference guide authorizationresponse class usage the constructor of this class takes no arguments. for example: commercepayments.authorizationresponse authr = new commercepayments.authorizationresponse(); contains information about the payment gateway’s response following an authorization transaction. the gateway adapter uses the payment gateway’s response to populate the authorizationresponse fields. the payments platform uses the information from this class to construct the authorization gateway response shown to the user. example private commercepayments.gatewayresponse createauthresponse(httpresponse response, double amount) { map<string, object> mapofresponsevalues = (map <string, object>) json.deserializeuntyped(response.getbody()); commercepayments.authorizationresponse authresponse = new commercepayments.authorizationresponse(); string resultcode = (string)mapofresponsevalues.get('resultcode'); if(resultcode != null){ system.debug('response - success'); if(resultcode. |
equals('authorised')){ system.debug('status - authorised'); authresponse.setgatewayauthcode((string)mapofresponsevalues.get('authcode')); authresponse.setsalesforceresultcodeinfo(new commercepayments.salesforceresultcodeinfo(commercepayments.salesforceresultcode.success)); } else { //sample returns 200 with refused status in some cases system.debug('status - refused'); authresponse.setgatewayresultcodedescription((string)mapofresponsevalues.get('refusalreason')); authresponse.setsalesforceresultcodeinfo(new commercepayments.salesforceresultcodeinfo(commercepayments.salesforceresultcode.decline)); } authresponse.setgatewayreferencenumber((string)mapofresponsevalues.get('pspreference')); authresponse.setamount(amount); authresponse.setgatewaydate(system.now()); return authresponse; } else { system.debug('response - failed'); system.debug('validation error'); string statuscode = (string)mapofresponsevalues.get('errortype'); string message = (string)mapofresponsevalues.get('message'); commercepayments.gatewayerrorresponse error = new 289apex reference guide authorizationresponse class commercepayments.gatewayerrorresponse(statuscode, message); return error; } } in this section: authorizationresponse methods authorizationresponse methods the following are methods for authorizationresponse. in this section: setamount(amount) sets the amount of the authorization. must be a non-zero value. setauthorizationexpirationdate(authexpdate) sets the expiration date of the authorization request. setgatewayauthcode(gatewayauthcode) sets the authorization code that the gateway returned. maximum length of 64 characters. setgatewayavscode(gatewayavscode) sets the avs (address verification system) result code information that the gateway returned. maximum length of 64 characters. setgatewaydate(gatewaydate) sets the date that the authorization occurred. some gateways don’t send this value. setgatewaymessage(gatewaymessage) sets error messages that the gateway returned for the authorization request. maximum length of 255 characters. setgatewayreferencedetails(gatewayreferencedetails) stores data that you can use for subsequent authorizations. you can use any data that isn’t normalized in financial entities. this field has a maximum length of 1000 characters and can store data as json or xml. setgatewayreferencenumber(gatewayreferencenumber) sets the unique gateway reference number for the transaction that the gateway returned. maximum length of 255 characters. setgatewayresultcode(gatewayresultcode) sets a gateway-specific result code. the code can be mapped to a salesforce-specific result code. maximum length of 64 characters. setgatewayresultcodedescription(gatewayresultcodedescription) sets a description of the gateway-specific result code that a payment gateway returned. maximum length of 1000 characters. setpaymentmethodtokenizationresponse(paymentmethodtokenizationresponse) sets information from the gateway about the tokenized payment method. setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets the salesforce-specific result code information. payment gateways have many response codes for payment calls. salesforce uses the result code information to map payment gateway codes to a predefined set of standard salesforce result codes. 290apex reference guide authorizationresponse class setamount(amount) sets the amount of the authorization. must be a non-zero value. signature global void setamount(double amount) parameters amount type: double return value type: void setauthorizationexpirationdate(authexpdate) sets the expiration date of the authorization request. signature global void setauthorizationexpirationdate(datetime authexpdate) parameters authexpdate type: datetime return value type: void setgatewayauthcode(gatewayauthcode) sets the authorization code that the gateway returned. maximum length of 64 characters. signature global void setgatewayauthcode(string gatewayauthcode) parameters gatewayauthcode type: string the authorization code returned by the gateway. return value type: void 291apex reference guide authorizationresponse class setgatewayavscode(gatewayavscode) sets the avs (address verification system) result code information that the gateway returned. maximum length of 64 characters. signature |
global void setgatewayavscode(string gatewayavscode) parameters gatewayavscode type: string used to verify the address mapped to a payment method when the payments platform requests tokenization from the payment gateway. return value type: void setgatewaydate(gatewaydate) sets the date that the authorization occurred. some gateways don’t send this value. signature global void setgatewaydate(datetime gatewaydate) parameters gatewaydate type: datetime return value type: void setgatewaymessage(gatewaymessage) sets error messages that the gateway returned for the authorization request. maximum length of 255 characters. signature global void setgatewaymessage(string gatewaymessage) parameters gatewaymessage type: string 292apex reference guide authorizationresponse class return value type: void setgatewayreferencedetails(gatewayreferencedetails) stores data that you can use for subsequent authorizations. you can use any data that isn’t normalized in financial entities. this field has a maximum length of 1000 characters and can store data as json or xml. signature global void setgatewayreferencedetails(string gatewayreferencedetails) parameters gatewayreferencedetails type: string return value type: void setgatewayreferencenumber(gatewayreferencenumber) sets the unique gateway reference number for the transaction that the gateway returned. maximum length of 255 characters. signature global void setgatewayreferencenumber(string gatewayreferencenumber) parameters gatewayreferencenumber type: string unique authorization id created by the payment gateway. return value type: void setgatewayresultcode(gatewayresultcode) sets a gateway-specific result code. the code can be mapped to a salesforce-specific result code. maximum length of 64 characters. signature global void setgatewayresultcode(string gatewayresultcode) 293apex reference guide authorizationresponse class parameters gatewayresultcode type: string gateway-specific result code. must be used to map a salesforce-specific result code. return value type: void setgatewayresultcodedescription(gatewayresultcodedescription) sets a description of the gateway-specific result code that a payment gateway returned. maximum length of 1000 characters. signature global void setgatewayresultcodedescription(string gatewayresultcodedescription) parameters gatewayresultcodedescription type: string description of the gateway’s result code. use this field to learn more about why the gateway returned a certain result code. return value type: void setpaymentmethodtokenizationresponse(paymentmethodtokenizationresponse) sets information from the gateway about the tokenized payment method. signature global void setpaymentmethodtokenizationresponse(commercepayments.paymentmethodtokenizationresponse paymentmethodtokenizationresponse) parameters paymentmethodtokenizationresponse paymentmethodtokenizationresponse on page 345 gateway response sent by payment gateway adapters for the payment method tokenization request. return value type: void 294apex reference guide baseapipaymentmethodrequest class setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets the salesforce-specific result code information. payment gateways have many response codes for payment calls. salesforce uses the result code information to map payment gateway codes to a predefined set of standard salesforce result codes. signature global void setsalesforceresultcodeinfo(commercepayments.salesforceresultcodeinfo salesforceresultcodeinfo) parameters salesforceresultcodeinfo type: salesforceresultcodeinfo on page 380 description of the salesforce result code value. return value type: void baseapipaymentmethodrequest class abstract class used to send information about a payment method to a gateway adapter during a service call. namespace commercepayments usage baseapipaymentmethodrequest is the base class for saleapipaymentmethodrequest and authapipaymentmethodrequest. in this section: baseapipaymentmethodrequest constructors baseapipaymentmethodrequest properties baseapipaymentmethodrequest methods baseapipaymentmethodrequest constructors the following are constructors for baseapipaymentmethodrequest. in this section: baseapipaymentmethodrequest(address, id, saveforfuture) constructs a payment method. this constructor is intended for test usage and throws an exception if used outside of the apex test context. 295apex reference guide baseapipaymentmethodrequest class baseapipaymentmethodrequest( |
address, id, saveforfuture) constructs a payment method. this constructor is intended for test usage and throws an exception if used outside of the apex test context. signature global baseapipaymentmethodrequest(commercepayments.addressrequest address, string id, boolean saveforfuture) parameters address type: commercepayments.addressrequest on page 262 sends data related on address request to a gateway adapter during a service call. id type: string saveforfuture type: boolean indicates whether salesforce saves the payment method for future use. baseapipaymentmethodrequest properties the following are properties for baseapipaymentmethodrequest. in this section: address the payment method’s address. id id of the payment method request. saveforfuture indicates whether the payment method is saved as a record in salesforce for future use. address the payment method’s address. signature global commercepayments.addressrequest address {get; set;} property value type: addressrequest on page 262 296apex reference guide baseapipaymentmethodrequest class id id of the payment method request. signature global string id {get; set;} property value type: string saveforfuture indicates whether the payment method is saved as a record in salesforce for future use. signature global boolean saveforfuture {get; set;} property value type: boolean baseapipaymentmethodrequest methods the following are methods for baseapipaymentmethodrequest. in this section: equals(obj) maintains the integrity of lists of type baseapipaymentmethodrequest by determining the equality of external objects in a list. this method is dynamic and is based on the equals method in java. hashcode() maintains the integrity of lists of type baseapipaymentmethodrequest by determining the uniqueness of the external object records in a list. tostring() converts a date to a string. equals(obj) maintains the integrity of lists of type baseapipaymentmethodrequest by determining the equality of external objects in a list. this method is dynamic and is based on the equals method in java. signature global boolean equals(object obj) 297apex reference guide basenotification class parameters obj type: object external object whose key is to be validated. return value type: boolean hashcode() maintains the integrity of lists of type baseapipaymentmethodrequest by determining the uniqueness of the external object records in a list. signature global integer hashcode() return value type: integer tostring() converts a date to a string. signature global string tostring() return value type: string basenotification class abstract class for storing notification information sent from payment gateways. namespace commercepayments usage an abstract class that contains the common fields from payment gateways. basenotification can’t be instantiated on its own. the constructor of this class takes no arguments. for example: commercepayments.basenotification bnt = new commercepayments.basenotification(); 298apex reference guide basenotification class example commercepayments.basenotification notification = null; if ('capture'.equals(eventcode)) { notification = new commercepayments.capturenotification(); } else if ('refund'.equals(eventcode)) { notification = new commercepayments.referencedrefundnotification(); } in this section: basenotification methods basenotification methods the following are methods for basenotification. in this section: setamount(amount) sets the transaction amount. must be a non-negative value. setgatewaydate(gatewaydate) sets the date that the notification occurred. some gateways don’t send this value. setgatewaymessage(gatewaymessage) sets error messages that the gateway returned for the notification request. maximum length of 255 characters. setgatewayreferencedetails(gatewayreferencedetails) sets the payment gateway’s reference details. setgatewayreferencenumber(gatewayreferencenumber) sets the payment gateway’s reference number. setgatewayresultcode(gatewayresultcode) sets a gateway-specific result code. the code can be mapped to a salesforce-specific result code. maximum length of 64 characters. setgatewayresultcodedescription(gatewayresultcodedescription) sets a description of the |
gateway-specific result code that a payment gateway returned. maximum length of 1000 characters. setid(id) sets the id of the notification sent by the gateway. setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets the information about the salesforce-specific result code used to match a result code from a payment gateway. setstatus(status) sets the status of the notification sent by the gateway. setamount(amount) sets the transaction amount. must be a non-negative value. 299apex reference guide basenotification class signature global void setamount(double amount) parameters amount type: double the amount of the transaction. return value type: void setgatewaydate(gatewaydate) sets the date that the notification occurred. some gateways don’t send this value. signature global void setgatewaydate(datetime gatewaydate) parameters gatewaydate type: datetime the date that the notification occurred. return value type: void setgatewaymessage(gatewaymessage) sets error messages that the gateway returned for the notification request. maximum length of 255 characters. signature global void setgatewaymessage(string gatewaymessage) parameters gatewaymessage type: string the message that the gateway returned with the notification request. contains additional information about the notification. return value type: void 300apex reference guide basenotification class setgatewayreferencedetails(gatewayreferencedetails) sets the payment gateway’s reference details. signature global void setgatewayreferencedetails(string gatewayreferencedetails) parameters gatewayreferencedetails type: string provides information about the gateway communication. return value type: void setgatewayreferencenumber(gatewayreferencenumber) sets the payment gateway’s reference number. signature global void setgatewayreferencenumber(string gatewayreferencenumber) parameters gatewayreferencenumber type: string unique transaction id created by the payment gateway. return value type: void setgatewayresultcode(gatewayresultcode) sets a gateway-specific result code. the code can be mapped to a salesforce-specific result code. maximum length of 64 characters. signature global void setgatewayresultcode(string gatewayresultcode) parameters gatewayresultcode type: string gateway-specific result code. must be used to map a salesforce-specific result code. 301apex reference guide basenotification class return value type: void setgatewayresultcodedescription(gatewayresultcodedescription) sets a description of the gateway-specific result code that a payment gateway returned. maximum length of 1000 characters. signature global void setgatewayresultcodedescription(string gatewayresultcodedescription) parameters gatewayresultcodedescription type: string provides additional information about the result code and why the gateway returned the code. descriptions vary between different gateways. return value type: void setid(id) sets the id of the notification sent by the gateway. signature global void setid(string id) parameters id type: string return value type: void setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets the information about the salesforce-specific result code used to match a result code from a payment gateway. signature global void setsalesforceresultcodeinfo(commercepayments.salesforceresultcodeinfo salesforceresultcodeinfo) 302apex reference guide basepaymentmethodrequest class parameters salesforceresultcodeinfo type: commercepayments.salesforceresultcodeinfo on page 380 payment gateways have many response codes for payment calls. salesforce uses the result code information to map payment gateway codes to a predefined set of standard salesforce result codes. return value type: void setstatus(status) sets the status of the notification sent by the gateway. signature global void setstatus(commercepayments.notificationstatus status) parameters status type: commercepayments.notificationstatus on page 333 shows whether the payments platform successfully received the notification from the gateway. return value type: void basepaymentmethodrequest class abstract class for storing information about payment methods. namespace commercepayments usage the basepaymentmethodrequest class contains fields common to cardpaymentmethodrequest on page 318 . in this section: basepaymentmethodrequest methods basepaymentmethodrequest methods the following are methods for basepaymentmethodrequest. 303 |
apex reference guide basepaymentmethodrequest class in this section: equals(obj) maintains the integrity of lists of type basepaymentmethodrequest by determining the equality of external objects in a list. this method is dynamic and based on the equals method in java. hashcode() maintains the integrity of lists of type basepaymentmethodrequest by determining the uniqueness of the external object records in a list. tostring() converts a date to a string. equals(obj) maintains the integrity of lists of type basepaymentmethodrequest by determining the equality of external objects in a list. this method is dynamic and based on the equals method in java. signature global boolean equals(object obj) parameters obj type: object external object whose key is to be validated. return value type: boolean hashcode() maintains the integrity of lists of type basepaymentmethodrequest by determining the uniqueness of the external object records in a list. signature global integer hashcode() return value type: integer tostring() converts a date to a string. signature global string tostring() 304apex reference guide baserequest class return value type: string baserequest class baserequest is extended by all the request classes. namespace commercepayments in this section: baserequest methods baserequest methods the following are methods for baserequest. in this section: baserequest(additionaldata, idempotencykey) used for testing. baserequest(additionaldata, idempotencykey) used for testing. signature global void baserequest(string additionaldata, map<string, string> idempotencykey) parameters additionaldata type: string contains additional data that may be required for a payment request. the additionaldata object consists of key-value pairs. you can retrieve the additionaldata object from the request object: map<string, string> additionaldata=request.additionaldata idempotencykey type: map<string, string> unique value that's generated by a client and sent to the server in the request. the server stores the value and uses the it to keep track of the request status. return value type: void 305apex reference guide capturenotification class capturenotification class when a payment gateway sends a notification for a capture transaction, the payment gateway adapter creates the capturenotification object to store information about the notification. namespace commercepayments usage capturenotification is used in asynchronous payment gateway adapters. specify the commercepayments namespace when creating an instance of this class. the constructor of this class takes no arguments. for example: commercepayments.capturenotification crn = new commercepayments.capturenotification(); example commercepayments.basenotification notification = null; if ('capture'.equals(eventcode)) { notification = new commercepayments.capturenotification(); } else if ('refund'.equals(eventcode)) { notification = new commercepayments.referencedrefundnotification(); } in this section: capturenotification methods capturenotification methods the following are methods for capturenotification. in this section: setamount(amount) sets the transaction amount. must be a non-negative value. setgatewaydate(gatewaydate) sets the date that the transaction occurred. some gateways don’t send this value. setgatewaymessage(gatewaymessage) sets error messages that the gateway returned for the payment request. maximum length of 255 characters. setgatewayreferencedetails(gatewayreferencedetails) sets additional data that you can use for subsequent transactions. you can use any data that isn’t normalized in financial entities. this field has a maximum length of 1000 characters and can store data as json or xml. setgatewayreferencenumber(gatewayreferencenumber) sets the unique gateway reference number for the transaction that the gateway returned. maximum length of 255 characters. 306apex reference guide capturenotification class setgatewayresultcode(gatewayresultcode) sets a gateway-specific result code. the code can be mapped to a salesforce-specific result code. maximum length of 64 characters. setgatewayresultcodedescription(gatewayresultcodedescription) sets a description of the gateway-specific result code that a gateway returned. maximum length of 1000 characters. setid(id) sets the id of a notification sent by the payment gateway. setsalesforceresultcodeinfo(s |
alesforceresultcodeinfo) sets the salesforce-specific result code information. payment gateways have many response codes for payment calls. salesforce uses the result code information to map payment gateway codes to a predefined set of standard salesforce result codes. setstatus(status) sets the notification status to the same value that was sent by the gateway. setamount(amount) sets the transaction amount. must be a non-negative value. signature global void setamount(double amount) parameters amount type: double the amount to be debited or captured. return value type: void setgatewaydate(gatewaydate) sets the date that the transaction occurred. some gateways don’t send this value. signature global void setgatewaydate(datetime gatewaydate) parameters gatewaydate type: datetime date and time of the gateway communication. return value type: void 307apex reference guide capturenotification class setgatewaymessage(gatewaymessage) sets error messages that the gateway returned for the payment request. maximum length of 255 characters. signature global void setgatewaymessage(string gatewaymessage) parameters gatewaymessage type: string information on error messages sent from the gateway. return value type: void setgatewayreferencedetails(gatewayreferencedetails) sets additional data that you can use for subsequent transactions. you can use any data that isn’t normalized in financial entities. this field has a maximum length of 1000 characters and can store data as json or xml. signature global void setgatewayreferencedetails(string gatewayreferencedetails) parameters gatewayreferencedetails type: string return value type: void setgatewayreferencenumber(gatewayreferencenumber) sets the unique gateway reference number for the transaction that the gateway returned. maximum length of 255 characters. signature global void setgatewayreferencenumber(string gatewayreferencenumber) parameters gatewayreferencenumber type: string unique transaction id created by the payment gateway. 308apex reference guide capturenotification class return value type: void setgatewayresultcode(gatewayresultcode) sets a gateway-specific result code. the code can be mapped to a salesforce-specific result code. maximum length of 64 characters. signature global void setgatewayresultcode(string gatewayresultcode) parameters gatewayresultcode type: string gateway-specific result code. map this value to a salesforce-specific result code. return value type: void setgatewayresultcodedescription(gatewayresultcodedescription) sets a description of the gateway-specific result code that a gateway returned. maximum length of 1000 characters. signature global void setgatewayresultcodedescription(string gatewayresultcodedescription) parameters gatewayresultcodedescription type: string description of the gateway’s result code. use this field to learn more about why the gateway returned a certain result code. return value type: void setid(id) sets the id of a notification sent by the payment gateway. signature global void setid(string id) 309apex reference guide capturenotification class parameters id type: string return value type: void setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets the salesforce-specific result code information. payment gateways have many response codes for payment calls. salesforce uses the result code information to map payment gateway codes to a predefined set of standard salesforce result codes. signature global void setsalesforceresultcodeinfo(commercepayments.salesforceresultcodeinfo salesforceresultcodeinfo) parameters salesforceresultcodeinfo type: commercepayments.salesforceresultcodeinfo on page 380 description of the salesforce result code value. return value type: void setstatus(status) sets the notification status to the same value that was sent by the gateway. signature global void setstatus(commercepayments.notificationstatus status) parameters status type: notificationstatus on page 333 sets the salesforce-specific result code information. payment gateways have many response codes for payment calls. salesforce uses the result code information to map payment gateway codes to a predefined set of standard salesforce result codes. return value type: void 310apex reference guide capturerequest class capturerequest class represents a capture request. this class extends the baserequest class and inherits all its methods. namespace commercepayments on page 256 usage the capturerequest class� |
�s buildcapturerequest method creates a capturerequest object to store payment information, such as value and currency, as json strings. example builds a capturerequest object for a multicurrency org. private string buildcapturerequest(commercepayments.capturerequest capturerequest) { boolean is_multicurrency_org = userinfo.ismulticurrencyorganization(); queryutils qbuilderforauth = new queryutils(paymentauthorization.sobjecttype); // add required fields qbuilderforauth.getselectclause().addfield('gatewayrefnumber', false); if (is_multicurrency_org) { // addfield also takes a boolean to enable translation (uses label instead of actual value) qbuilderforauth.getselectclause().addfield('currencyisocode', false); } in this section: capturerequest constructors capturerequest properties capturerequest constructors the following are constructors for capturerequest. in this section: capturerequest(amount, authorizationid) this constructor is intended for test usage and throws an exception if used outside of the apex test context. capturerequest(amount, authorizationid) this constructor is intended for test usage and throws an exception if used outside of the apex test context. parameters amount type: double 311apex reference guide captureresponse class the amount to be debited or captured. authorizationid type: string represents a payment authorization record. capturerequest properties the following are properties for capturerequest. in this section: accountid account id value. references an account record. amount amount of currency that needs to be captured. paymentauthorizationid id value that references a paymentauthorization. accountid account id value. references an account record. property value type: string amount amount of currency that needs to be captured. property value type: double paymentauthorizationid id value that references a paymentauthorization. property value type: string captureresponse class the payment gateway adapter sends this response for the capture request type. this class extends abstractresponse and inherits its methods. 312apex reference guide captureresponse class namespace commercepayments on page 256 usage you must specify the commercepayments namespace when creating an instance of this class. the constructor of this class takes no arguments. for example: commercepayments.capture response ctr = new commercepayments.captureresponse(); in this section: captureresponse methods captureresponse methods the following are methods for captureresponse. in this section: setamount(amount) sets the transaction amount. setasync(async) indicates whether the payment gateway adapter used in the payment capture was asynchronous (true) or synchronous (false). setgatewayavscode(gatewayavscode) sets the payment gateway’s avs (address verification system) code. setgatewaydate(gatewaydate) sets the payment gateway’s date. setgatewaymessage(gatewaymessage) sets information or messages that the gateway returned. setgatewayreferencedetails(gatewayreferencedetails) sets the payment gateway’s reference details. setgatewayreferencenumber(gatewayreferencenumber) sets the payment gateway’s reference number. setgatewayresultcode(gatewayresultcode) sets the payment gateway’s result code. setgatewayresultcodedescription(gatewayresultcodedescription) sets the payment gateway’s result code description. setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets salesforce result code information. setamount(amount) sets the transaction amount. 313apex reference guide captureresponse class signature global void setamount(double amount) parameters amount type: double the amount to be debited or captured. return value type: void setasync(async) indicates whether the payment gateway adapter used in the payment capture was asynchronous (true) or synchronous (false). signature global void setasync(boolean async) parameters async type: boolean return value type: void setgatewayavscode(gatewayavscode) sets the payment gateway’s avs (address verification system) code. signature global void setgatewayavscode(string gatewayavscode) parameters gatewayavscode type: string payment gateways that use an avs system return this code. return value type: void 314apex reference guide |
captureresponse class setgatewaydate(gatewaydate) sets the payment gateway’s date. signature global void setgatewaydate(datetime gatewaydate) parameters gatewaydate type: datetime the date that communication happened with the gateway. return value type: void setgatewaymessage(gatewaymessage) sets information or messages that the gateway returned. signature global void setgatewaymessage(string gatewaymessage) parameters gatewaymessage type: string information or error messages returned by the gateway. return value type: void setgatewayreferencedetails(gatewayreferencedetails) sets the payment gateway’s reference details. signature global void setgatewayreferencedetails(string gatewayreferencedetails) parameters gatewayreferencedetails type: string provides information about the gateway communication. 315apex reference guide captureresponse class return value type: void setgatewayreferencenumber(gatewayreferencenumber) sets the payment gateway’s reference number. signature global void setgatewayreferencenumber(string gatewayreferencenumber) parameters gatewayreferencenumber type: string unique transaction id created by the payment gateway. return value type: void setgatewayresultcode(gatewayresultcode) sets the payment gateway’s result code. signature global void setgatewayresultcode(string gatewayresultcode) parameters gatewayresultcode type: string the gateway result code. you must map this to a salesforce result code. return value type: void setgatewayresultcodedescription(gatewayresultcodedescription) sets the payment gateway’s result code description. signature global void setgatewayresultcodedescription(string gatewayresultcodedescription) 316apex reference guide cardcategory enum parameters gatewayresultcodedescription type: string description of the gatewayresultcode. provides additional context about the result code that the gateway returned. return value type: void setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets salesforce result code information. signature global void setsalesforceresultcodeinfo(commercepayments.salesforceresultcodeinfo salesforceresultcodeinfo) parameters salesforceresultcodeinfo salesforceresultcodeinfotype: commercepayments.salesforceresultcodeinfo description of the salesforce result code value. return value type: void cardcategory enum defines whether the payment method represents a credit card or a debit card. namespace commercepayments on page 256 enum values the following are the values of the commercepayments.cardcategory enum. value description creditcard shows that the payment method is a credit card. debitcard shows that the payment method is a debit card. 317apex reference guide cardpaymentmethodrequest class cardpaymentmethodrequest class sends data related to a card payment method to a gateway adapter during a service call. namespace commercepayments on page 256 usage this class contains details about the card used as a payment method for authorization, sale, or tokenization transaction requests. the gateway adapter reads the fields of this class object while constructing a transaction json request to send to the payment gateway. the object of this class is available as the cardpaymentmethod field in the saleapipaymentmethodrequest class, authapipaymentmethodrequest class, and paymentmethodtokenizationrequest class. example: this code sample retrieves the cardpaymentmethodrequest object from the paymentmethod class. commercepayments.cardpaymentmethodrequest cardpaymentmethod = paymentmethod.cardpaymentmethod; in this section: cardpaymentmethodrequest constructors cardpaymentmethodrequest properties cardpaymentmethodrequest methods cardpaymentmethodrequest constructors the following are constructors for cardpaymentmethodrequest. in this section: cardpaymentmethodrequest(cardcategory) sets the cardcategory value for the card payment method request. cardpaymentmethodrequest(cardcategory) sets the cardcategory value for the card payment method request. signature global cardpaymentmethodrequest(commercepayments.cardcategory cardcategory) parameters cardcategory type: cardcategory on page 317 defines whether the card payment method is a credit card or a debit card. 318apex reference guide cardpaymentmethodrequest class cardpaymentmethodrequest properties the following are properties for cardpaymentmethodrequest. in this section: accountid customer account for this payment method. autopay indicates whether a token is being requested |
so that the payment method can be used for recurring payments. cardcategory indicates whether a card payment method is for a credit card or debit card. cardholderfirstname the first name of the cardholder for the card payment method. cardholderlastname the last name of the cardholder for the card payment method. cardholdername full name of the cardholder on the card payment method. cardnumber system-defined unique id for the card payment method. cardtype defines the credit card bank. possible values are americanexpress, dinersclub, jcb, maestro, mastercard, andvisa. cvv the card security code for the credit or debit card on a card payment method. email email address of the cardholder for the credit or debit card on a card payment method. expirymonth expiration month for the credit or debit card on a card payment method. expiryyear expiration year of the credit or debit card for the card payment method. inputcardtype input field for the card type. this field doesn’t store the card type directly, but instead populates cardbin, lastfour, and displaycardnumber based on the value entered in inputcardtype. startmonth the credit or debit card becomes valid on the first day of the startmonth in the startyear startyear year during which the credit or debit card becomes valid. accountid customer account for this payment method. 319apex reference guide cardpaymentmethodrequest class signature global string accountid {get; set;} property value type: string autopay indicates whether a token is being requested so that the payment method can be used for recurring payments. signature global boolean autopay {get; set;} property value type: boolean cardcategory indicates whether a card payment method is for a credit card or debit card. signature global commercepayments.cardcategory cardcategory {get; set;} property value type: cardcategory on page 317 cardholderfirstname the first name of the cardholder for the card payment method. signature global string cardholderfirstname {get; set;} property value type: string cardholderlastname the last name of the cardholder for the card payment method. signature global string cardholderlastname {get; set;} 320apex reference guide cardpaymentmethodrequest class property value type: string cardholdername full name of the cardholder on the card payment method. signature global string cardholdername {get; set;} property value type: string cardnumber system-defined unique id for the card payment method. signature global string cardnumber {get; set;} property value type: string cardtype defines the credit card bank. possible values are americanexpress, dinersclub, jcb, maestro, mastercard, andvisa. signature global commercepayments.cardtype cardtype {get; set;} property value type: cardtype cvv the card security code for the credit or debit card on a card payment method. signature global string cvv {get; set;} property value type: string 321apex reference guide cardpaymentmethodrequest class email email address of the cardholder for the credit or debit card on a card payment method. signature global string email {get; set;} property value type: string expirymonth expiration month for the credit or debit card on a card payment method. signature global integer expirymonth {get; set;} property value type: integer expiryyear expiration year of the credit or debit card for the card payment method. signature global integer expiryyear {get; set;} property value type: integer inputcardtype input field for the card type. this field doesn’t store the card type directly, but instead populates cardbin, lastfour, and displaycardnumber based on the value entered in inputcardtype. signature global string inputcardtype {get; set;} property value type: string 322apex reference guide cardpaymentmethodrequest class startmonth the credit or debit card becomes valid on the first day of the startmonth in the startyear signature global integer startmonth {get; set;} property value type: integer startyear year during which the credit or debit card becomes valid. signature global integer startyear {get; set;} property value type: integer cardpaymentmethodrequest methods |
the following are methods for cardpaymentmethodrequest. in this section: equals(obj) maintains the integrity of lists of type cardpaymentmethodrequest by determining the equality of external objects in a list. this method is dynamic and based on the equals method in java. hashcode() maintains the integrity of lists of type cardpaymentmethodrequest. tostring() converts a date to a string. equals(obj) maintains the integrity of lists of type cardpaymentmethodrequest by determining the equality of external objects in a list. this method is dynamic and based on the equals method in java. signature global boolean equals(object obj) 323apex reference guide custommetadatatypeinfo class parameters obj type: object external object whose key is to be validated. return value type: boolean hashcode() maintains the integrity of lists of type cardpaymentmethodrequest. signature global integer hashcode() return value type: integer tostring() converts a date to a string. signature global string tostring() return value type: string custommetadatatypeinfo class access information about custom metadata. the paymentgatewayadapter can send custommetadatatypeinfo to transaction requests through the response object’s salesforceresultcodeinfo. namespace commercepayments on page 256 in this section: custommetadatatypeinfo constructors custommetadatatypeinfo methods 324apex reference guide gatewayerrorresponse class custommetadatatypeinfo constructors the following are constructors for custommetadatatypeinfo. in this section: custommetadatatypeinfo(cmtrecordid, cmtsfresultcodefieldname) constructor for providing custom metadata type information. custommetadatatypeinfo(cmtrecordid, cmtsfresultcodefieldname) constructor for providing custom metadata type information. signature global custommetadatatypeinfo(string cmtrecordid, string cmtsfresultcodefieldname) parameters cmtrecordid type: string id of the matchedcustom metadata type record cmtsfresultcodefieldname type: string field that contains the salesforce result code values. belongs to the custom metadata type. custommetadatatypeinfo methods the following are methods for custommetadatatypeinfo. gatewayerrorresponse class use to respond with an error indication following errors from the paymentgateway adapter, such as request-forbidden responses, custom validation errors, or expired api tokens. namespace commercepayments on page 256 usage use gatewayerrorresponse to create an object that stores information about error responses sent by the payment gateway adapter. 325apex reference guide gatewayerrorresponse class example if gatewayresponse receives an exception rather than a valid request, it calls gatewayerrorresponse to create an error object with information about the exception. global commercepayments.gatewayresponse processrequest(commercepayments.paymentgatewaycontext gatewaycontext) { commercepayments.requesttype requesttype = gatewaycontext.getpaymentrequesttype(); commercepayments.gatewayresponse response; try { if (requesttype == commercepayments.requesttype.authorize) { response = createauthresponse((commercepayments.authorizationrequest)gatewaycontext.getpaymentrequest()); } else if (requesttype == commercepayments.requesttype.capture) { response = createcaptureresponse((commercepayments.capturerequest)gatewaycontext.getpaymentrequest()) ; } else if (requesttype == commercepayments.requesttype.referencedrefund) { response = createrefundresponse((commercepayments.referencedrefundrequest)gatewaycontext.getpaymentrequest()); } return response; } catch(salesforcevalidationexception e) { commercepayments.gatewayerrorresponse error = new commercepayments.gatewayerrorresponse('400', e.getmessage()); return error; } } in this section: gatewayerrorresponse constructors gatewayerrorresponse constructors the following are constructors for gatewayerrorresponse. in this section: gatewayerrorresponse(errorcode, errormessage) constructor to create a gatewayerrorresponse object that accepts errorcode and errormessage. gatewayerrorresponse(errorcode, errormessage) constructor to create a gatewayerrorresponse object that accepts errorcode and errormessage. signature global gatewayerrorresponse(string errorcode, string errormessage) 326apex reference guide gatewaynotificationresponse class parameters errorcode type |
: string should match with the http status code to be returned to the user. here are a few examples. • if the status code is for a bad request, the errorcode should be 400. • if the status code is for a forbidden request, errorcode should be 403. • if errorcode isn’t a valid http status code, a 500 internal server error is returned. note: errorcode must have a value, otherwise the platform throws an error. errormessage type: string the message response to users following an error. note: errormessage must have a value, otherwise the platform throws an error. gatewaynotificationresponse class when the payment gateway sends a notification to the payments platform, the platform responds with a gatewaynotificationresponse indicating whether the platform succeeded or failed at receiving the notification. namespace commercepayments on page 256 usage you must specify the commercepayments namespace when creating an instance of this class. the constructor of this class takes no arguments. for example: commercepayments.gatewaynotificationresponse gnr = new commercepayments.gatewaynotificationresponse(); when an asynchronous payment gateway sends a notification, the gateway requires the platform to acknowledge that it has either succeeded or failed in receiving the notification. payment gateway adapters use this class to construct the acknowledgment response, which gateways expect for a notification. gatewaynotificationresponse is the return type of the processnotification method. example commercepayments.gatewaynotificationresponse gnr = new commercepayments.gatewaynotificationresponse(); if (saveresult.issuccess()) { system.debug('notification accepted by platform'); } else { system.debug('errors in the result '+ blob.valueof(saveresult.geterrormessage())); } gnr.setstatuscode(200); 327apex reference guide gatewaynotificationresponse class gnr.setresponsebody(blob.valueof('[accepted]')); return gnr; in this section: gatewaynotificationresponse methods gatewaynotificationresponse methods the following are methods for gatewaynotificationresponse. in this section: setresponsebody(responsebody) sets the body of the response to the gateway. some gateways expect the payments platform to acknowledge the notification with a response regardless of whether the notification was accepted. setstatuscode(statuscode) sets the http status code sent to the gateway as part of the payments platform’s response notification. setresponsebody(responsebody) sets the body of the response to the gateway. some gateways expect the payments platform to acknowledge the notification with a response regardless of whether the notification was accepted. signature global void setresponsebody(blob responsebody) parameters responsebody type: blob common response values include accepted for successfully receiving the response. for example: commercepayments.gatewaynotificationresponse gnr = new commercepayments.gatewaynotificationresponse(); if (saveresult.issuccess()) { system.debug('notification accepted by platform'); } else { system.debug('errors in the result '+ blob.valueof(saveresult.geterrormessage())); } gnr.setstatuscode(200); gnr.setresponsebody(blob.valueof('[accepted]')); return gnr; return value type: void 328apex reference guide gatewayresponse interface setstatuscode(statuscode) sets the http status code sent to the gateway as part of the payments platform’s response notification. signature global void setstatuscode(integer statuscode) parameters statuscode type: integer the status code will vary based on the type of payments platform response. users should configure their gatewaynotificationresponse class to account for all values that their payments platform can possibly return. for example: commercepayments.gatewaynotificationresponse gnr = new commercepayments.gatewaynotificationresponse(); if (saveresult.issuccess()) { system.debug('notification accepted by platform'); } else { system.debug('errors in the result '+ blob.valueof(saveresult.geterrormessage())); } gnr.setstatuscode(200); gnr.setresponsebody(blob.valueof('[accepted]')); return gnr; return value type: void gatewayresponse interface generic payment gateway response interface. this class extends the captureresponse on page 312, abstracttransactionresponse on page 268, and abstractresponse on page 259 classes and inherits all their properties. it |
has no unique methods or parameters. namespace commercepayments on page 256 in this section: gatewayresponse example implementation gatewayresponse example implementation this is an example implementation of the commercepayments.gatewayresponse interface. /** * abstract function to build gateway response for a transaction 329apex reference guide notificationclient class * the input is the response from gateway * it creates and returns gatewayresponse from the httpresponse */ public abstract commercepayments.gatewayresponse buildresponse(httpresponse response); /** * function to process transaction requests * steps involved are: * 1. build httprequest with the input request from gateway context * 2. send request and get the response from gateway * 3. parse the response from gateway and return gatewayresponse */ public commercepayments.gatewayresponse execute(){ httprequest req; try{ //building a new request req = buildrequest(); } catch(payeezevalidationexception e) { return getvalidationexceptionerror(e); } commercepayments.paymentshttp http = new commercepayments.paymentshttp(); httpresponse res = null; try{ //sending the request res = http.send(req); } catch(calloutexception ce) { return getcalloutexceptionerror(ce); } try{ //parsing the response from gateway return buildresponse(res); } catch(exception e) { return getparseexceptionerror(e); } } for additional context, review the complete sample gateway adapter in the commercepayments gateway reference implementation. notificationclient class communicates with the payment platform regarding the gateway’s notification. namespace commercepayments on page 256 usage specify the commercepayments namespace when creating an instance of this class. the constructor of this class takes no arguments. for example: commercepayments.notificationclient ntc = new commercepayments.notificationclient(); 330apex reference guide notificationsaveresult class this class is used in asynchronous payment gateway adapters. the notification client contains api for communicating with the payments platform regarding the gateway’s notification. when the gateway sends a notification, the gateway adapter invokes the record method in notificationclient to request that the platform updates notification details. example the notificationsaveresult class creates a saveresult object to store the result of the save request made to the payment gateway. commercepayments.notificationsaveresult saveresult = commercepayments.notificationclient.record(notification); in this section: notificationclient methods notificationclient methods the following are methods for notificationclient. in this section: record(notification) stores the results of a notification request. record(notification) stores the results of a notification request. signature global static commercepayments.notificationsaveresult record(commercepayments.basenotification notification) parameters notification type: basenotification on page 298 return value type: notificationsaveresult on page 331 notificationsaveresult class contains the result of the payment platform’s attempt to record data from the gateway’s notification. namespace commercepayments on page 256 331apex reference guide notificationsaveresult class usage this class is used with asynchronous payments. it is the return type of the notificiationclient.record operation and contains the result of the payment platform’s attempt to save notification details. the constructor of this class takes no arguments. for example: commercepayments.notificationsaveresult nsr = new commercepayments.notificationsaveresult(); example commercepayments.notificationsaveresult saveresult = commercepayments.notificationclient.record(notification); in this section: notificationsaveresult methods notificationsaveresult methods the following are methods for notificationsaveresult. in this section: geterrormessage() gets the error message, if any, from the payment platform regarding its attempt to save the notification sent from the payment gateway. getstatuscode() gets the status code from the payment platform’s attempt to save the notification sent from the payment gateway. issuccess() gets the status of whether the payment platform successfully saved the notification sent from the payment gateway. geterrormessage() gets the error message, if any, from the payment platform regarding its attempt to save the notification sent from the payment gateway. signature global string geterrormessage() return value type: string getstatuscode() gets the status code from the payment platform’s attempt to save the notification sent from |
the payment gateway. 332 |
apex reference guide notificationstatus enum signature global integer getstatuscode() return value type: integer issuccess() gets the status of whether the payment platform successfully saved the notification sent from the payment gateway. signature global boolean issuccess() return value type: boolean notificationstatus enum shows whether the payments platform successfully received the notification from the gateway. usage when the gateway sends a notification for a payment request, the payments platform delegates the notification request to the gateway adapter. first, the adapter evaluates the signature from the notification request. if the signature is valid, the adapter builds a notification object to store information about the notification. during this process, the adapter sets the notificationstatus to failed or success based on information from the notification request. enum values the following are the values of the commercepayments.notificationstatus enum. value description failed the payments platform couldn’t receive the notification due to an error. success the payments platform received the notification. paymentgatewayadapter interface paymentgatewayadapters can implement this interface in order to process requests. namespace commercepayments on page 256 333apex reference guide paymentgatewayasyncadapter interface in this section: paymentgatewayadapter methods paymentgatewayadapter methods the following are methods for paymentgatewayadapter. in this section: processrequest(var1) the entry point for processing payment requests. returns the response from the payment gateway. processrequest(var1) the entry point for processing payment requests. returns the response from the payment gateway. signature global commercepayments.gatewayresponse processrequest(commercepayments.paymentgatewaycontext var1) parameters var1 type: commercepayments.paymentgatewaycontext you can retrieve the request type and the request from the context object. return value type: commercepayments.gatewayresponse the response from the payment gateway. paymentgatewayasyncadapter interface implement the interface to allow customers to process payments asynchronously. namespace commercepayments on page 256 usage implementing an asynchronous adapter also requires the processnotification method from the gatewaynotificationresponse on page 327 class. 334apex reference guide paymentgatewayasyncadapter interface example global with sharing class sampleasyncadapter implements commercepayments.paymentgatewayasyncadapter, commercepayments.paymentgatewayadapter { global sampleasyncadapter() {} global commercepayments.gatewayresponse processrequest(commercepayments.paymentgatewaycontext gatewaycontext) { } global commercepayments.gatewaynotificationresponse processnotification(commercepayments.paymentgatewaynotificationcontext gatewaynotificationcontext) { } } in this section: paymentgatewayasyncadapter methods paymentgatewayasyncadapter example implementation paymentgatewayasyncadapter methods the following are methods for paymentgatewayasyncadapter. in this section: processnotification(paymentgatewaynotificationcontext) entry point for processing notifications from payment gateways. processnotification(paymentgatewaynotificationcontext) entry point for processing notifications from payment gateways. signature global commercepayments.gatewaynotificationresponse processnotification(commercepayments.paymentgatewaynotificationcontext var1) parameters paymentgatewaynotificationcontext type: paymentgatewaynotificationcontext on page 339 the paymentgatewaynotificationcontext object wraps all the information related to a gateway notification. return value type: gatewaynotificationresponse on page 327 when the payment gateway sends a notification to the payments platform, the platform responds with a gatewaynotificationresponse indicating whether the platform succeeded or failed at receiving the notification. 335apex reference guide paymentgatewayasyncadapter interface paymentgatewayasyncadapter example implementation this is a sample implementation of the commercepayments.paymentgatewayasyncadapter interface. global with sharing class adyenadapter implements commercepayments.paymentgatewayasyncadapter, commercepayments.paymentgatewayadapter { global adyenadapter() {} global commercepayments.gatewayresponse processrequest(commercepayments.paymentgatewaycontext gatewaycontext) { } global commercepayments.gatewaynotificationresponse processnotification(commercepayments.paymentgatewaynotificationcontext gatewaynotificationcontext) { } } commercepayments.requesttype requesttype = gatewaycontext.getpaymentrequesttype(); if (requesttype == commercepayments.requesttype.capture) { req.setendpoint('/pal/servlet/payment/v52 |
/capture'); // refer to the end of this doc for sample buildcapturerequest implementation body = buildcapturerequest((commercepayments.capturerequest)gatewaycontext.getpaymentrequest()); } else if (requesttype == commercepayments.requesttype.referencedrefund) { req.setendpoint('/pal/servlet/payment/v52/refund'); body = buildrefundrequest((commercepayments.referencedrefundrequest)gatewaycontext.getpaymentrequest()); } req.setbody(body); req.setmethod('post'); commercepayments.paymentshttp http = new commercepayments.paymentshttp(); httpresponse res = null; try { res = http.send(req); } catch(calloutexception ce) { commercepayments.gatewayerrorresponse error = new commercepayments.gatewayerrorresponse('500', ce.getmessage()); return error; } if ( requesttype == commercepayments.requesttype.capture) { // refer to the end of this doc for sample createcaptureresponse implementation response = createcaptureresponse(res); } else if ( requesttype == commercepayments.requesttype.referencedrefund) { response = createrefundresponse(res); } return response; commercepayments.paymentgatewaynotificationrequest notificationrequest = gatewaynotificationcontext.getpaymentgatewaynotificationrequest(); blob request = notificationrequest.getrequestbody(); map<string, object> jsonreq = (map<string, object>)json.deserializeuntyped(request.tostring()); 336apex reference guide paymentgatewaycontext class list<object> notificationitems = (list<object>)jsonreq.get('notificationitems'); map<string, object> notificationrequestitem = (map<string, object>)((map<string, object>)notificationitems[0]).get('notificationrequestitem'); boolean success = boolean.valueof(notificationrequestitem.get('success')); string pspreference = (string)notificationrequestitem.get('pspreference'); string eventcode = (string)notificationrequestitem.get('eventcode'); double amount = (double)((map<string, object>)notificationrequestitem.get('amount')).get('value'); commercepayments.notificationstatus notificationstatus = null; if (success) { notificationstatus = commercepayments.notificationstatus.success; } else { notificationstatus = commercepayments.notificationstatus.failed; } commercepayments.basenotification notification = null; if ('capture'.equals(eventcode)) { notification = new commercepayments.capturenotification(); } else if ('refund'.equals(eventcode)) { notification = new commercepayments.referencedrefundnotification(); } notification.setstatus(notificationstatus); notification.setgatewayreferencenumber(pspreference); notification.setamount(amount); commercepayments.notificationsaveresult saveresult = commercepayments.notificationclient.record(notification); commercepayments.gatewaynotificationresponse gnr = new commercepayments.gatewaynotificationresponse(); if (saveresult.issuccess()) { system.debug('notification accepted by platform'); } else { system.debug('errors in the result '+ blob.valueof(saveresult.geterrormessage())); } gnr.setstatuscode(200); gnr.setresponsebody(blob.valueof('[accepted]')); return gnr; paymentgatewaycontext class wraps the information related to a payment request. namespace commercepayments on page 256 usage the constructor of this class takes no arguments. for example: 337apex reference guide paymentgatewaycontext class commercepayments.paymentgatewaycontext pgc = new commercepayments.paymentgatewaycontext(); example global commercepayments.gatewayresponse processrequest(commercepayments.paymentgatewaycontext gatewaycontext) { commercepayments.requesttype requesttype = gatewaycontext.getpaymentrequesttype(); if (requesttype == commercepayments.requesttype.capture) { commercepayments.capturerequest capturerequest = (commercepayments.capturerequest) gatewaycontext.getpaymentrequest(); } } in this section: paymentgatewaycontext constructors |
paymentgatewaycontext methods paymentgatewaycontext constructors the following are constructors for paymentgatewaycontext. in this section: paymentgatewaycontext(request, requesttype) constructor to enable instance creation. this constructor is intended for test usage and throws an exception if used outside of the apex test context. paymentgatewaycontext(request, requesttype) constructor to enable instance creation. this constructor is intended for test usage and throws an exception if used outside of the apex test context. signature global paymentgatewaycontext(commercepayments.paymentgatewayrequest request, string requesttype) parameters request type: commercepayments.paymentgatewayrequest raw payload. sensitive attributes are masked to ensure pci compliance. requesttype type: string defines the type of request made to the gateway 338apex reference guide paymentgatewaynotificationcontext class paymentgatewaycontext methods the following are methods for paymentgatewaycontext. in this section: getpaymentrequest() returns the payment request object. getpaymentrequesttype() returns the payment request type. getpaymentrequest() returns the payment request object. signature global commercepayments.paymentgatewayrequest getpaymentrequest() return value type: paymentgatewayrequest getpaymentrequesttype() returns the payment request type. signature global string getpaymentrequesttype() return value type: string paymentgatewaynotificationcontext class wraps the information related to a gateway notification. namespace commercepayments on page 256 usage this class is used with asynchronous payments. it wraps all of the information related to a notification from the payment gateway. the payments platform provides its context to the payment gateway adapters. the constructor of this class takes no arguments. for example: 339apex reference guide paymentmethodtokenizationrequest class commercepayments.paymentgatewaynotificationcontext pgnc = new commercepayments.paymentgatewaynotificationcontext(); example global commercepayments.gatewaynotificationresponse processnotification(commercepayments.paymentgatewaynotificationcontext gatewaynotificationcontext) { commercepayments.paymentgatewaynotificationrequest notificationrequest = gatewaynotificationcontext.getpaymentgatewaynotificationrequest(); } in this section: paymentgatewaynotificationcontext methods paymentgatewaynotificationcontext methods the following are methods for paymentgatewaynotificationcontext. in this section: getpaymentgatewaynotificationrequest() returns the payment gateway’s notification request. getpaymentgatewaynotificationrequest() returns the payment gateway’s notification request. signature global commercepayments.paymentgatewaynotificationrequest getpaymentgatewaynotificationrequest() return value type: paymentgatewaynotificationrequest on page 351 paymentmethodtokenizationrequest class stores data about a request to tokenize a card payment method. the tokenization process occurs in the payment gateway. this process replaces sensitive customer data, such as a card number or cvv, with unique identification symbols. the symbols are used while the data is handled by salesforce, the payment gateway, and the customer bank, allowing salesforce to store the token without storing sensitive customer data. namespace commercepayments on page 256 340apex reference guide paymentmethodtokenizationrequest class usage the constructor of this class takes no arguments. for example: commercepayments.paymentmethodtokenizationrequest pmtr = new commercepayments.paymentmethodtokenizationrequest(); this class holds all the required details about the tokenize request. gateway adapters read the information in this class while constructing a tokenization json request, which is sent to the payment gateway. example the following code is used within your payment gateway adapter apex class. use the gatewayresponse class's processrequest method to build responses based on the request type that it receives from an instance of paymentgatewaycontext on page 337. if the request type is tokenize, gatewayresponse on page 329 calls the createtokenizeresponse method and passes an instance of the paymentmethodtokenizationrequest class. the passed paymentmethodtokenizationrequest object contains the address and cardpaymentmethod information that the payment gateway needs to manage the tokenization process. for example: global commercepayments.gatewayresponse processrequest(commercepayments.paymentgatewaycontext gatewaycontext) { commercepayments.requesttype requesttype = gatewaycontext.getpaymentrequesttype(); commercepayments.gatewayresponse response; try { if (request |
type == commercepayments.requesttype.tokenize) { response = createtokenizeresponse((commercepayments.paymentmethodtokenizationrequest)gatewaycontext.getpaymentrequest()); } //add other else if statements for different request types as needed. return response; } catch(salesforcevalidationexception e) { commercepayments.gatewayerrorresponse error = new commercepayments.gatewayerrorresponse('400', e.getmessage()); return error; } } configure the createtokenizeresponse method to accept an instance of paymentmethodtokenizationrequest. then, build an instance of paymentmethodtokenizationresponse based on the values received from the payment gateway. public commercepayments.gatewayresponse createtokenizeresponse(commercepayments.paymentmethodtokenizationrequest tokenizerequest) { commercepayments.paymentmethodtokenizationresponse tokenizeresponse = new commercepayments.paymentmethodtokenizationresponse(); tokenizeresponse.setgatewaytokenencrypted(encryptedvalue); tokenizeresponse.setgatewaytokendetails(tokendetails); tokenizeresponse.setgatewayavscode(avscode); 341apex reference guide paymentmethodtokenizationrequest class tokenizeresponse.setgatewaymessage(gatewaymessage); tokenizeresponse.setgatewayresultcode(resultcode); tokenizeresponse.setgatewayresultcodedescription(resultcodedescription); tokenizeresponse.setsalesforceresultcodeinfo(resultcodeinfo); tokenizeresponse.setgatewaydate(system.now()); return tokenizeresponse; } the tokenizeresponse contains the results of the gateway's tokenization process, and if successful, the tokenized value. in this section: paymentmethodtokenizationrequest constructors paymentmethodtokenizationrequest properties paymentmethodtokenizationrequest methods paymentmethodtokenizationrequest constructors the following are constructors for paymentmethodtokenizationrequest. in this section: paymentmethodtokenizationrequest(paymentgatewayid) payment gateway id constructor used with paymentmethodtokenizationrequest. this constructor is intended for test usage and throws an exception if used outside of the apex test context. paymentmethodtokenizationrequest() the following are constructors for paymentmethodtokenizationrequest. paymentmethodtokenizationrequest(paymentgatewayid) payment gateway id constructor used with paymentmethodtokenizationrequest. this constructor is intended for test usage and throws an exception if used outside of the apex test context. signature global paymentmethodtokenizationrequest(string paymentgatewayid) parameters paymentgatewayid type: string the payment method’s payment gateway id that will be tokenized. paymentmethodtokenizationrequest() the following are constructors for paymentmethodtokenizationrequest. 342apex reference guide paymentmethodtokenizationrequest class signature global paymentmethodtokenizationrequest() paymentmethodtokenizationrequest properties the following are properties for paymentmethodtokenizationrequest. in this section: address the card payment method address to be tokenized. cardpaymentmethod the card payment method containing data to be tokenized. address the card payment method address to be tokenized. signature global commercepayments.addressrequest address {get; set;} property value type: addressrequest on page 262 cardpaymentmethod the card payment method containing data to be tokenized. signature global commercepayments.cardpaymentmethodrequest cardpaymentmethod {get; set;} property value type: cardpaymentmethodrequest on page 318 paymentmethodtokenizationrequest methods the following are methods for paymentmethodtokenizationrequest. in this section: equals(obj) maintains the integrity of lists of type paymentmethodtokenizationrequest by determining the equality of external objects in a list. this method is dynamic and is based on the equals method in java. 343apex reference guide paymentmethodtokenizationrequest class hashcode() maintains the integrity of lists of type paymentmethodtokenizationrequest by determining the uniquness of the external object records in a list. tostring() converts a date to a string. equals(obj) maintains the integrity of lists of type paymentmethodtokenizationrequest by determining the equality of external objects in a list. this method is dynamic and is based on the equals method in java. signature global boolean equals(object obj) parameters obj type: object external object whose key is to be validated. return value type: boolean hashcode() maintains the integrity of lists of type paymentmethodtokenization |
request by determining the uniquness of the external object records in a list. signature global integer hashcode() return value type: integer tostring() converts a date to a string. signature global string tostring() return value type: string 344apex reference guide paymentmethodtokenizationresponse class paymentmethodtokenizationresponse class gateway response sent by payment gateway adapters for the payment method tokenization request. the response includes the payment method’s token id value. namespace commercepayments on page 256 usage the constructor of this class takes no arguments. for example: commercepayments.paymentmethodtokenizationresponse pmtr = new commercepayments.paymentmethodtokenizationresponse(); after the payment gateway processes a tokenization request, the fields of paymentmethodtokenizationresponse receive and store information from the gateway's response. the gateway's response shows whether the tokenization request was successful, the token value, and any additional messages or information about the tokenization process. you can then pass an instance of paymentmethodtokenizationresponse to an authorization response or a sale response. this class is mapped to a response class in the java layer. example this constructor builds a new instance of the paymentmethodtokenizationresponse class. commercepayments.paymentmethodtokenizationresponse tokenizeresponse = new commercepayments.paymentmethodtokenizationresponse(); paymentmethodtokenizationresponse contains only setter methods. each setter accepts a value from the payment gateway and use it to set an attribute of paymentmethodtokenizationresponse. the most important method in paymentmethodtokenizationresponse is setgatewaytokenencrypted, which uses salesforce encryption to set an encrypted token value for a payment method. the setgatewaytokenencrypted method is available in salesforce api v52.0 and later. we recommend using it to ensure your tokenized payment method values are encrypted and secure. while the setgatewaytoken method (available in earlier api versions) also returns a payment method token, the tokenized value isn't encrypted. if the instantiated class already has a gateway token, setgatewaytokenencrypted throws an error. /** @description method to set gateway token to persist in encrypted text */ global void setgatewaytokenencrypted(string gatewaytokenencrypted) { if (gatewaytokenset) { throwtokenerror(); } this.delegate.setgatewaytokenencrypted(gatewaytokenencrypted); gatewaytokenencryptedset = true; } a typical instantiation of paymentmethodtokenizationresponse sets the encrypted gateway token alongside the other tokenization response values sent by the gateway. public commercepayments.gatewayresponse createtokenizeresponse(commercepayments.paymentmethodtokenizationrequest tokenizerequest) 345apex reference guide paymentmethodtokenizationresponse class { commercepayments.paymentmethodtokenizationresponse tokenizeresponse = new commercepayments.paymentmethodtokenizationresponse(); tokenizeresponse.setgatewaytokenencrypted(gatewaytokenencrypted); tokenizeresponse.setgatewaytokendetails(gatewaytokendetails); tokenizeresponse.setgatewayavscode(gatewayavscode); tokenizeresponse.setgatewaymessage(gatewaymessage); tokenizeresponse.setgatewayresultcode(gatewayresultcode); tokenizeresponse.setgatewayresultcodedescription(gatewayresultcodedescription); tokenizeresponse.setsalesforceresultcodeinfo(success_salesforce_result_code_info); tokenizeresponse.setgatewaydate(system.now()); return tokenizeresponse; } after you've built a paymentmethodtokenizationresponse object and set the encrypted gateway token, pass the object to the setpaymentmethodtokenizationresponse method of an authorization response or a sale response. authorization response public commercepayments.gatewayresponse createauthresponse(commercepayments.authorizationrequest authrequest) { commercepayments.authorizationresponse authresponse = new commercepayments.authorizationresponse(); commercepayments.paymentmethodtokenizationresponse paymentmethodtokenizationresponse = new commercepayments.paymentmethodtokenizationresponse(); if(authrequest.amount!=null ) { authresponse.setamount(authrequest.amount); } else { throw new salesforcevalidationexception('required field missing : amount'); } authresponse.setgatewayresultcode('00'); authresponse.setgatewayresultcodedescription('transaction normal'); authresponse.setgatewayauthcode('sf'+getrandomnumber(6)); |
authresponse.setgatewayreferencenumber(getrandomnumber(10)); authresponse.setsalesforceresultcodeinfo(success_salesforce_result_code_info); authresponse.setgatewaydate(system.now()); paymentmethodtokenizationresponse.setgatewaytokenencrypted(gatewaytokenencrypted); authresponse.setpaymentmethodtokenizationresponse(paymentmethodtokenizationresponse); return authresponse; } sale response public commercepayments.gatewayresponse createsaleresponse(commercepayments.salerequest salerequest) { commercepayments.saleresponse saleresponse = new commercepayments.saleresponse(); 346apex reference guide paymentmethodtokenizationresponse class commercepayments.paymentmethodtokenizationresponse paymentmethodtokenizationresponse = new commercepayments.paymentmethodtokenizationresponse(); if(salerequest.amount!=null ) { saleresponse.setamount(salerequest.amount); } else { throw new salesforcevalidationexception('required field missing : amount'); } system.debug('response - success'); saleresponse.setgatewaydate(system.now()); saleresponse.setgatewayresultcode('00'); saleresponse.setgatewayresultcodedescription('transaction normal'); saleresponse.setgatewayreferencenumber('sf'+getrandomnumber(6)); saleresponse.setsalesforceresultcodeinfo(success_salesforce_result_code_info); paymentmethodtokenizationresponse.setgatewaytokenencrypted(gatewaytokenencrypted); saleresponse.setpaymentmethodtokenizationresponse(paymentmethodtokenizationresponse); return saleresponse; } in this section: paymentmethodtokenizationresponse methods paymentmethodtokenizationresponse methods the following are methods for paymentmethodtokenizationresponse. in this section: setgatewayavscode(gatewayavscode) sets the avs (address verification system) result code information that the gateway returned. maximum length of 64 characters. setgatewaydate(gatewaydate) sets the date that the tokenization occurred. some gateways don’t send this value. setgatewaymessage(gatewaymessage) sets error messages that the gateway returned for the tokenization request. maximum length of 255 characters. setgatewayresultcode(gatewayresultcode) sets a gateway-specific result code. the code may be mapped to a salesforce-specific result code. maximum length of 64 characters. setgatewayresultcodedescription(gatewayresultcodedescription) sets a description of the gateway-specific result code that a payment gateway returned. maximum length of 1000 characters. 347apex reference guide paymentmethodtokenizationresponse class setgatewaytoken(gatewaytoken) sets the gateway token value that the gateway returned. setgatewaytokendetails(gatewaytokendetails) sets any additional information that the gateway returned about the payment token. setgatewaytokenencrypted(gatewaytokenencrypted) sets the value of the gatewaytokenencrypted field on a cardpaymentmethod or digitalwallet object. setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets the salesforce-specific result code information. payment gateways have many response codes for payment calls. salesforce uses the result code information to map payment gateway codes to a predefined set of standard salesforce result codes. setgatewayavscode(gatewayavscode) sets the avs (address verification system) result code information that the gateway returned. maximum length of 64 characters. signature global void setgatewayavscode(string gatewayavscode) parameters gatewayavscode type: string used to verify the address mapped to a payment method when the payments platform requests tokenization from the payment gateway. return value type: void setgatewaydate(gatewaydate) sets the date that the tokenization occurred. some gateways don’t send this value. signature global void setgatewaydate(datetime gatewaydate) parameters gatewaydate type: datetime return value type: void setgatewaymessage(gatewaymessage) sets error messages that the gateway returned for the tokenization request. maximum length of 255 characters. 348apex reference guide paymentmethodtokenizationresponse class signature global void setgatewaymessage(string gatewaymessage) parameters gatewaymessage type: string return value type: void setgatewayresultcode(gatewayresultcode) sets a |
gateway-specific result code. the code may be mapped to a salesforce-specific result code. maximum length of 64 characters. signature global void setgatewayresultcode(string gatewayresultcode) parameters gatewayresultcode type: string gateway-specific result code. must be used to map a salesforce-specific result code. return value type: void setgatewayresultcodedescription(gatewayresultcodedescription) sets a description of the gateway-specific result code that a payment gateway returned. maximum length of 1000 characters. signature global void setgatewayresultcodedescription(string gatewayresultcodedescription) parameters gatewayresultcodedescription type: string provides additional information about the result code and why the gateway returned the specific code. descriptions will vary between different gateways. return value type: void 349apex reference guide paymentmethodtokenizationresponse class setgatewaytoken(gatewaytoken) sets the gateway token value that the gateway returned. signature global void setgatewaytoken(string gatewaytoken) parameters gatewaytoken type: string the gateway token that the payment gateway sends following a tokenization request. for the cardpaymentmethod and digitalwallet objects, use the gatewytokenencrypted parameter, which encrypts the token value. return value type: void setgatewaytokendetails(gatewaytokendetails) sets any additional information that the gateway returned about the payment token. signature global void setgatewaytokendetails(string gatewaytokendetails) parameters gatewaytokendetails type: string return value type: void setgatewaytokenencrypted(gatewaytokenencrypted) sets the value of the gatewaytokenencrypted field on a cardpaymentmethod or digitalwallet object. signature global void setgatewaytokenencrypted(string gatewaytokenencrypted) parameters gatewaytokenencrypted type: string 350apex reference guide paymentgatewaynotificationrequest class the gateway token that the payment gateway sends following a tokenization request. salesforce payments uses salesforce encryption to encrypt the token value. return value type: void setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets the salesforce-specific result code information. payment gateways have many response codes for payment calls. salesforce uses the result code information to map payment gateway codes to a predefined set of standard salesforce result codes. signature global void setsalesforceresultcodeinfo(commercepayments.salesforceresultcodeinfo salesforceresultcodeinfo) parameters salesforceresultcodeinfo type: salesforceresultcodeinfo on page 380 description of the salesforce result code value. return value type: void paymentgatewaynotificationrequest class contains the notification request data from the gateway. namespace commercepayments on page 256 usage when the payment gateway sends a notification for a payment request, the payments platform sends the notification request to the gateway adapter. if the notification payload contains an eventcode of capture, the adapter constructs a capturenotification. if the notification payload contains an eventcode of refund, the adapter constructs a referencedrefundnotification. if the notification payload contains eventcode of authorisation, the adapter constructs a gatewaynotificationresponse. you can obtain a notification request from paymentgatewaynotificationcontext on page 339 by invoking its getpaymentgatewaynotificationrequest method. 351apex reference guide paymentgatewaynotificationrequest class example global commercepayments.gatewaynotificationresponse processnotification(commercepayments.paymentgatewaynotificationcontext gatewaynotificationcontext) { commercepayments.paymentgatewaynotificationrequest notificationrequest = gatewaynotificationcontext.getpaymentgatewaynotificationrequest(); } in this section: paymentgatewaynotificationrequest properties paymentgatewaynotificationrequest methods paymentgatewaynotificationrequest properties the following are properties for paymentgatewaynotificationrequest. in this section: requestbody body of the notification request sent by the payment gateway. requestbody body of the notification request sent by the payment gateway. signature global blob requestbody {get; set;} property value type: blob paymentgatewaynotificationrequest methods the following are methods for paymentgatewaynotificationrequest. in this section: getheaders() gets http headers from the notification request sent by the payment gateway. getrequestbody() stores the notification request body information from the payment gateway’s notification request. gethead |
ers() gets http headers from the notification request sent by the payment gateway. 352apex reference guide paymentshttp class signature global map<string,string> getheaders() return value type: map<string,string> getrequestbody() stores the notification request body information from the payment gateway’s notification request. signature global blob getrequestbody() return value type: blob paymentshttp class makes an http request to start the interaction with the payment gateway. namespace commercepayments on page 256 usage you must specify the commercepayments namespace when creating an instance of this class. the constructor of this class takes no arguments. for example: commercepayments.paymentshttp payhttp = new commercepayments.paymentshttp(); in this section: paymentshttp methods paymentshttp constructors paymentshttp methods the following are methods for paymentshttp. all methods are instance methods. in this section: send(request) sends an httprequest and returns the response. 353apex reference guide refundrequest class send(request) sends an httprequest and returns the response. signature global httpresponse send(httprequest request) parameters request type: system.httprequest return value type: system.httpresponse paymentshttp constructors the following are constructors for paymentshttp. in this section: paymentshttp() initiates an http request and response. paymentshttp() initiates an http request and response. signature global paymentshttp() refundrequest class sends data related to a refund to the payment gateway adapter. namespace commercepayments on page 354 usage the constructor of this class takes no arguments. for example: commercepayments.refundrequest rrq = new commercepayments.refundrequest(); 354apex reference guide refundrequest class example commercepayments.referencedrefundrequest refundrequest = new commercepayments.referencedrefundrequest(80, pmt.id); in this section: refundrequest methods refundrequest methods the following are methods for refundrequest. in this section: equals(obj) maintains the integrity of lists of type refundrequest by determining the equality of external objects in a list. this method is dynamic and is based on the equals method in java. hashcode() maintains the integrity of lists of type refundrequest by determining the uniqueness of the external object records in a list. equals(obj) maintains the integrity of lists of type refundrequest by determining the equality of external objects in a list. this method is dynamic and is based on the equals method in java. signature global boolean equals(object obj) parameters obj type: object return value type: boolean hashcode() maintains the integrity of lists of type refundrequest by determining the uniqueness of the external object records in a list. signature global integer hashcode() return value type: integer 355apex reference guide referencedrefundnotification class referencedrefundnotification class when a payment gateway sends a notification for a refund transaction, the payment gateway adapter creates the referencedrefundnotification object to store information about notification. namespace commercepayments on page 256 usage this class is used with asynchronous payments. when a payment gateway sends a notification for a refund transcation, the gateway adapter creates an object of type referencedrefundnotification to populate the respective values. the constructor of this class takes no arguments. for example: commercepayments.referencedrefundnotification rrn = new commercepayments.referencedrefundnotification(); example commercepayments.notificationstatus notificationstatus = null; if (success) { notificationstatus = commercepayments.notificationstatus.success; } else { notificationstatus = commercepayments.notificationstatus.failed; } commercepayments.basenotification notification = null; if ('capture'.equals(eventcode)) { notification = new commercepayments.capturenotification(); } else if ('refund'.equals(eventcode)) { notification = new commercepayments.referencedrefundnotification(); } in this section: referencedrefundnotification methods referencedrefundnotification methods the following are methods for referencedrefundnotification. in this section: setamount |
(amount) sets the transaction amount. can be positive, negative, or zero. setgatewaydate(gatewaydate) sets the date that communication for the refund notification occurred with the payment gateway. setgatewaymessage(gatewaymessage) sets information or messages that the gateway returned. 356apex reference guide referencedrefundnotification class setgatewayreferencedetails(gatewayreferencedetails) sets the payment gateway’s reference details. setgatewayreferencenumber(gatewayreferencenumber) sets the payment gateway’s reference number. setgatewayresultcode(gatewayresultcode) sets the payment gateway’s result code. setgatewayresultcodedescription(gatewayresultcodedescription) sets the payment gateway’s result code description. setid(id) sets the id of a notification sent by the payment gateway. setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets salesforce result code information. setstatus(status) sets the notification status value on the notification object. setamount(amount) sets the transaction amount. can be positive, negative, or zero. signature global void setamount(double amount) parameters amount type: double the amount to be debited or captured. return value type: void setgatewaydate(gatewaydate) sets the date that communication for the refund notification occurred with the payment gateway. signature global void setgatewaydate(datetime gatewaydate) parameters gatewaydate type: datetime the date that communication happened with the gateway. 357apex reference guide referencedrefundnotification class return value type: void setgatewaymessage(gatewaymessage) sets information or messages that the gateway returned. signature global void setgatewaymessage(string gatewaymessage) parameters gatewaymessage type: string return value type: void setgatewayreferencedetails(gatewayreferencedetails) sets the payment gateway’s reference details. signature global void setgatewayreferencedetails(string gatewayreferencedetails) parameters gatewayreferencedetails type: string provides information about the gateway communication. return value type: void setgatewayreferencenumber(gatewayreferencenumber) sets the payment gateway’s reference number. signature global void setgatewayreferencenumber(string gatewayreferencenumber) parameters gatewayreferencenumber type: string 358apex reference guide referencedrefundnotification class unique transaction id created by the payment gateway. return value type: void setgatewayresultcode(gatewayresultcode) sets the payment gateway’s result code. signature global void setgatewayresultcode(string gatewayresultcode) parameters gatewayresultcode type: string the gateway result code. you must map this to a salesforce-specific result code. return value type: void setgatewayresultcodedescription(gatewayresultcodedescription) sets the payment gateway’s result code description. signature global void setgatewayresultcodedescription(string gatewayresultcodedescription) parameters gatewayresultcodedescription type: string description of the gateway result code. provides additional context about the result code . return value type: void setid(id) sets the id of a notification sent by the payment gateway. signature global void setid(string id) 359apex reference guide referencedrefundrequest parameters id type: string return value type: void setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets salesforce result code information. signature global void setsalesforceresultcodeinfo(commercepayments.salesforceresultcodeinfo salesforceresultcodeinfo) parameters salesforceresultcodeinfo type: salesforceresultcodeinfo on page 380 description of the salesforce result code value. return value type: void setstatus(status) sets the notification status value on the notification object. signature global void setstatus(commercepayments.notificationstatus status) parameters status type: notificationstatus on page 333 indicates whether the payments platform successfully received the notification from the payment gateway. return value type: void referencedrefundrequest access information about the referenced refund requests. extends the refundrequest class. 360apex reference guide referencedrefundrequest namespace commercepayments on page 256 example global commercepayments. |
gatewayresponse processrequest(commercepayments.paymentgatewaycontext gatewaycontext) { commercepayments.requesttype requesttype = gatewaycontext.getpaymentrequesttype(); if (requesttype == commercepayments.requesttype.referencedrefund) { commercepayments.*referencedrefundrequest* refundrequest = (commercepayments.*referencedrefundrequest*) gatewaycontext.getpaymentrequest(); } } in this section: referencedrefundrequest constructors referencedrefundrequest properties referencedrefundrequest methods referencedrefundrequest constructors the following are constructors for referencedrefundrequest. in this section: referencedrefundrequest(amount, paymentid) this constructor is intended for test usage and throws an exception if used outside of the apex test context. referencedrefundrequest(amount, paymentid) this constructor is intended for test usage and throws an exception if used outside of the apex test context. parameters amount type: double the amount to be debited or captured. paymentid type: string the payment record. referencedrefundrequest properties the following are properties for referencedrefundrequest. 361apex reference guide referencedrefundresponse class in this section: paymentid references a payment object. accountid references an account. amount references an amount. paymentid references a payment object. property value type: string accountid references an account. property value type: string amount references an amount. property value type: double referencedrefundrequest methods the following are methods for referencedrefundrequest. referencedrefundresponse class the payment gateway adapter sends this response for the referencedrefund request type. namespace commercepayments on page 256 usage the constructor of this class takes no arguments. for example: 362apex reference guide referencedrefundresponse class commercepayments.referencedrefundresponse refr = new commercepayments.referencedrefundresponse(); in this section: referencedrefundresponse methods referencedrefundresponse methods the following are methods for referencedrefundresponse. in this section: setamount(amount) sets the transaction amount. the value must be a postive number. setgatewayavscode(gatewayavscode) sets the payment gateway’s address verification system (avs) code. setgatewaydate(gatewaydate) sets the payment gateway’s date. setgatewaymessage(gatewaymessage) sets information or messages that the gateway returned. setgatewayreferencedetails(gatewayreferencedetails) sets the payment gateway’s reference details. setgatewayreferencenumber(gatewayreferencenumber) sets the payment gateway’s reference number. setgatewayresultcode(gatewayresultcode) sets the payment gateway’s result code. setgatewayresultcodedescription(gatewayresultcodedescription) sets the payment gateway’s result code description. setsalesforceresultcodeinfo(salesforceresultcodeinfo) set the salesforce result code info. setamount(amount) sets the transaction amount. the value must be a postive number. signature global void setamount(double amount) parameters amount type: double the amount to be debited or captured. 363apex reference guide referencedrefundresponse class return value type: void setgatewayavscode(gatewayavscode) sets the payment gateway’s address verification system (avs) code. signature global void setgatewayavscode(string gatewayavscode) parameters gatewayavscode type: string code sent by gateways that use an address verification system. return value type: void setgatewaydate(gatewaydate) sets the payment gateway’s date. signature global void setgatewaydate(datetime gatewaydate) parameters gatewaydate type: datetime date and time of the gateway communication. return value type: void setgatewaymessage(gatewaymessage) sets information or messages that the gateway returned. signature global void setgatewaymessage(string gatewaymessage) 364apex reference guide referencedrefundresponse class parameters gatewaymessage type: string information or error messages returned by the gateway. |
return value type: void setgatewayreferencedetails(gatewayreferencedetails) sets the payment gateway’s reference details. signature global void setgatewayreferencedetails(string gatewayreferencedetails) parameters gatewayreferencedetails type: string information about the gateway communication. return value type: void setgatewayreferencenumber(gatewayreferencenumber) sets the payment gateway’s reference number. signature global void setgatewayreferencenumber(string gatewayreferencenumber) parameters gatewayreferencenumber type: string unique transaction id created by the payment gateway. return value type: void setgatewayresultcode(gatewayresultcode) sets the payment gateway’s result code. 365apex reference guide referencedrefundresponse class signature global void setgatewayresultcode(string gatewayresultcode) parameters gatewayresultcode type: string the gateway result code. must be mapped to a salesforce result code. return value type: void setgatewayresultcodedescription(gatewayresultcodedescription) sets the payment gateway’s result code description. signature global void setgatewayresultcodedescription(string gatewayresultcodedescription) parameters gatewayresultcodedescription type: string description of the gatewayresultcode. provides more information about the result code returned by the gateway. return value type: void setsalesforceresultcodeinfo(salesforceresultcodeinfo) set the salesforce result code info. signature global void setsalesforceresultcodeinfo(commercepayments.salesforceresultcodeinfo salesforceresultcodeinfo) parameters salesforceresultcodeinfo type: commercepayments.salesforceresultcodeinfo on page 380 describes the salesforce result code value. return value type: void 366apex reference guide requesttype enum requesttype enum defines the type of payment transaction request made to the payment gateway. enum values the following are the values of the commercepayments.requesttype enum. value description authorize payment authorization request capture payment capture request referencedrefund payment refund request sale sale request commercepayments.requesttype, sale tokenization payment tokenization request commercepayments.requesttype, tokenization saleapipaymentmethodrequest class sends data related to a card payment method to a gateway adapter during a sale service call. namespace commercepayments on page 256 usage this class holds information about a payment method that was used for a sale request. saleapipaymentmethodrequest contains all the possible payment methods as fields, but only one value is populated for a given request. gateway adapters use this class when constructing a sale request. the object of this class is obtained through the paymentmethod field on the salerequest object. example: this code sample retrieves the saleapipaymentmethodrequest object from the salerequest class. commercepayments.saleapipaymentmethodrequest paymentmethod = salerequest.paymentmethod; in this section: saleapipaymentmethodrequest constructors saleapipaymentmethodrequest properties saleapipaymentmethodrequest methods 367apex reference guide saleapipaymentmethodrequest class saleapipaymentmethodrequest constructors the following are constructors for saleapipaymentmethodrequest. in this section: saleapipaymentmethodrequest(cardpaymentmethodrequest) sends data related to a card payment method to a gateway adapter during a sale service call. saleapipaymentmethodrequest() constructor for building a sale payment method request. this constructor is intended for test usage and throws an exception if used outside of the apex test context. saleapipaymentmethodrequest(cardpaymentmethodrequest) sends data related to a card payment method to a gateway adapter during a sale service call. signature global saleapipaymentmethodrequest(commercepayments.cardpaymentmethodrequest cardpaymentmethodrequest) parameters cardpaymentmethodrequest type: cardpaymentmethodrequest on page 318 saleapipaymentmethodrequest() constructor for building a sale payment method request. this constructor is intended for test usage and throws an exception if used outside of the apex test context. signature global saleapipaymentmethodrequest() saleapipaymentmethodrequest properties the following are properties for saleapipaymentmethodrequest. in this section: cardpaymentmethod contains details of the card used in a |
payment method. cardpaymentmethod contains details of the card used in a payment method. 368apex reference guide saleapipaymentmethodrequest class signature global commercepayments.cardpaymentmethodrequest cardpaymentmethod {get; set;} property value type: cardpaymentmethodrequest on page 318 saleapipaymentmethodrequest methods the following are methods for saleapipaymentmethodrequest. in this section: equals(obj) maintains the integrity of lists of type saleapipaymentmethodrequest by determining the equality of external objects in a list. this method is dynamic and is based on the equals method in java. hashcode() maintains the integrity of lists of type saleapipaymentmethodrequest by determining the uniqueness of the external object records in a list. tostring() converts a date to a string. equals(obj) maintains the integrity of lists of type saleapipaymentmethodrequest by determining the equality of external objects in a list. this method is dynamic and is based on the equals method in java. signature global boolean equals(object obj) parameters obj type: object return value type: boolean hashcode() maintains the integrity of lists of type saleapipaymentmethodrequest by determining the uniqueness of the external object records in a list. signature global integer hashcode() 369apex reference guide salerequest class return value type: integer tostring() converts a date to a string. signature global string tostring() return value type: string salerequest class stores information about a sales request. namespace commercepayments on page 256 usage this class holds all the required details about a sale request. gateway adapters read the fields of this class object while constructing a sale json request thatis sent to the payment gateway. the object of this class is made available through commercepayments.paymentgatewaycontext by calling getpaymentrequest(). example this code sample retrieves the salerequest object from the paymentgatewaycontext class. commercepayments.salerequest = (commercepayments.salerequest)gatewaycontext.getpaymentrequest() in this section: salerequest constructors salerequest properties salerequest methods salerequest constructors the following are constructors for salerequest. 370apex reference guide salerequest class in this section: salerequest(amount) constructor for defining an amount for the sale request. this constructor is intended for test usage and throws an exception if used outside of the apex test context. salerequest(amount) constructor for defining an amount for the sale request. this constructor is intended for test usage and throws an exception if used outside of the apex test context. signature global salerequest(double amount) parameters amount type: double amount of the sale request. salerequest properties the following are properties for salerequest. in this section: accountid customer account id for the sale request. amount amount of the sale request. can be positive only. comments additional information about the sale request. currencyisocode currency code for the sale request. paymentmethod payment method used in the sale request. accountid customer account id for the sale request. signature global string accountid {get; set;} 371apex reference guide salerequest class property value type: string amount amount of the sale request. can be positive only. signature global double amount {get; set;} property value type: double comments additional information about the sale request. signature global string comments {get; set;} property value type: string currencyisocode currency code for the sale request. signature global string currencyisocode {get; set;} property value type: string paymentmethod payment method used in the sale request. signature global commercepayments.saleapipaymentmethodrequest paymentmethod {get; set;} property value type: saleapipaymentmethodrequest on page 367 372apex reference guide salerequest class salerequest methods the following are methods for salerequest. in this section: equals(obj) compares this object with the specified object and returns true if both objects are equal; otherwise, returns false. hashcode() maintains the integrity of lists of type salerequest by determining the uniqueness of the external object records in a list. tostring() converts a |
date to a string. equals(obj) compares this object with the specified object and returns true if both objects are equal; otherwise, returns false. signature global boolean equals(object obj) parameters obj type: object return value type: boolean hashcode() maintains the integrity of lists of type salerequest by determining the uniqueness of the external object records in a list. signature global integer hashcode() return value type: integer tostring() converts a date to a string. signature global string tostring() 373apex reference guide saleresponse class return value type: string saleresponse class response sent by payment gateway adapters for a sales service. namespace commercepayments on page 256 usage the constructor of this class takes no arguments. for example: commercepayments.saleresponse slr commercepayments.saleresponse(); this class contains details about a customer card that was used as a payment method for authorization, sale, or tokenization request. the gateway adapter reads the fields of this class while constructing a transaction json request, which it then sends to the payment gateway. the object of this class is made available by the cardpaymentmethod field in saleapipaymentmethodrequest on page 367 and authapipaymentmethodrequest on page 273. example this code sample builds a saleresponse object. commercepayments.saleresponse saleresponse = new commercepayments.saleresponse(); saleresponse.setgatewayreferencedetails("refdetailstring"); saleresponse.setgatewayresultcode("res_code"); saleresponse.setgatewayresultcodedescription(""); saleresponse.setgatewayreferencenumber(""); saleresponse.setsalesforceresultcodeinfo(getsalesforceresultcodeinfo(commercepayments.salesforceresultcode.success.name())); in this section: saleresponse methods saleresponse methods the following are methods for saleresponse. in this section: setamount(amount) sets the transaction amount. must be a non-negative value. setgatewayavscode(gatewayavscode) sets the avs (address verification system) result code information that the gateway returned. maximum length of 64 characters. setgatewaydate(gatewaydate) sets the date that the sale occurred. some gateways don’t send this value. 374apex reference guide saleresponse class setgatewaymessage(gatewaymessage) sets error messages that the gateway returned for the sale request. maximum length of 255 characters. setgatewayreferencedetails(gatewayreferencedetails) sets additional data that you can use for subsequent sales. you can use any data that isn’t normalized in financial entities. this field has a maximum length of 1000 characters and can store data as json or xml. setgatewayreferencenumber(gatewayreferencenumber) sets the unique gateway reference number for the transaction that the gateway returned. maximum length of 255 characters. setgatewayresultcode(gatewayresultcode) sets a gateway-specific result code. the code may be mapped to a salesforce-specific result code. maximum length of 64 characters. setgatewayresultcodedescription(gatewayresultcodedescription) sets a description of the gateway-specific result code that a payment gateway returned. maximum length of 1000 characters. setpaymentmethodtokenizationresponse(paymentmethodtokenizationresponse) sets information from the gateway about the tokenized payment method. setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets the salesforce-specific result code information. payment gateways have many response codes for payment calls. salesforce uses the result code information to map payment gateway codes to a predefined set of standard salesforce result codes. setamount(amount) sets the transaction amount. must be a non-negative value. signature global void setamount(double amount) parameters amount type: double the amount of the transaction. return value type: void setgatewayavscode(gatewayavscode) sets the avs (address verification system) result code information that the gateway returned. maximum length of 64 characters. signature global void setgatewayavscode(string gatewayavscode) parameters gatewayavscode type: string 375apex reference guide saleresponse class used to verify the address mapped to a payment method when the payments platform requests tokenization from the payment gateway. return value type: void setgatewaydate(gatewaydate) sets the date that the sale occurred. |
some gateways don’t send this value. signature global void setgatewaydate(datetime gatewaydate) parameters gatewaydate type: datetime return value type: void setgatewaymessage(gatewaymessage) sets error messages that the gateway returned for the sale request. maximum length of 255 characters. signature global void setgatewaymessage(string gatewaymessage) parameters gatewaymessage type: string return value type: void setgatewayreferencedetails(gatewayreferencedetails) sets additional data that you can use for subsequent sales. you can use any data that isn’t normalized in financial entities. this field has a maximum length of 1000 characters and can store data as json or xml. signature global void setgatewayreferencedetails(string gatewayreferencedetails) 376apex reference guide saleresponse class parameters gatewayreferencedetails type: string return value type: void setgatewayreferencenumber(gatewayreferencenumber) sets the unique gateway reference number for the transaction that the gateway returned. maximum length of 255 characters. signature global void setgatewayreferencenumber(string gatewayreferencenumber) parameters gatewayreferencenumber type: string unique authorization id created by the payment gateway. return value type: void setgatewayresultcode(gatewayresultcode) sets a gateway-specific result code. the code may be mapped to a salesforce-specific result code. maximum length of 64 characters. signature global void setgatewayresultcode(string gatewayresultcode) parameters gatewayresultcode type: string gateway-specific result code. must be used to map a salesforce-specific result code. return value type: void setgatewayresultcodedescription(gatewayresultcodedescription) sets a description of the gateway-specific result code that a payment gateway returned. maximum length of 1000 characters. 377apex reference guide saleresponse class signature global void setgatewayresultcodedescription(string gatewayresultcodedescription) parameters gatewayresultcodedescription type: string description of the gateway’s result code. use this field to learn more about why the gateway returned a certain result code. return value type: void setpaymentmethodtokenizationresponse(paymentmethodtokenizationresponse) sets information from the gateway about the tokenized payment method. signature global void setpaymentmethodtokenizationresponse(commercepayments.paymentmethodtokenizationresponse paymentmethodtokenizationresponse) parameters paymentmethodtokenizationresponse type: paymentmethodtokenizationresponse on page 345 gateway response sent by payment gateway adapters for the payment method tokenization request. the response includes the payment method’s token id value. return value type: void setsalesforceresultcodeinfo(salesforceresultcodeinfo) sets the salesforce-specific result code information. payment gateways have many response codes for payment calls. salesforce uses the result code information to map payment gateway codes to a predefined set of standard salesforce result codes. signature global void setsalesforceresultcodeinfo(commercepayments.salesforceresultcodeinfo salesforceresultcodeinfo) parameters salesforceresultcodeinfo type: salesforceresultcodeinfo on page 380 378apex reference guide salesforceresultcode enum sets the salesforce-specific result code information. payment gateways have many response codes for payment calls. salesforce uses the result code information to map payment gateway codes to a predefined set of standard salesforce result codes. return value type: void salesforceresultcode enum defines the gateway call status values in salesforce based on the call status values that the payment gateway returned. usage payment gateways can return many different responses. salesforce maps these responses into one of seven possible salesforce response values. enum values the following are the values of the commercepayments.salesforceresultcode enum. value description decline the gateway call failed, but it may still work if you try again. for example, the customer had insufficient funds or briefly lost their connection to the internet. this is also known as a “soft decline.” indeterminate the gateway didn't respond to the call and the user has to check the transaction request’s status. indeterminate responses often occur following server timeouts, system failure, or any action that interrupts the gateway’s ability to process the payment. permanentfail the customer’s bank recognized the payment account as closed, terminated, or fraudulent. the gateway won’t further calls |
from the payment method associate with the transaction. after a permanent fail response, the transaction changes its gateway status to permanent fail. requiresreview the gateway call initially failed, but the payment method may still work after further evaluation. this response often happens when the customer bank requires more information about the payment request. in this case, the bank provides an authorization code manually when the payment manager calls the processor. success the gateway processed the transaction successfully. systemerror salesforce ended the payment request call before receiving a gateway response. system error responses often occur due to gateway server errors, invalid customer credentials, or anytime the request times out before receiving a gateway response. the failure occurs before the request reaches the gateway, so there’s no risk of an unaccounted payment remaining in the gateway. you can continue with the transaction by manually creating a payment. validationerror the gateway received incorrect customer payment information, such as misspelled credit card names or a cvv with missing numbers. 379apex reference guide salesforceresultcodeinfo salesforceresultcodeinfo stores salesforce result code information from payment gateway adapters. namespace commercepayments on page 256 usage the constructor of this class takes no arguments. for example: commercepayments.salesforceresultcodeinfo srci = new commercepayments.salesforceresultcodeinfo(); gateways can return the transaction result as either custommetadata or salesforceresultcode. in this section: salesforceresultcodeinfo constructors salesforceresultcodeinfo constructors the following are constructors for salesforceresultcodeinfo. in this section: salesforceresultcodeinfo(custommetadatatypeinfo) constructor for providing the custommetadatatypeinfo for the result of the transaction. salesforceresultcodeinfo(salesforceresultcode) constructor that provides the salesforceresultcode for the transaction result. salesforceresultcodeinfo(custommetadatatypeinfo) constructor for providing the custommetadatatypeinfo for the result of the transaction. signature global salesforceresultcodeinfo(commercepayments.custommetadatatypeinfo custommetadatatypeinfo) parameters custommetadatatypeinfo type: custommetadatatypeinfo on page 324 information about the metadata type. salesforceresultcodeinfo(salesforceresultcode) constructor that provides the salesforceresultcode for the transaction result. 380apex reference guide connectapi namespace signature global salesforceresultcodeinfo(commercepayments.salesforceresultcode salesforceresultcode) parameters salesforceresultcode type: salesforceresultcode on page 379 the enum value for the result code. connectapi namespace the connectapi namespace (also called connect in apex) provides classes for accessing the same data available in connect rest api. use connect in apex to create custom experiences in salesforce. for information about working with the connectapi classes, see connect in apex. in this section: actionlinks class create, delete, and get information about an action link group definition; get information about an action link group; get action link diagnostic information. announcements class access information about announcements and post announcements. botversionactivation class access and update activation information of a bot version. cdpcalculatedinsight class create, delete, get, run, and update data cloud calculated insights. cdpidentityresolution class create, delete, get, run, and update data cloud identity resolution rulesets. cdpquery class get data cloud metadata and query data. cdpsegment class create, delete, get, publish, and update data cloud segments. chatter class access information about followers and subscriptions for records. chatterfavorites class chatter favorites give you easy access to topics, list views, and feed searches. chatterfeeds class get, post, and delete feed elements, likes, comments, and bookmarks. you can also search feed elements, share feed elements, and vote on polls. chattergroups class information about groups, such as the group’s members, photo, and the groups the specified user is a member of. add members to a group, remove members, and change the group photo. 381apex reference guide connectapi namespace chattermessages class get, send, search, and reply to private messages. you can also get and search private conversations, mark conversations as read, and get a count of unread private messages. chatterusers class access information about users, such as activity, followers, subscriptions, files, and groups. clm class create and update contract |
lifecycle management (clm) contracts using object id. commercebuyerexperience class create, delete, or get commerce addresses. get order delivery group, order item, order shipments, shipment items, and order summaries. get adjustments for order items and order summaries. commercecart class get, create, update, and delete carts. get cart items, add items to carts, update and delete cart items. commercecatalog class get products, product categories, and product category paths. commercepromotions class evaluate promotions for commerce orders. get coupon code redemption usage. commercesearch class get sort rules for the live search index. get product search suggestions. search products. commercesearchsettings class get indexes. get index logs. create an index of a product catalog. commercestorepricing class get product prices. commercewishlist class get, create, update, and delete wishlists. add wishlists to carts. get wishlist items, add items to wishlists, and delete wishlist items. communities class get information about experience cloud sites in your org. communitymoderation class get information about flagged feed items and comments in an experience cloud site. add and remove flags from comments and feed items. contenthub class access files connect repositories and their files and folders. conversationapplicationdefinition class access information about a conversation application definition. datacloud class purchase data.com contact or company records, and retrieve purchase information. emailmergefieldservice class extract a list of merge fields for an object. a merge field is a field you can put in an email template, mail merge template, custom link, or formula to incorporate values from a record. employeeprofiles class get, set and crop, and delete employee banner photos and photos. 382 |
apex reference guide connectapi namespace externalemailservices class access information about integration with external email services, such as sending email within salesforce through an external email account. externalmanagedaccount class get externally managed accounts. fieldservice class preview and create shifts from a pattern or filter fields on recordset filter criteria. fulfillmentorder class fulfill orders in order management. knowledge class get information about trending articles in experience cloud sites. lightningscheduler class create and update service appointments. managedcontent class get managed content versions. get a managed content space. managedcontentdelivery class get collection items. get collection metadata. get a managed content channel. get managed content. managedtopics class get managed topics in an experience cloud site. create, delete, and reorder managed topics. marketingintegration class get, save, and submit a microsites marketing integration form for an experience cloud site. mentions class access information about mentions. a mention is an “@” character followed by a user or group name. when a user or group is mentioned, they receive a notification. missions class export and purge mission activity for users. get a user’s mission progress. update mission activity counts for users. namedcredentials class create, refresh, get, delete, and update credentials. create, get, delete, and update external credentials. create, get, delete, and update named credentials. get the url for the oauth token flow for an external credential. navigationmenu class get navigation menu items for an experience cloud site. nextbestaction class execute recommendation strategies, get recommendations, manage recommendation reactions. omnichannelinventoryservice class route orders to inventory locations in order management. orchestration class get orchestration instances. orderpaymentsummary class work with payments in order management. ordersummary class work with orders in order management. 383apex reference guide connectapi namespace ordersummarycreation class create order summaries in order management. organization class access information about an org. pardotbusinessunitcontext class get the pardot business units the context user has access to. payments class authorize a payment, capture an authorized payment, and refund an authorized payment. personalization class get assigned personalization audiences that match the user context. create, get, update, and delete an audience. get personalization targets that match the user context, based on the assigned audiences that include the user. create and update targets. get and delete a target. pick ticket class create tickets to fulfill orders. questionandanswers class access question and answers suggestions. recommendations class get and reject chatter, custom, and static recommendations. create, get, update, and delete custom recommendation audiences, custom recommendation definitions, and scheduled custom recommendations. records class access information about record motifs, which are small icons used to distinguish record types in the salesforce ui. repricing class perform functions related to repricing orders in order management. returnorder class process returnorders in order management. routing class route orders to inventory locations in order management. salesforceinbox class access information about automated activity capture, which is available in einstein and salesforce inbox. sites class search an experience cloud site. smartdatadiscovery class get predictions on salesforce objects. socialengagement class manage information about social accounts or fan pages for social networks. surveys class send survey invitations by email. taxplatform class apply or cancel tax. 384apex reference guide actionlinks class topics class access information about topics, such as their descriptions, the number of people talking about them, related topics, and information about groups contributing to the topic. update a topic’s name or description, merge topics, and add and remove topics from records and feed items. userprofiles class access user profile data. the user profile data populates the profile page (also called the chatter profile page). this data includes user information (such as address, manager, and phone number), some user capabilities (permissions), and a set of subtab apps, which are custom tabs on the profile page. zones class access information about chatter answers zones in your organization. zones organize questions into logical groups, with each zone having its own focus and unique questions. connectapi input classes some connectapi methods take arguments that are instances of connectapi input classes. connectapi output classes most connectapi methods return instances of connectapi output classes. connectapi en |
ums enums specific to the connectapi namespace. connectapi exceptions the connectapi namespace contains exception classes. connectapi utilities the connectapi namespace contains a utility class. connectapi release notes use the salesforce release notes to learn about the most recent updates and changes to the connectapi namespace in apex. actionlinks class create, delete, and get information about an action link group definition; get information about an action link group; get action link diagnostic information. namespace connectapi usage an action link is a button on a feed element. clicking an action link can take a user to a web page, initiate a file download, or invoke an api call to salesforce or to an external server. an action link includes a url and an http method, and can include a request body and header information, such as an oauth token for authentication. use action links to integrate salesforce and third-party services into the feed so that users can drive productivity and accelerate innovation. there are two views of an action link and an action link group: the definition, and the context user’s view. the definition includes potentially sensitive information, such as authentication information. the context user’s view is filtered by visibility options and the values reflect the state of the context user. action link definition can be sensitive to a third party (for example, oauth bearer token headers). for this reason, only calls made from the apex namespace that created the action link definition can read, modify, or delete the definition. in addition, the user making the 385apex reference guide actionlinks class call must have created the definition or have view all data permission. use these methods to operate on action link group definitions (which contain action link definitions). • createactionlinkgroupdefinition(communityid, actionlinkgroup) • deleteactionlinkgroupdefinition(communityid, actionlinkgroupid) • getactionlinkgroupdefinition(communityid, actionlinkgroupid) use these methods to operate on a context user’s view of an action link or an action link group. • getactionlink(communityid, actionlinkid) • getactionlinkgroup(communityid, actionlinkgroupid) • getactionlinkdiagnosticinfo(communityid, actionlinkid) for information about how to use action links, see working with action links. actionlinks methods these are methods for actionlinks. all methods are static. in this section: createactionlinkgroupdefinition(communityid, actionlinkgroup) create an action link group definition. to associate an action link group with a feed element, first create an action link group definition. then post a feed element with an associated actions capability. deleteactionlinkgroupdefinition(communityid, actionlinkgroupid) delete an action link group definition. deleting an action link group definition removes all references to it from feed elements. getactionlink(communityid, actionlinkid) get information about an action link, including state for the context user. getactionlinkdiagnosticinfo(communityid, actionlinkid) get diagnostic information returned when an action link executes. diagnostic information is given only for users who can access the action link. getactionlinkgroup(communityid, actionlinkgroupid) get information about an action link group including state for the context user. getactionlinkgroupdefinition(communityid, actionlinkgroupid) get information about an action link group definition. createactionlinkgroupdefinition(communityid, actionlinkgroup) create an action link group definition. to associate an action link group with a feed element, first create an action link group definition. then post a feed element with an associated actions capability. api version 33.0 requires chatter no 386apex reference guide actionlinks class signature public static connectapi.actionlinkgroupdefinition createactionlinkgroupdefinition(string communityid, connectapi.actionlinkgroupdefinitioninput actionlinkgroup) parameters communityid type: string id for an experience cloud site, internal, or null. actionlinkgroup type: connectapi.actionlinkgroupdefinitioninput a connectapi.actionlinkgroupdefinitioninput object that defines the action link group. return value type: connectapi.actionlinkgroupdefinition usage an action link is a button on a feed element. clicking an action link can take a user to a web page, initiate a file download, or invoke an api call to salesforce or to an external server. an action link includes a url and an http method, and can include a request body and header information, such as an oauth token for authentication. use action links to integrate salesforce and |
third-party services into the feed so that users can drive productivity and accelerate innovation. all action links must belong to a group. action links in a group are mutually exclusive and share some properties. define standalone actions in their own action group. information in the action link group definition can be sensitive to a third party (for example, oauth bearer token headers). for this reason, only calls made from the apex namespace that created the action link group definition can read, modify, or delete the definition. in addition, the user making the call must have created the definition or have view all data permission. note: invoking apiasync action links from an app requires a call to set the status. however, there isn’t currently a way to set the status of an action link using apex. to set the status, use connect rest api. see the action link resource in the connect rest api developer guide for more information. example for defining an action link and posting with a feed element for more information about this example, see define an action link and post with a feed element. connectapi.actionlinkgroupdefinitioninput actionlinkgroupdefinitioninput = new connectapi.actionlinkgroupdefinitioninput(); connectapi.actionlinkdefinitioninput actionlinkdefinitioninput = new connectapi.actionlinkdefinitioninput(); connectapi.requestheaderinput requestheaderinput1 = new connectapi.requestheaderinput(); connectapi.requestheaderinput requestheaderinput2 = new connectapi.requestheaderinput(); // create the action link group definition. actionlinkgroupdefinitioninput.actionlinks = new list<connectapi.actionlinkdefinitioninput>(); actionlinkgroupdefinitioninput.executionsallowed = connectapi.actionlinkexecutionsallowed.onceperuser; actionlinkgroupdefinitioninput.category = connectapi.platformactiongroupcategory.primary; 387apex reference guide actionlinks class // to do: verify that the date is in the future. // action link groups are removed from feed elements on the expiration date. datetime mydate = datetime.newinstance(2016, 3, 1); actionlinkgroupdefinitioninput.expirationdate = mydate; // create the action link definition. actionlinkdefinitioninput.actiontype = connectapi.actionlinktype.api; actionlinkdefinitioninput.actionurl = '/services/data/v33.0/chatter/feed-elements'; actionlinkdefinitioninput.headers = new list<connectapi.requestheaderinput>(); actionlinkdefinitioninput.labelkey = 'post'; actionlinkdefinitioninput.method = connectapi.httprequestmethod.httppost; actionlinkdefinitioninput.requestbody = '{\"subjectid\": \"me\",\"feedelementtype\": \"feeditem\",\"body\": {\"messagesegments\": [{\"type\": \"text\",\"text\": \"this is a test post created via an api action link.\"}]}}'; actionlinkdefinitioninput.requiresconfirmation = true; // to do: substitute an oauth value for your salesforce org. requestheaderinput1.name = 'authorization'; requestheaderinput1.value = 'oauth 00dd00000007wnp!arsaqcwoev0zzav847ftl4zf.85w.ewspbugxr4sajsp'; actionlinkdefinitioninput.headers.add(requestheaderinput1); requestheaderinput2.name = 'content-type'; requestheaderinput2.value = 'application/json'; actionlinkdefinitioninput.headers.add(requestheaderinput2); // add the action link definition to the action link group definition. actionlinkgroupdefinitioninput.actionlinks.add(actionlinkdefinitioninput); // instantiate the action link group definition. connectapi.actionlinkgroupdefinition actionlinkgroupdefinition = connectapi.actionlinks.createactionlinkgroupdefinition(network.getnetworkid(), actionlinkgroupdefinitioninput); connectapi.feediteminput feediteminput = new connectapi.feediteminput(); connectapi.feedelementcapabilitiesinput feedelementcapabilitiesinput = new connectapi.feedelementcapabilitiesinput(); connectapi.associatedactionscapabilityinput associatedactionscapabilityinput = new connectapi.associatedactionscapabilityinput(); connectapi.messagebodyinput messagebodyinput = new connectapi.messagebodyinput(); connectapi.textsegmentinput textsegmentinput = new connectapi.textsegmentinput(); // set the properties of the feediteminput |
object. feediteminput.body = messagebodyinput; feediteminput.capabilities = feedelementcapabilitiesinput; feediteminput.subjectid = 'me'; // create the text for the post. messagebodyinput.messagesegments = new list<connectapi.messagesegmentinput>(); textsegmentinput.text = 'click to post a feed item.'; messagebodyinput.messagesegments.add(textsegmentinput); // the feedelementcapabilitiesinput object holds the capabilities of the feed item. 388apex reference guide actionlinks class // define an associated actions capability to hold the action link group. // the action link group id is returned from the call to create the action link group definition. feedelementcapabilitiesinput.associatedactions = associatedactionscapabilityinput; associatedactionscapabilityinput.actionlinkgroupids = new list<string>(); associatedactionscapabilityinput.actionlinkgroupids.add(actionlinkgroupdefinition.id); // post the feed item. connectapi.feedelement feedelement = connectapi.chatterfeeds.postfeedelement(network.getnetworkid(), feediteminput); example for defining an action link in a template and posting with a feed element for more information about this example, see define an action link in a template and post with a feed element. // get the action link group template id. actionlinkgrouptemplate template = [select id from actionlinkgrouptemplate where developername='doc_example']; // add binding name-value pairs to a map. // the names are defined in the action link template(s) associated with the action link group template. // get them from setup ui or soql. map<string, string> bindingmap = new map<string, string>(); bindingmap.put('apiversion', 'v33.0'); bindingmap.put('text', 'this post was created by an api action link.'); bindingmap.put('subjectid', 'me'); // create actionlinktemplatebindinginput objects from the map elements. list<connectapi.actionlinktemplatebindinginput> bindinginputs = new list<connectapi.actionlinktemplatebindinginput>(); for (string key : bindingmap.keyset()) { connectapi.actionlinktemplatebindinginput bindinginput = new connectapi.actionlinktemplatebindinginput(); bindinginput.key = key; bindinginput.value = bindingmap.get(key); bindinginputs.add(bindinginput); } // set the template id and template binding values in the action link group definition. connectapi.actionlinkgroupdefinitioninput actionlinkgroupdefinitioninput = new connectapi.actionlinkgroupdefinitioninput(); actionlinkgroupdefinitioninput.templateid = template.id; actionlinkgroupdefinitioninput.templatebindings = bindinginputs; // instantiate the action link group definition. connectapi.actionlinkgroupdefinition actionlinkgroupdefinition = connectapi.actionlinks.createactionlinkgroupdefinition(network.getnetworkid(), actionlinkgroupdefinitioninput); connectapi.feediteminput feediteminput = new connectapi.feediteminput(); connectapi.feedelementcapabilitiesinput feedelementcapabilitiesinput = new connectapi.feedelementcapabilitiesinput(); 389apex reference guide actionlinks class connectapi.associatedactionscapabilityinput associatedactionscapabilityinput = new connectapi.associatedactionscapabilityinput(); connectapi.messagebodyinput messagebodyinput = new connectapi.messagebodyinput(); connectapi.textsegmentinput textsegmentinput = new connectapi.textsegmentinput(); // define the feediteminput object to pass to postfeedelement feediteminput.body = messagebodyinput; feediteminput.capabilities = feedelementcapabilitiesinput; feediteminput.subjectid = 'me'; // the messagebodyinput object holds the text in the post messagebodyinput.messagesegments = new list<connectapi.messagesegmentinput>(); textsegmentinput.text = 'click to post a feed item.'; messagebodyinput.messagesegments.add(textsegmentinput); // the feedelementcapabilitiesinput object holds the capabilities of the feed item. // for this feed item, we define an associated actions capability to hold the action link group. // the action link group id is returned from the call to create the action link group definition. feedelementcapabilitiesinput.associatedactions |
= associatedactionscapabilityinput; associatedactionscapabilityinput.actionlinkgroupids = new list<string>(); associatedactionscapabilityinput.actionlinkgroupids.add(actionlinkgroupdefinition.id); // post the feed item. connectapi.feedelement feedelement = connectapi.chatterfeeds.postfeedelement(network.getnetworkid(), feediteminput); deleteactionlinkgroupdefinition(communityid, actionlinkgroupid) delete an action link group definition. deleting an action link group definition removes all references to it from feed elements. api version 33.0 requires chatter no signature public static void deleteactionlinkgroupdefinition(string communityid, string actionlinkgroupid) parameters communityid type: string id for an experience cloud site, internal, or null. 390apex reference guide actionlinks class actionlinkgroupid type: string the id of the action link group. return value type: void usage information in the action link group definition can be sensitive to a third party (for example, oauth bearer token headers). for this reason, only calls made from the apex namespace that created the action link group definition can read, modify, or delete the definition. in addition, the user making the call must have created the definition or have view all data permission. getactionlink(communityid, actionlinkid) get information about an action link, including state for the context user. api version 33.0 requires chatter no signature public static connectapi.platformaction getactionlink(string communityid, string actionlinkid) parameters communityid type: string id for an experience cloud site, internal, or null. actionlinkid type: string the id of the action link. return value type: connectapi.platformaction getactionlinkdiagnosticinfo(communityid, actionlinkid) get diagnostic information returned when an action link executes. diagnostic information is given only for users who can access the action link. 391apex reference guide actionlinks class api version 33.0 requires chatter no signature public static connectapi.actionlinkdiagnosticinfo getactionlinkdiagnosticinfo(string communityid, string actionlinkid) parameters communityid type: string id for an experience cloud site, internal, or null. actionlinkid type: string the id of the action link. return value type: connectapi.actionlinkdiagnosticinfo getactionlinkgroup(communityid, actionlinkgroupid) get information about an action link group including state for the context user. api version 33.0 requires chatter no signature public static connectapi.platformactiongroup getactionlinkgroup(string communityid, string actionlinkgroupid) parameters communityid type: string id for an experience cloud site, internal, or null. 392apex reference guide actionlinks class actionlinkgroupid type: string the id of the action link group. return value type: connectapi.platformactiongroup usage all action links must belong to a group. action links in a group are mutually exclusive and share some properties. action link groups are accessible by clients, unlike action link group definitions. getactionlinkgroupdefinition(communityid, actionlinkgroupid) get information about an action link group definition. api version 33.0 requires chatter no signature public static connectapi.actionlinkgroupdefinition getactionlinkgroupdefinition(string communityid, string actionlinkgroupid) parameters communityid type: string id for an experience cloud site, internal, or null. actionlinkgroupid type: string the id of the action link group. return value type: connectapi.actionlinkgroupdefinition usage information in the action link group definition can be sensitive to a third party (for example, oauth bearer token headers). for this reason, only calls made from the apex namespace that created the action link group definition can read, modify, or delete the definition. in addition, the user making the call must have created the definition or have view all data permission. 393apex reference guide announcements class announcements class access information about announcements and post announcements. namespace connectapi usage use the connectapi.announcements class to get, create, update, and delete announcements. use an announcement to highlight information. users can discuss, like, and post comments on announcements. deleting the feed |
post deletes the announcement. this image shows an announcement displayed in a group. creating an announcement also creates a feed item with the announcement text. an announcement displays in a designated location in the salesforce ui until 11:59 p.m. on its expiration date, unless it’s deleted or replaced by another announcement. announcements methods the following are methods for announcements. all methods are static. in this section: deleteannouncement(communityid, announcementid) delete an announcement. getannouncement(communityid, announcementid) get an announcement. 394apex reference guide announcements class getannouncements(communityid, parentid) get the first page of announcements. getannouncements(communityid, parentid, pageparam, pagesize) get a page of announcements. postannouncement(communityid, announcement) post an announcement. updateannouncement(communityid, announcementid, expirationdate) update the expiration date of an announcement. deleteannouncement(communityid, announcementid) delete an announcement. api version 31.0 requires chatter yes signature public static void deleteannouncement(string communityid, string announcementid) parameters communityid type: string id for an experience cloud site, internal, or null. announcementid type: string an announcement id, which has a prefix of 0bt. return value type: void usage to get a list of announcements in a group, call getannouncements(communityid, parentid) or getannouncements(communityid, parentid, pageparam, pagesize). to post an announcement to a group, call postannouncement(communityid, announcement) . getannouncement(communityid, announcementid) get an announcement. 395apex reference guide announcements class api version 31.0 requires chatter yes signature public static connectapi.announcement getannouncement(string communityid, string announcementid) parameters communityid type: string id for an experience cloud site, internal, or null. announcementid type: string an announcement id, which has a prefix of 0bt. return value type: connectapi.announcement usage to get a list of announcements in a group, call getannouncements(communityid, parentid) or getannouncements(communityid, parentid, pageparam, pagesize). to post an announcement to a group, call postannouncement(communityid, announcement) . getannouncements(communityid, parentid) get the first page of announcements. api version 36.0 available to guest users 38.0 requires chatter yes 396apex reference guide announcements class signature public static connectapi.announcementpage getannouncements(string communityid, string parentid) parameters communityid type: string id for an experience cloud site, internal, or null. parentid type: string id of the parent entity for the announcement, that is, a group id when the announcement appears in a group. return value type: connectapi.announcementpage getannouncements(communityid, parentid, pageparam, pagesize) get a page of announcements. api version 36.0 available to guest users 38.0 requires chatter yes signature public static connectapi.announcementpage getannouncements(string communityid, string parentid, integer pageparam, integer pagesize) parameters communityid type: string id for an experience cloud site, internal, or null. parentid type: string id of the parent entity for the announcement, that is, a group id when the announcement appears in a group. pageparam type: integer 397apex reference guide announcements class number of the page you want returned. starts at 0. if you pass in null or 0, the first page is returned. pagesize type: integer specifies the number of announcements per page. return value type: connectapi.announcementpage postannouncement(communityid, announcement) post an announcement. api version 36.0 requires chatter yes signature public static connectapi.announcement postannouncement(string communityid, connectapi.announcementinput announcement) parameters communityid type: string id for an experience cloud site, internal, or null. announcement |
type: connectapi.announcementinput a connectapi.announcementinput object. return value type: connectapi.announcement updateannouncement(communityid, announcementid, expirationdate) update the expiration date of an announcement. api version 31.0 398apex reference guide botversionactivation class requires chatter yes signature public static connectapi.announcement updateannouncement(string communityid, string announcementid, datetime expirationdate) parameters communityid type: string id for an experience cloud site, internal, or null. announcementid type: string an announcement id, which has a prefix of 0bt. expirationdate type: datetime the salesforce ui displays an announcement until 11:59 p.m. on this date unless another announcement is posted first. the salesforce ui ignores the time value in the expirationdate. however, you can use the time value to create your own display logic in your own ui. return value type: connectapi.announcement usage to get a list of announcements in a group, call getannouncements(communityid, parentid) or getannouncements(communityid, parentid, pageparam, pagesize). to post an announcement to a group, call postannouncement(communityid, announcement) . botversionactivation class access and update activation information of a bot version. namespace connectapi botversionactivation methods the following are methods for botversionactivation. all methods are static. 399apex reference guide botversionactivation class in this section: getversionactivationinfo(botversionid) get the active or inactive status of the bot version. updateversionstatus(botversionid, status, postbody) update the status of the specified bot version. getversionactivationinfo(botversionid) get the active or inactive status of the bot version. api version 50.0 requires chatter no signature public static connectapi.botversionactivationinfo getversionactivationinfo(string botversionid) parameters botversionid type: string id of the bot version. return value type: connectapi.botversionactivationinfo usage to access this method, enable the bot feature, and the user must be an admin or have the manage bots or manage bots training data user permissions. updateversionstatus(botversionid, status, postbody) update the status of the specified bot version. api version 50.0 requires chatter no 400apex reference guide cdpcalculatedinsight class signature public static connectapi.botversionactivationinfo updateversionstatus(string botversionid, connectapi.botversionactivationstatus status, connectapi.botversionactivationinput postbody) parameters botversionid type: string id of the bot version. status type: connectapi.botversionactivationstatus activation status of the bot version. values are: • active • inactive activation status must be specified in the status or postbody parameter. postbody type: connectapi.botversionactivationinput parameters to update for the bot version. activation status must be specified in the status or postbody parameter. return value type: connectapi.botversionactivationinfo usage to access this method, enable the bot feature, and the user must be an admin or have the manage bots or manage bots training data user permissions. cdpcalculatedinsight class create, delete, get, run, and update data cloud calculated insights. namespace connectapi cdpcalculatedinsight methods the following are methods for cdpcalculatedinsight. all methods are static. in this section: createcalculatedinsight(input) create a calculated insight. 401apex reference guide cdpcalculatedinsight class deletecalculatedinsight(apiname) delete a calculated insight. getcalculatedinsight(apiname) get a calculated insight. getcalculatedinsights(definitiontype, batchsize, offset, orderby, dataspace) get calculated insights. getcalculatedinsights(definitiontype, batchsize, offset, orderby, dataspace, pagetoken) get a page of calculated insights. runcalculatedinsight(apiname) run a calculated insight. updatecalculatedinsight(apiname, input) update a calculated insight. createcalculatedinsight( |
input) create a calculated insight. api version 57.0 requires chatter no signature public static connectapi.cdpcalculatedinsightoutput createcalculatedinsight(connectapi.cdpcalculatedinsightinput input) parameters input type: connectapi.cdpcalculatedinsightinput input representation for a calculated insight. return value type: connectapi.cdpcalculatedinsightoutput deletecalculatedinsight(apiname) delete a calculated insight. api version 57.0 402apex reference guide cdpcalculatedinsight class requires chatter no signature public static void deletecalculatedinsight(string apiname) parameters apiname type: string api name of the calculated insight to delete. return value type: void getcalculatedinsight(apiname) get a calculated insight. api version 57.0 requires chatter no signature public static connectapi.cdpcalculatedinsightoutput getcalculatedinsight(string apiname) parameters apiname type: string api name of the calculated insight to get. return value type: connectapi.cdpcalculatedinsightoutput getcalculatedinsights(definitiontype, batchsize, offset, orderby, dataspace) get calculated insights. api version 56.0 403apex reference guide cdpcalculatedinsight class requires chatter no signature public static connectapi.cdpcalculatedinsightpage getcalculatedinsights(string definitiontype, integer batchsize, integer offset, string orderby, string dataspace) parameters definitiontype type: string definition type of the calculated insight. values are: • calculatedmetric • externalmetric • streamingmetric batchsize type: integer number of items to return. values are from 1–300. if unspecified, the default value is 25. offset type: integer number of rows to skip before returning results. if unspecified, no rows are skipped. orderby type: string sort order for the result set, such as genderid__c asc,occupation__c desc. if unspecified, items are returned in the order they are retrieved. dataspace type: string name of the data space. return value type: connectapi.cdpcalculatedinsightpage getcalculatedinsights(definitiontype, batchsize, offset, orderby, dataspace, pagetoken) get a page of calculated insights. api version 57.0 requires chatter no 404apex reference guide cdpcalculatedinsight class signature public static connectapi.cdpcalculatedinsightpage getcalculatedinsights(string definitiontype, integer batchsize, integer offset, string orderby, string dataspace, string pagetoken) parameters definitiontype type: string definition type of the calculated insight. values are: • calculatedmetric • externalmetric • streamingmetric batchsize type: integer number of items to return. values are from 1–300. if unspecified, the default value is 25. offset type: integer number of rows to skip before returning results. if unspecified, no rows are skipped. orderby type: string sort order for the result set, such as genderid__c asc,occupation__c desc. if unspecified, items are returned in the order they are retrieved. dataspace type: string name of the data space. pagetoken type: string specifies the page token to use to view a page of information. page tokens are returned as part of the response class, such as currentpagetoken or nextpagetoken. if you pass in null, the first page is returned. return value type: connectapi.cdpcalculatedinsightpage runcalculatedinsight(apiname) run a calculated insight. api version 57.0 405apex reference guide cdpcalculatedinsight class requires chatter no signature public static connectapi.cdpcalculatedinsightstandardactionesponserepresentation runcalculatedinsight(string apiname) parameters apiname type: string api name of the calculated insight to run. return value type: connectapi.cdpcalculatedinsightstandardactionresponserepresentation updatecalculatedinsight(apiname, input) update a calculated insight. api version 57.0 requires chatter no signature public static |
connectapi.cdpcalculatedinsightoutput updatecalculatedinsight(string apiname, connectapi.cdpcalculatedinsightinput input) parameters apiname type: string api name of the calculated insight to update. input type: connectapi.cdpcalculatedinsightinput input representation for a calculated insight. return value type: connectapi.cdpcalculatedinsightoutput 406apex reference guide cdpidentityresolution class cdpidentityresolution class create, delete, get, run, and update data cloud identity resolution rulesets. namespace connectapi cdpidentityresolution methods the following are methods for cdpidentityresolution. all methods are static. in this section: createidentityresolution(input) create an identity resolution ruleset. deleteidentityresolution(identityresolution) delete an identity resolution ruleset. getidentityresolution(identityresolution) get an identity resolution ruleset. getidentityresolutions() get identity resolution rulesets. runidentityresolutionnow(identityresolution, input) trigger an immediate identity resolution ruleset job run. updateidentityresolution(identityresolution, input) update an identity resolution ruleset. createidentityresolution(input) create an identity resolution ruleset. api version 57.0 requires chatter no signature public static connectapi.cdpidentityresolutionoutput createidentityresolution(connectapi.cdpidentityresolutionconfiginput input) parameters input type: connectapi.cdpidentityresolutionconfiginput 407apex reference guide cdpidentityresolution class input representation for creating an identity resolution ruleset. return value type: connectapi.cdpidentityresolutionoutput deleteidentityresolution(identityresolution) delete an identity resolution ruleset. api version 57.0 requires chatter no signature public static void deleteidentityresolution(string identityresolution) parameters identityresolution type: string developer name or id of the ruleset. return value type: void getidentityresolution(identityresolution) get an identity resolution ruleset. api version 57.0 requires chatter no signature public static connectapi.cdpidentityresolutionoutput getidentityresolution(string identityresolution) 408apex reference guide cdpidentityresolution class parameters identityresolution type: string developer name or id of the ruleset. return value type: connectapi.cdpidentityresolutionoutput getidentityresolutions() get identity resolution rulesets. api version 57.0 requires chatter no signature public static connectapi.cdpidentityresolutionsoutput getidentityresolutions() return value type: connectapi.cdpidentityresolutionsoutput runidentityresolutionnow(identityresolution, input) trigger an immediate identity resolution ruleset job run. api version 57.0 requires chatter no signature public static connectapi.cdpidentityresolutionrunnowoutput runidentityresolutionnow(string identityresolution, connectapi.cdpidentityresolutionrunnowinput input) 409apex reference guide cdpquery class parameters identityresolution type: string developer name of the ruleset. input type: connectapi.cdpidentityresolutionrunnowinput input representation for running an identity resolution ruleset job on demand. return value type: connectapi.cdpidentityresolutionrunnowoutput updateidentityresolution(identityresolution, input) update an identity resolution ruleset. api version 57.0 requires chatter no signature public static connectapi.cdpidentityresolutionoutput updateidentityresolution(string identityresolution, connectapi.cdpidentityresolutionconfigpatchinput input) parameters identityresolution type: string developer name or id of the ruleset. input type: connectapi.cdpidentityresolutionconfigpatchinput input representation for updating an identity resolution ruleset. return value type: connectapi.cdpidentityresolutionoutput cdpquery class get data cloud metadata and query data. 410apex reference guide cdpquery class namespace connectapi |
cdpquery methods the following are methods for cdpquery. all methods are static. in this section: getallmetadata() get all metadata, including calculated insights, engagement, profile, and other objects, as well as their relationships to other objects. getallmetadata(entitytype, entitycategory, entityname) get all metadata, filtering for entity type, category, and name. getinsightsmetadata() get insight metadata, including calculated insight objects, their dimensions and measures. getinsightsmetadata(ciname) get metadata for a calculated insight object. metadata includes dimensions and measures. getprofilemetadata() get metadata for data model objects in the profile category, including individual, contact point email, unified individual, and contact point address objects. metadata includes the objects, their fields, and category. getprofilemetadata(datamodelname) get metadata for a data model object in the profile category, such as individual, contact point email, unified individual, and contact point address. metadata includes the list of fields, data types, and indexes available for lookup. nextbatchansisqlv2(nextbatchid) get the next batch of data across data model, lake, unified, and linked objects. queryansisql(input) synchronously query data across data model, lake, unified, and linked objects.this query returns up to 4,999 rows. queryansisql(input, batchsize, offset, orderby) synchronously query data across data model, lake, unified, and linked objects. specify batch size, offset, and order of the results. this query returns up to 4,999 rows. queryansisqlv2(input) query up to 8 mb of data across data model, lake, unified, and linked objects. querycalculatedinsights(ciname, dimensions, measures, orderby, filters, batchsize, offset) query a calculated insight object. querycalculatedinsights(ciname, dimensions, measures, orderby, filters, batchsize, offset, timegranularity) query a calculated insight object within a specified time range. queryprofileapi(datamodelname, filters, fields, batchsize, offset, orderby) query a profile data model object using filters. queryprofileapi(datamodelname, id, searchkey, filters, fields, batchsize, offset, orderby) query a profile data model object using filters and a search key. queryprofileapi(datamodelname, id, childdatamodelname, searchkey, filters, fields, batchsize, offset, orderby) query a profile data model object and a child object using filters and a search key. 411apex reference guide cdpquery class queryprofileapi(datamodelname, id, ciname, searchkey, dimensions, measures, filters, fields, batchsize, offset, orderby) query a profile data model object and a calculated insight object using filters and a search key. queryprofileapi(datamodelname, id, ciname, searchkey, dimensions, measures, filters, fields, batchsize, offset, orderby, timegranularity) query a profile data model object and a calculated insight object using filters, a search key, and a time range. universalidlookupbysourceid(entityname, datasourceid, datasourceobjectid, sourcerecordid) look up objects by source id. getallmetadata() get all metadata, including calculated insights, engagement, profile, and other objects, as well as their relationships to other objects. api version 52.0 requires chatter no signature public static connectapi.cdpquerymetadataoutput getallmetadata() return value type: connectapi.cdpquerymetadataoutput getallmetadata(entitytype, entitycategory, entityname) get all metadata, filtering for entity type, category, and name. api version 54.0 requires chatter no signature public static connectapi.cdpquerymetadataoutput getallmetadata(string entitytype, string entitycategory, string entityname) parameters entitytype type: string 412apex reference guide cdpquery class type of metadata entity requested. valid values are datalakeobject, datamodelobject, and calculatedinsight. if unspecified, all types are returned. entitycategory type: string category of the metadata entity. valid values are profile, engagement, and related. if unspecified, all category entities are returned. entityname type: string metadata name |
of the entity, for example unifiedindividual__dlm. if unspecified, a complete list of entities is returned. return value type: connectapi.cdpquerymetadataoutput getinsightsmetadata() get insight metadata, including calculated insight objects, their dimensions and measures. api version 52.0 requires chatter no signature public static connectapi.cdpquerymetadataoutput getinsightsmetadata() return value type: connectapi.cdpquerymetadataoutput getinsightsmetadata(ciname) get metadata for a calculated insight object. metadata includes dimensions and measures. api version 52.0 requires chatter no signature public static connectapi.cdpquerymetadataoutput getinsightsmetadata(string ciname) 413apex reference guide cdpquery class parameters ciname type: string name of the calculated insight object, for example, individualchildrencount__cio. return value type: connectapi.cdpquerymetadataoutput getprofilemetadata() get metadata for data model objects in the profile category, including individual, contact point email, unified individual, and contact point address objects. metadata includes the objects, their fields, and category. api version 52.0 requires chatter no signature public static connectapi.cdpquerymetadataoutput getprofilemetadata() return value type: connectapi.cdpquerymetadataoutput getprofilemetadata(datamodelname) get metadata for a data model object in the profile category, such as individual, contact point email, unified individual, and contact point address. metadata includes the list of fields, data types, and indexes available for lookup. api version 52.0 requires chatter no signature public static connectapi.cdpquerymetadataoutput getprofilemetadata(string datamodelname) 414apex reference guide cdpquery class parameters datamodelname type: string name of the data model object, for example, unifiedindividual__dlm. return value type: connectapi.cdpquerymetadataoutput nextbatchansisqlv2(nextbatchid) get the next batch of data across data model, lake, unified, and linked objects. api version 54.0 requires chatter no signature public static connectapi.cdpqueryoutputv2 nextbatchansisqlv2(string nextbatchid) parameters nextbatchid type: string id of the next batch. see the usage section for more information. return value type: connectapi.cdpqueryoutputv2 usage initially, use the queryansisqlv2(input) method to query up to 8 mb of data. use the nextbatchid from the connectapi.cdpqueryoutputv2 output class as the nextbatchid parameter in this method to get the next batch of data. you can continue using subsequent next batch ids for up to an hour. queryansisql(input) synchronously query data across data model, lake, unified, and linked objects.this query returns up to 4,999 rows. note: a newer version of the query api is available. we recommend using queryansisqlv2(input) and nextbatchansisqlv2(nextbatchid) to take advantage of subsequent requests and larger response sizes. 415apex reference guide cdpquery class api version 52.0 requires chatter no signature public static connectapi.cdpqueryoutput queryansisql(connectapi.cdpqueryinput input) parameters input type: connectapi.cdpqueryinput a connectapi.cdpqueryinput body with the sql query. return value type: connectapi.cdpqueryoutput queryansisql(input, batchsize, offset, orderby) synchronously query data across data model, lake, unified, and linked objects. specify batch size, offset, and order of the results. this query returns up to 4,999 rows. note: a newer version of the query api is available. we recommend using queryansisqlv2(input) and nextbatchansisqlv2(nextbatchid) to take advantage of subsequent requests and larger response sizes. api version 53.0 requires chatter no signature public static connectapi.cdpqueryoutput queryansisql(connectapi.cdpqueryinput |
input, integer batchsize, integer offset, string orderby) parameters input type: connectapi.cdpqueryinput a connectapi.cdpqueryinput body with the sql query. batchsize type: integer 416apex reference guide cdpquery class number of records to return. values are from 1–4999. the default value is 4999. offset type: integer number of rows to skip before returning results. the sum of offset and batchsize must be less than 2147483647. the default value is 0. orderby type: string comma-separated values to sort the results in ascending or descending order, for example, genderid__c asc,occupation__c desc. return value type: connectapi.cdpqueryoutput queryansisqlv2(input) query up to 8 mb of data across data model, lake, unified, and linked objects. api version 54.0 requires chatter no signature public static connectapi.cdpqueryoutputv2 queryansisqlv2(connectapi.cdpqueryinput input) parameters input type: connectapi.cdpqueryinput a connectapi.cdpqueryinput body with the sql query. return value type: connectapi.cdpqueryoutputv2 usage use the nextbatchid in the connectapi.cdpqueryoutputv2 output class as the nextbatchid parameter in the nextbatchansisqlv2(nextbatchid) method to continue getting batches of data for up to an hour. querycalculatedinsights(ciname, dimensions, measures, orderby, filters, batchsize, offset) query a calculated insight object. 417apex reference guide cdpquery class api version 52.0 requires chatter no signature public static connectapi.cdpqueryoutput querycalculatedinsights(string ciname, string dimensions, string measures, string orderby, string filters, integer batchsize, integer offset) parameters ciname type: string name of the calculated insight object, for example, individualchildrencount__cio. dimensions type: string comma-separated list of up to 10 dimensions, such as genderid__c, to project. if unspecified, this parameter includes all of the available dimensions. measures type: string comma-separated list of up to 5 measures, such as totalsales__c, to project. if unspecified, this parameter includes all of the available measures. orderby type: string sort order for the result set, such as genderid__c asc,occupation__c desc. if unspecified, items are returned in the order they are retrieved. filters type: string filter the result set to a more narrow scope or specific type, such as [genderid__c=male,firstname__c=angel]. batchsize type: integer number of items to return. values are from 1–4,999. if unspecified, the default value is 4999. offset type: integer number of rows to skip before returning results. if unspecified, no rows are skipped. return value type: connectapi.cdpqueryoutput 418apex reference guide cdpquery class querycalculatedinsights(ciname, dimensions, measures, orderby, filters, batchsize, offset, timegranularity) query a calculated insight object within a specified time range. api version 54.0 requires chatter no signature public static connectapi.cdpqueryoutput querycalculatedinsights(string ciname, string dimensions, string measures, string orderby, string filters, integer batchsize, integer offset, string timegranularity) parameters ciname type: string name of the calculated insight object, for example, individualchildrencount__cio. dimensions type: string comma-separated list of up to 10 dimensions, such as genderid__c, to project. if unspecified, this parameter includes all of the available dimensions. measures type: string comma-separated list of up to 5 measures, such as totalsales__c, to project. if unspecified, this parameter includes all of the available measures. orderby type: string sort order for the result set, such as genderid__c asc,occupation__c desc. if unspecified, items are returned in the order they are retrieved. filters type: string filter the result set |
to a more narrow scope or specific type, such as [genderid__c=male,firstname__c=angel]. batchsize type: integer number of items to return. values are from 1–4,999. if unspecified, the default value is 4999. offset type: integer number of rows to skip before returning results. if unspecified, no rows are skipped. 419apex reference guide cdpquery class timegranularity type: string time range for the measures. values are: • hour • day • month • quarter • year if unspecified, no time range is applied. return value type: connectapi.cdpqueryoutput queryprofileapi(datamodelname, filters, fields, batchsize, offset, orderby) query a profile data model object using filters. api version 52.0 requires chatter no signature public static connectapi.cdpqueryoutput queryprofileapi(string datamodelname, string filters, string fields, integer batchsize, integer offset, string orderby) parameters datamodelname type: string name of the data model object, for example, unifiedindividual__dlm. filters type: string comma-separated list of equality expressions within square brackets, for example, [firstname__c=don]. fields type: string comma-separated list of up to 50 field names that you want to include in the result, for example, id__c,firstname__c, genderid__c,occupation__c. if unspecified, an arbitrary set of fields is returned. batchsize type: integer 420apex reference guide cdpquery class number of items to return. values are from 1–4,999. if unspecified, the default value is 100. offset type: integer number of rows to skip before returning results. if unspecified, no rows are skipped. orderby type: string sort order for the result set, such as genderid__c asc,occupation__c desc. if unspecified, items are returned in the order they are retrieved. return value type: connectapi.cdpqueryoutput queryprofileapi(datamodelname, id, searchkey, filters, fields, batchsize, offset, orderby) query a profile data model object using filters and a search key. api version 52.0 requires chatter no signature public static connectapi.cdpqueryoutput queryprofileapi(string datamodelname, string id, string searchkey, string filters, string fields, integer batchsize, integer offset, string orderby) parameters datamodelname type: string name of the data model object, for example, unifiedindividual__dlm. id type: string value of the primary or secondary key field, for example, john. if unspecified, defaults to the value of the primary key field. searchkey type: string if a field other than the primary key is used, name of the key field, for example, firstname__c. filters type: string comma-separated list of equality expressions within square brackets, for example, [firstname__c=don]. 421apex reference guide cdpquery class fields type: string comma-separated list of up to 50 field names that you want to include in the result, for example, id__c,firstname__c, genderid__c,occupation__c. if unspecified, an arbitrary set of fields is returned. batchsize type: integer number of items to return. values are from 1–4,999. if unspecified, the default value is 100. offset type: integer number of rows to skip before returning results. if unspecified, no rows are skipped. orderby type: string sort order for the result set, such as genderid__c asc,occupation__c desc. if unspecified, items are returned in the order they are retrieved. return value type: connectapi.cdpqueryoutput queryprofileapi(datamodelname, id, childdatamodelname, searchkey, filters, fields, batchsize, offset, orderby) query a profile data model object and a child object using filters and a search key. api version 52.0 requires chatter no signature public static connectapi.cdpqueryoutput queryprofileapi(string datamodelname, string id, string childdatamodelname, string searchkey, string filters, string fields, integer batchsize, integer offset, string orderby |
) parameters datamodelname type: string name of the data model object, for example, unifiedindividual__dlm. id type: string value of the primary or secondary key field, for example, john. if unspecified, defaults to the value of the primary key field. 422apex reference guide cdpquery class childdatamodelname type: string name of the child data model object, for example, unifiedcontactpointemail__dlm. searchkey type: string if a field other than the primary key is used, name of the key field, for example, firstname__c. filters type: string comma-separated list of equality expressions within square brackets, for example, [firstname__c=don]. filters are applied to the parent object only. fields type: string comma-separated list of child object field names that you want to include in the result, for example, id__c,emailaddress__c. if unspecified, the first 10 alphabetically sorted fields are returned. batchsize type: integer number of items to return. values are from 1–4,999. if unspecified, the default value is 100. offset type: integer number of rows to skip before returning results. if unspecified, no rows are skipped. orderby type: string sort order for the result set, such as genderid__c asc,occupation__c desc. if unspecified, items are returned in the order they are retrieved. return value type: connectapi.cdpqueryoutput queryprofileapi(datamodelname, id, ciname, searchkey, dimensions, measures, filters, fields, batchsize, offset, orderby) query a profile data model object and a calculated insight object using filters and a search key. api version 52.0 requires chatter no 423apex reference guide cdpquery class signature public static connectapi.cdpqueryoutput queryprofileapi(string datamodelname, string id, string ciname, string searchkey, string dimensions, string measures, string filters, string fields, integer batchsize, integer offset, string orderby) parameters datamodelname type: string name of the data model object, for example, unifiedindividual__dlm. id type: string value of the primary or secondary key field, for example, john. if unspecified, defaults to the value of the primary key field. ciname type: string name of the calculated insight object, for example, individualchildrencount__cio. searchkey type: string if a field other than the primary key is used, name of the key field, for example, firstname__c. dimensions type: string comma-separated list of up to 10 dimensions, such as genderid__c, to project. if unspecified, this parameter includes all of the available dimensions. measures type: string comma-separated list of up to 5 measures, such as totalsales__c, to project. if unspecified, this parameter includes all of the available measures. filters type: string comma-separated list of equality expressions within square brackets, for example, [firstname__c=don]. fields type: string comma-separated list of up to 50 field names that you want to include in the result, for example, id__c,firstname__c, genderid__c,occupation__c. if unspecified, an arbitrary set of fields is returned. batchsize type: integer number of items to return. values are from 1–4,999. if unspecified, the default value is 100. offset type: integer number of rows to skip before returning results. if unspecified, no rows are skipped. orderby type: string 424apex reference guide cdpquery class sort order for the result set, such as genderid__c asc,occupation__c desc. if unspecified, items are returned in the order they are retrieved. return value type: connectapi.cdpqueryoutput queryprofileapi(datamodelname, id, ciname, searchkey, dimensions, measures, filters, fields, batchsize, offset, orderby, timegranularity) query a profile data model object and a calculated insight object using filters, a search key, and a time range. api version 54.0 requires chatter no signature public static connectapi.cdpqueryoutput queryprofileapi(string datamodelname, string id, string ciname, string searchkey |
, string dimensions, string measures, string filters, string fields, integer batchsize, integer offset, string orderby, string timegranularity) parameters datamodelname type: string name of the data model object, for example, unifiedindividual__dlm. id type: string value of the primary or secondary key field, for example, john. if unspecified, defaults to the value of the primary key field. ciname type: string name of the calculated insight object, for example, individualchildrencount__cio. searchkey type: string if a field other than the primary key is used, name of the key field, for example, firstname__c. dimensions type: string comma-separated list of up to 10 dimensions, such as genderid__c, to project. if unspecified, this parameter includes all of the available dimensions. measures type: string 425apex reference guide cdpquery class comma-separated list of up to 5 measures, such as totalsales__c, to project. if unspecified, this parameter includes all of the available measures. filters type: string comma-separated list of equality expressions within square brackets, for example, [firstname__c=don]. fields type: string comma-separated list of up to 50 field names that you want to include in the result, for example, id__c,firstname__c, genderid__c,occupation__c. if unspecified, an arbitrary set of fields is returned. batchsize type: integer number of items to return. values are from 1–4,999. if unspecified, the default value is 100. offset type: integer number of rows to skip before returning results. if unspecified, no rows are skipped. orderby type: string sort order for the result set, such as genderid__c asc,occupation__c desc. if unspecified, items are returned in the order they are retrieved. timegranularity type: string time range for the measures. values are: • hour • day • month • quarter • year if unspecified, no time range is applied. return value type: connectapi.cdpqueryoutput universalidlookupbysourceid(entityname, datasourceid, datasourceobjectid, sourcerecordid) look up objects by source id. api version 54.0 426apex reference guide cdpsegment class requires chatter no signature public static connectapi.cdpquerydataoutput universalidlookupbysourceid(string entityname, string datasourceid, string datasourceobjectid, string sourcerecordid) parameters entityname type: string entity name. datasourceid type: string data source id. datasourceobjectid type: string data source object id. sourcerecordid type: string source record id. return value type: connectapi.cdpquerydataoutput cdpsegment class create, delete, get, publish, and update data cloud segments. namespace connectapi cdpsegment methods the following are methods for cdpsegment. all methods are static. in this section: createsegment(input) create a segment. deletesegment(segmentapiname) delete a segment. 427apex reference guide cdpsegment class executepublishadhoc(segmentid) publish a segment. getsegment(segmentapiname) get a segment. getsegments() get segments. getsegmentspaginated(batchsize, offset, orderby) get an ordered batch of segments. updatesegment(segmentapiname, input) update a segment. createsegment(input) create a segment. api version 55.0 requires chatter no signature public static connectapi.cdpsegmentoutput createsegment(connectapi.cdpsegmentinput input) parameters input type: connectapi.cdpsegmentinput a connectapi.cdpsegmentinput class. return value type: connectapi.cdpsegmentoutput deletesegment(segmentapiname) delete a segment. api version 56.0 428apex reference guide cdpsegment class requires chatter no signature public static void deletesegment(string segmentapiname) parameters segmentapiname type: string api name |
of the segment. return value type: void executepublishadhoc(segmentid) publish a segment. api version 56.0 requires chatter no signature public static connectapi.cdpsegmentactionoutput executepublishadhoc(string segmentid) parameters segmentid type: string id of the segment to publish. return value type: connectapi.cdpsegmentactionoutput getsegment(segmentapiname) get a segment. api version 56.0 429apex reference guide cdpsegment class requires chatter no signature public static connectapi.cdpsegmentcontaineroutput getsegment(string segmentapiname) parameters segmentapiname type: string api name of the segment. return value type: connectapi.cdpsegmentcontaineroutput getsegments() get segments. api version 55.0 requires chatter no signature public static connectapi.cdpsegmentcontaineroutput getsegments() return value type: connectapi.cdpsegmentcontaineroutput getsegmentspaginated(batchsize, offset, orderby) get an ordered batch of segments. api version 56.0 requires chatter no 430apex reference guide cdpsegment class signature public static connectapi.cdpsegmentcontaineroutput getsegmentspaginated(integer batchsize, integer offset, string orderby) parameters batchsize type: integer number of items to return. values are from 1–200. if unspecified, the default value is 20. offset type: integer number of rows to skip before returning results. if unspecified, no rows are skipped. orderby type: string sort order for the result set, such as name asc or marketsegmenttype desc. if unspecified, items are returned by name in ascending order. return value type: connectapi.cdpsegmentcontaineroutput updatesegment(segmentapiname, input) update a segment. api version 56.0 requires chatter no signature public static connectapi.cdpsegmentoutput updatesegment(string segmentapiname, connectapi.cdpsegmentinput input) parameters segmentapiname type: string api name of the segment. input type: connectapi.cdpsegmentinput a connectapi.cdpsegmentinput class with the updates. 431apex reference guide chatter class return value type: connectapi.cdpsegmentoutput chatter class access information about followers and subscriptions for records. namespace connectapi chatter methods the following are methods for chatter. all methods are static. in this section: deletesubscription(communityid, subscriptionid) delete a subscription. use this method to stop following a record, a user, or a file. getfollowers(communityid, recordid) get the first page of followers for a record. getfollowers(communityid, recordid, pageparam, pagesize) get a page of followers for a record. getsubscription(communityid, subscriptionid) get information about a subscription. submitdigestjob(period) submit a daily or weekly chatter email digest job. deletesubscription(communityid, subscriptionid) delete a subscription. use this method to stop following a record, a user, or a file. api version 28.0 requires chatter yes signature public static void deletesubscription(string communityid, string subscriptionid) 432 |
apex reference guide chatter class parameters communityid type: string id for an experience cloud site, internal, or null. subscriptionid type: string the id for a subscription. return value type: void usage “following” a user, group, or record is the same as “subscribing” to a user, group, or record. a “follower” is the user who followed the user, group, or record. a “subscription” is an object describing the relationship between the follower and the user, group, or record they followed. to leave a group, call deletemember(communityid, membershipid). example when you follow a user, the call to connectapi.chatterusers.follow returns a connectapi.subscription object. to stop following the user, pass the id property of that object to this method. connectapi.chatter.deletesubscription(null, '0e8rr0000004cnk0au'); see also: follow a record follow(communityid, userid, subjectid) getfollowers(communityid, recordid) get the first page of followers for a record. api version 28.0 requires chatter yes signature public static connectapi.followerpage getfollowers(string communityid, string recordid) 433apex reference guide chatter class parameters communityid type: string id for an experience cloud site, internal, or null. recordid type: string id for a record or the keyword me. return value type: connectapi.followerpage usage “following” a user, group, or record is the same as “subscribing” to a user, group, or record. a “follower” is the user who followed the user, group, or record. a “subscription” is an object describing the relationship between the follower and the user, group, or record they followed. see also: follow a record getfollowers(communityid, recordid, pageparam, pagesize) get a page of followers for a record. api version 28.0 requires chatter yes signature public static connectapi.followerpage getfollowers(string communityid, string recordid, integer pageparam, integer pagesize) parameters communityid type: string id for an experience cloud site, internal, or null. recordid type: string id for a record or the keyword me. 434apex reference guide chatter class pageparam type: integer number of the page you want returned. starts at 0. if you pass in null or 0, the first page is returned. pagesize type: integer specifies the number of items per page. valid values are from 1 through 100. if you pass in null, the default size is 25. return value type: connectapi.followerpage usage “following” a user, group, or record is the same as “subscribing” to a user, group, or record. a “follower” is the user who followed the user, group, or record. a “subscription” is an object describing the relationship between the follower and the user, group, or record they followed. see also: follow a record getsubscription(communityid, subscriptionid) get information about a subscription. api version 28.0 requires chatter yes signature public static connectapi.subscription getsubscription(string communityid, string subscriptionid) parameters communityid type: string id for an experience cloud site, internal, or null. subscriptionid type: string the id for a subscription. 435apex reference guide chatter class return value type: connectapi.subscription usage “following” a user, group, or record is the same as “subscribing” to a user, group, or record. a “follower” is the user who followed the user, group, or record. a “subscription” is an object describing the relationship between the follower and the user, group, or record they followed. see also: follow a record submitdigestjob(period) submit a daily or weekly chatter email digest job. api version 37.0 requires chatter yes signature public static connectapi.digestjobrepresentation submitdigestjob(connecta |
pi.digestperiod period) parameters period type: connectapi.digestperiod time period that’s included in a chatter email digest. values are: • dailydigest—the email includes up to the 50 latest posts from the previous day. • weeklydigest—the email includes up to the 50 latest posts from the previous week. return value type: connectapi.digestjob usage the times when chatter sends email digests are not configurable in the ui. to control when email digests are sent and to use this method, contact salesforce to enable api-only chatter digests. warning: enabling api-only chatter digests disables the scheduled digests for your org. you must call the api for your users to receive their digests. 436apex reference guide chatterfavorites class we recommend scheduling digest jobs by implementing the apex schedulable interface with this method. to monitor your digest jobs from setup, enter background jobs in the quick find box, then select background jobs. example schedule daily digests: global class exampledigestjob1 implements schedulable { global void execute(schedulablecontext context) { connectapi.chatter.submitdigestjob(connectapi.digestperiod.dailydigest); } } schedule weekly digests: global class exampledigestjob2 implements schedulable { global void execute(schedulablecontext context) { connectapi.chatter.submitdigestjob(connectapi.digestperiod.weeklydigest); } } see also: apex scheduler chatterfavorites class chatter favorites give you easy access to topics, list views, and feed searches. namespace connectapi usage use connect in apex to get and delete topics, list views, and feed searches that have been added as favorites. add topics and feed searches as favorites, and update the last view date of a feed search or list view feed to the current system time. in this image of salesforce, “build issues” is a topic, “all accounts” is a list view, and “united” is a feed search. 437apex reference guide chatterfavorites class chatterfavorites methods the following are methods for chatterfavorites. all methods are static. in this section: addfavorite(communityid, subjectid, searchtext) add a feed search favorite for a user. addrecordfavorite(communityid, subjectid, targetid) add a topic as a favorite. deletefavorite(communityid, subjectid, favoriteid) delete a favorite. getfavorite(communityid, subjectid, favoriteid) get information about a favorite. getfavorites(communityid, subjectid) get a list of favorites for a user. getfeedelements(communityid, subjectid, favoriteid) get the first page of feed elements for a favorite. getfeedelements(communityid, subjectid, favoriteid, pageparam, pagesize, sortparam) get a page of sorted feed elements for a favorite. getfeedelements(communityid, subjectid, favoriteid, recentcommentcount, elementsperbundle, pageparam, pagesize, sortparam) get a page of sorted feed elements for a favorite. include no more than the specified number of comments per feed element. updatefavorite(communityid, subjectid, favoriteid, updatelastviewdate) update the last view date of the saved search or list view feed to the current system time. 438apex reference guide chatterfavorites class addfavorite(communityid, subjectid, searchtext) add a feed search favorite for a user. api version 28.0 requires chatter yes signature public static connectapi.feedfavorite addfavorite(string communityid, string subjectid, string searchtext) parameters communityid type: string id for an experience cloud site, internal, or null. subjectid type: string id of the context user or the alias me. searchtext type: string specify the text of the search to be saved as a favorite. this method can only create a feed search favorite, not a list view favorite or a topic. return value type: connectapi.feedfavorite addrecordfavorite(communityid, subjectid, targetid) add a topic as a favorite. api version 28.0 requires chatter yes 439apex reference guide chatterfavorites class |
signature public static connectapi.feedfavorite addrecordfavorite(string communityid, string subjectid, string targetid) parameters communityid type: string id for an experience cloud site, internal, or null. subjectid type: string id of the context user or the alias me. targetid type: string the id of the topic to add as a favorite. return value type: connectapi.feedfavorite deletefavorite(communityid, subjectid, favoriteid) delete a favorite. api version 28.0 requires chatter yes signature public static void deletefavorite(string communityid, string subjectid, string favoriteid) parameters communityid type: string id for an experience cloud site, internal, or null. subjectid type: string id of the context user or the alias me. favoriteid type: string 440apex reference guide chatterfavorites class id of a favorite. return value type: void getfavorite(communityid, subjectid, favoriteid) get information about a favorite. api version 28.0 requires chatter yes signature public static connectapi.feedfavorite getfavorite(string communityid, string subjectid, string favoriteid) parameters communityid type: string id for an experience cloud site, internal, or null. subjectid type: string id of the context user or the alias me. favoriteid type: string id of a favorite. return value type: connectapi.feedfavorite getfavorites(communityid, subjectid) get a list of favorites for a user. api version 28.0 441apex reference guide chatterfavorites class requires chatter yes signature public static connectapi.feedfavorites getfavorites(string communityid, string subjectid) parameters communityid type: string id for an experience cloud site, internal, or null. subjectid type: string id of the context user or the alias me. return value type: connectapi.feedfavorites getfeedelements(communityid, subjectid, favoriteid) get the first page of feed elements for a favorite. api version 31.0 requires chatter yes signature public static connectapi.feedelementpage getfeedelements(string communityid, string subjectid, string favoriteid) parameters communityid type: string id for an experience cloud site, internal, or null. subjectid type: string id of the context user or the alias me. favoriteid type: string 442apex reference guide chatterfavorites class id of a favorite. return value type: connectapi.feedelementpage usage to test code that uses this method, use the matching set test method (prefix the method name with settest). use the set test method with the same parameters or the code throws an exception. see also: settestgetfeedelements(communityid, subjectid, favoriteid, result) apex developer guide: testing connectapi code getfeedelements(communityid, subjectid, favoriteid, pageparam, pagesize, sortparam) get a page of sorted feed elements for a favorite. api version 31.0 requires chatter yes signature public static connectapi.feedelementpage getfeedelements(string communityid, string subjectid, string favoriteid, string pageparam, integer pagesize, connectapi.feedsortorder sortparam) parameters communityid type: string id for an experience cloud site, internal, or null. subjectid type: string id of the context user or the alias me. favoriteid type: string id of a favorite. pageparam type: string 443apex reference guide chatterfavorites class page token to use to view the page. page tokens are returned as part of the response class, for example, currentpagetoken or nextpagetoken. if you pass in null, the first page is returned. pagesize type: integer specifies the number of feed elements per page. valid values are from 1 through 100. if you pass in null, the default size is 25. sortparam type: connectapi.feedsortorder values are: • createddateasc—sorts by oldest creation date. this sort order is available only for directmessagemoderation, draft, moderation, and pendingreview feeds. • createddatedesc—s |
orts by most recent creation date. • lastmodifieddatedesc—sorts by most recent activity. • mostviewed—sorts by most viewed content. this sort order is available only for home feeds when the connectapi.feedfilter is unansweredquestions. • relevance—sorts by most relevant content. this sort order is available only for company, home, and topics feeds. if you pass in null, the default value createddatedesc is used. return value type: connectapi.feedelementpage usage to test code that uses this method, use the matching set test method (prefix the method name with settest). use the set test method with the same parameters or the code throws an exception. see also: settestgetfeedelements(communityid, subjectid, favoriteid, pageparam, pagesize, sortparam, result) apex developer guide: testing connectapi code getfeedelements(communityid, subjectid, favoriteid, recentcommentcount, elementsperbundle, pageparam, pagesize, sortparam) get a page of sorted feed elements for a favorite. include no more than the specified number of comments per feed element. api version 31.0 requires chatter yes 444apex reference guide chatterfavorites class signature public static connectapi.feedelementpage getfeedelements(string communityid, string subjectid, string favoriteid, integer recentcommentcount, integer elementsperbundle, string pageparam, integer pagesize, connectapi.feedsortorder sortparam) parameters communityid type: string id for an experience cloud site, internal, or null. subjectid type: string id of the context user or the alias me. favoriteid type: string id of a favorite. recentcommentcount type: integer maximum number of comments to return with each feed element. the default value is 3. elementsperbundle type: integer maximum number of feed elements per bundle. the default and maximum value is 10. pageparam type: string page token to use to view the page. page tokens are returned as part of the response class, for example, currentpagetoken or nextpagetoken. if you pass in null, the first page is returned. pagesize type: integer specifies the number of feed elements per page. valid values are from 1 through 100. if you pass in null, the default size is 25. sortparam type: connectapi.feedsortorder values are: • createddateasc—sorts by oldest creation date. this sort order is available only for directmessagemoderation, draft, moderation, and pendingreview feeds. • createddatedesc—sorts by most recent creation date. • lastmodifieddatedesc—sorts by most recent activity. • mostviewed—sorts by most viewed content. this sort order is available only for home feeds when the connectapi.feedfilter is unansweredquestions. • relevance—sorts by most relevant content. this sort order is available only for company, home, and topics feeds. if you pass in null, the default value createddatedesc is used. 445apex reference guide chatterfavorites class return value type: connectapi.feedelementpage usage to test code that uses this method, use the matching set test method (prefix the method name with settest). use the set test method with the same parameters or the code throws an exception. see also: settestgetfeedelements(communityid, subjectid, favoriteid, recentcommentcount, elementsperbundle, pageparam, pagesize, sortparam, result) apex developer guide: testing connectapi code updatefavorite(communityid, subjectid, favoriteid, updatelastviewdate) update the last view date of the saved search or list view feed to the current system time. api version 28.0 requires chatter yes signature public static connectapi.feedfavorite updatefavorite(string communityid, string subjectid, string favoriteid, boolean updatelastviewdate) parameters communityid type: string id for an experience cloud site, internal, or null. subjectid type: string id of the context user or the alias me. favoriteid type: string id of a favorite. updatelastviewdate type: boolean specify whether to update the last view date of the specified favorite to the current system time (true) or not (false). 446apex reference guide chatterfavorites class return value type: connectapi |
.feedfavorite chatterfavorites test methods the following are the test methods for chatterfavorites. all methods are static. for information about using these methods to test your connectapi code, see testing connectapi code. in this section: settestgetfeedelements(communityid, subjectid, favoriteid, result) register a connectapi.feedelementpage object to be returned when getfeedelements is called with matching parameters in a test context. use the method with the same parameters or the code throws an exception. settestgetfeedelements(communityid, subjectid, favoriteid, pageparam, pagesize, sortparam, result) register a connectapi.feedelementpage object to be returned when getfeedelements is called with matching parameters in a test context. use the method with the same parameters or the code throws an exception. settestgetfeedelements(communityid, subjectid, favoriteid, recentcommentcount, elementsperbundle, pageparam, pagesize, sortparam, result) register a connectapi.feedelementpage object to be returned when getfeedelements is called with matching parameters in a test context. use the method with the same parameters or the code throws an exception. settestgetfeedelements(communityid, subjectid, favoriteid, result) register a connectapi.feedelementpage object to be returned when getfeedelements is called with matching parameters in a test context. use the method with the same parameters or the code throws an exception. api version 31.0 signature public static void settestgetfeedelements(string communityid, string subjectid, string favoriteid, connectapi.feedelementpage result) parameters communityid type: string id for an experience cloud site, internal, or null. subjectid type: string id of the context user or the alias me. favoriteid type: string id of a favorite. 447apex reference guide chatterfavorites class result type: connectapi.feedelementpage object containing test data. return value type: void see also: getfeedelements(communityid, subjectid, favoriteid) apex developer guide: testing connectapi code settestgetfeedelements(communityid, subjectid, favoriteid, pageparam, pagesize, sortparam, result) register a connectapi.feedelementpage object to be returned when getfeedelements is called with matching parameters in a test context. use the method with the same parameters or the code throws an exception. api version 31.0 signature public static void settestgetfeedelements(string communityid, string subjectid, string favoriteid, string pageparam, integer pagesize, connectapi.feedsortorder sortparam, connectapi.feedelementpage result) parameters communityid type: string id for an experience cloud site, internal, or null. subjectid type: string id of the context user or the alias me. favoriteid type: string id of a favorite. pageparam type: string page token to use to view the page. page tokens are returned as part of the response class, for example, currentpagetoken or nextpagetoken. if you pass in null, the first page is returned. pagesize type: integer 448apex reference guide chatterfavorites class specifies the number of feed elements per page. valid values are from 1 through 100. if you pass in null, the default size is 25. sortparam type: connectapi.feedsortorder values are: • createddateasc—sorts by oldest creation date. this sort order is available only for directmessagemoderation, draft, moderation, and pendingreview feeds. • createddatedesc—sorts by most recent creation date. • lastmodifieddatedesc—sorts by most recent activity. • mostviewed—sorts by most viewed content. this sort order is available only for home feeds when the connectapi.feedfilter is unansweredquestions. • relevance—sorts by most relevant content. this sort order is available only for company, home, and topics feeds. if you pass in null, the default value createddatedesc is used. result type: connectapi.feedelementpage object containing test data. return value type: void see also: getfeedelements(communityid, subjectid, favoriteid, pageparam, pagesize, sortparam) apex developer guide: testing connectapi code |
settestgetfeedelements(communityid, subjectid, favoriteid, recentcommentcount, elementsperbundle, pageparam, pagesize, sortparam, result) register a connectapi.feedelementpage object to be returned when getfeedelements is called with matching parameters in a test context. use the method with the same parameters or the code throws an exception. api version 31.0 signature public static void settestgetfeedelements(string communityid, string subjectid, string favoriteid, integer recentcommentcount, integer elementsperbundle, string pageparam, integer pagesize, connectapi.feedsortorder sortparam, connectapi.feedelementpage result) parameters communityid type: string id for an experience cloud site, internal, or null. 449apex reference guide chatterfavorites class subjectid type: string id of the context user or the alias me. favoriteid type: string id of a favorite. recentcommentcount type: integer maximum number of comments to return with each feed element. the default value is 3. elementsperbundle type: integer maximum number of feed elements per bundle. the default and maximum value is 10. pageparam type: string page token to use to view the page. page tokens are returned as part of the response class, for example, currentpagetoken or nextpagetoken. if you pass in null, the first page is returned. pagesize type: integer specifies the number of feed elements per page. valid values are from 1 through 100. if you pass in null, the default size is 25. sortparam type: connectapi.feedsortorder values are: • createddateasc—sorts by oldest creation date. this sort order is available only for directmessagemoderation, draft, moderation, and pendingreview feeds. • createddatedesc—sorts by most recent creation date. • lastmodifieddatedesc—sorts by most recent activity. • mostviewed—sorts by most viewed content. this sort order is available only for home feeds when the connectapi.feedfilter is unansweredquestions. • relevance—sorts by most relevant content. this sort order is available only for company, home, and topics feeds. if you pass in null, the default value createddatedesc is used. result type: connectapi.feedelementpage object containing test data. return value type: void see also: getfeedelements(communityid, subjectid, favoriteid, recentcommentcount, elementsperbundle, pageparam, pagesize, sortparam) apex developer guide: testing connectapi code 450apex reference guide chatterfavorites class retired chatterfavorites methods the following methods for chatterfavorites are retired. in this section: getfeeditems(communityid, subjectid, favoriteid) get the first page of feed items for a favorite. getfeeditems(communityid, subjectid, favoriteid, pageparam, pagesize, sortparam) get a page of sorted feed items for a favorite. getfeeditems(communityid, subjectid, favoriteid, recentcommentcount, pageparam, pagesize, sortparam) get a page of sorted feed items for a favorite. include no more than the specified number of comments per feed item. settestgetfeeditems(communityid, subjectid, favoriteid, result) register a connectapi.feeditempage object to be returned when getfeeditems is called with matching parameters in a test context. use the method with the same parameters or the code throws an exception. settestgetfeeditems(communityid, subjectid, favoriteid, pageparam, pagesize, sortparam, result) register a connectapi.feeditempage object to be returned when getfeeditems is called with matching parameters in a test context. use the method with the same parameters or the code throws an exception. settestgetfeeditems(communityid, subjectid, favoriteid, recentcommentcount, pageparam, pagesize, sortparam, result) register a connectapi.feeditempage object to be returned when getfeeditems is called with matching parameters in a test context. use the method with the same parameters or the code throws an exception. getfeeditems(communityid, subjectid, favoriteid) get the first page of feed items for a favorite. api version 28.0–31.0 important: in version 32.0 and later, use getfeedelements(communityid, subjectid, favoriteid). |
requires chatter yes signature public static connectapi.feeditempage getfeeditems(string communityid, string subjectid, string favoriteid) parameters communityid type: string id for an experience cloud site, internal, or null. 451apex reference guide chatterfavorites class subjectid type: string id of the context user or the alias me. favoriteid type: string id of a favorite. return value type: connectapi.feeditempage usage to test code that uses this method, use the matching set test method (prefix the method name with settest). use the set test method with the same parameters or the code throws an exception. see also: settestgetfeeditems(communityid, subjectid, favoriteid, result) apex developer guide: testing connectapi code getfeeditems(communityid, subjectid, favoriteid, pageparam, pagesize, sortparam) get a page of sorted feed items for a favorite. api version 28.0–31.0 important: in version 32.0 and later, use getfeedelements(communityid, subjectid, favoriteid, pageparam, pagesize, sortparam). requires chatter yes signature public static connectapi.feeditempage getfeeditems(string communityid, string subjectid, string favoriteid, string pageparam, integer pagesize, connectapi.feedsortorder sortparam) parameters communityid type: string id for an experience cloud site, internal, or null. 452apex reference guide chatterfavorites class subjectid type: string id of the context user or the alias me. favoriteid type: string id of a favorite. pageparam type: string page token to use to view the page. page tokens are returned as part of the response class, for example, currentpagetoken or nextpagetoken. if you pass in null, the first page is returned. pagesize type: integer number of feed items per page. valid values are from 1 through 100. if you pass in null, the default size is 25. sortparam type: connectapi.feedsortorder values are: • createddateasc—sorts by oldest creation date. this sort order is available only for directmessagemoderation, draft, moderation, and pendingreview feeds. • createddatedesc—sorts by most recent creation date. • lastmodifieddatedesc—sorts by most recent activity. • mostviewed—sorts by most viewed content. this sort order is available only for home feeds when the connectapi.feedfilter is unansweredquestions. • relevance—sorts by most relevant content. this sort order is available only for company, home, and topics feeds. sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. if you pass in null, the default value createddatedesc is used. return value type: connectapi.feeditempage usage to test code that uses this method, use the matching set test method (prefix the method name with settest). use the set test method with the same parameters or the code throws an exception. see also: settestgetfeeditems(communityid, subjectid, favoriteid, pageparam, pagesize, sortparam, result) apex developer guide: testing connectapi code getfeeditems(communityid, subjectid, favoriteid, recentcommentcount, pageparam, pagesize, sortparam) get a page of sorted feed items for a favorite. include no more than the specified number of comments per feed item. 453apex reference guide chatterfavorites class api version 29.0–31.0 important: in version 32.0 and later, use getfeedelements(communityid, subjectid, favoriteid, recentcommentcount, elementsperbundle, pageparam, pagesize, sortparam). requires chatter yes signature public static connectapi.feeditempage getfeeditems(string communityid, string subjectid, string favoriteid, integer recentcommentcount, string pageparam, integer pagesize, feedsortorder sortparam) parameters communityid type: string id for an experience cloud site, internal, or null. subjectid type: string id of the context user or the alias me. favoriteid type: string id of a favorite. recentcommentcount type: integer maximum number of comments to return with each feed item. the default value is 3. |
pageparam type: string page token to use to view the page. page tokens are returned as part of the response class, for example, currentpagetoken or nextpagetoken. if you pass in null, the first page is returned. pagesize type: integer number of feed items per page. valid values are from 1 through 100. if you pass in null, the default size is 25. sortparam type: connectapi.feedsortorder values are: • createddateasc—sorts by oldest creation date. this sort order is available only for directmessagemoderation, draft, moderation, and pendingreview feeds. • createddatedesc—sorts by most recent creation date. • lastmodifieddatedesc—sorts by most recent activity. 454apex reference guide chatterfavorites class • mostviewed—sorts by most viewed content. this sort order is available only for home feeds when the connectapi.feedfilter is unansweredquestions. • relevance—sorts by most relevant content. this sort order is available only for company, home, and topics feeds. sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. if you pass in null, the default value createddatedesc is used. return value type: connectapi.feeditempage usage to test code that uses this method, use the matching set test method (prefix the method name with settest). use the set test method with the same parameters or the code throws an exception. see also: settestgetfeeditems(communityid, subjectid, favoriteid, recentcommentcount, pageparam, pagesize, sortparam, result) apex developer guide: testing connectapi code settestgetfeeditems(communityid, subjectid, favoriteid, result) register a connectapi.feeditempage object to be returned when getfeeditems is called with matching parameters in a test context. use the method with the same parameters or the code throws an exception. api version 28.0–31.0 signature public static void settestgetfeeditems(string communityid, string subjectid, string favoriteid, connectapi.feeditempage result) parameters communityid type: string id for an experience cloud site, internal, or null. subjectid type: string id of the context user or the alias me. favoriteid type: string id of a favorite. result type: connectapi.feeditempage 455apex reference guide chatterfavorites class object containing test data. return value type: void see also: getfeeditems(communityid, subjectid, favoriteid) apex developer guide: testing connectapi code settestgetfeeditems(communityid, subjectid, favoriteid, pageparam, pagesize, sortparam, result) register a connectapi.feeditempage object to be returned when getfeeditems is called with matching parameters in a test context. use the method with the same parameters or the code throws an exception. api version 28.0–31.0 signature public static void settestgetfeeditems(string communityid, string subjectid, string favoriteid, string pageparam, integer pagesize, feedsortorder sortparam, connectapi.feeditempage result) parameters communityid type: string id for an experience cloud site, internal, or null. subjectid type: string id of the context user or the alias me. favoriteid type: string id of a favorite. pageparam type: string page token to use to view the page. page tokens are returned as part of the response class, for example, currentpagetoken or nextpagetoken. if you pass in null, the first page is returned. pagesize type: integer number of feed items per page. valid values are from 1 through 100. if you pass in null, the default size is 25. 456apex reference guide chatterfavorites class sortparam type: connectapi.feedsortorder values are: • createddateasc—sorts by oldest creation date. this sort order is available only for directmessagemoderation, draft, moderation, and pendingreview feeds. • createddatedesc—sorts by most recent creation date. • lastmodifieddatedesc—sorts by most recent activity. • mostviewed—sorts by most viewed content. this sort order is available only for home feeds when the connectapi.feedfilter is unansweredquestions. • relev |
ance—sorts by most relevant content. this sort order is available only for company, home, and topics feeds. sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. if you pass in null, the default value createddatedesc is used. result type: connectapi.feeditempage object containing test data. return value type: void see also: getfeeditems(communityid, subjectid, favoriteid, pageparam, pagesize, sortparam) apex developer guide: testing connectapi code settestgetfeeditems(communityid, subjectid, favoriteid, recentcommentcount, pageparam, pagesize, sortparam, result) register a connectapi.feeditempage object to be returned when getfeeditems is called with matching parameters in a test context. use the method with the same parameters or the code throws an exception. api version 29.0–31.0 signature public static void settestgetfeeditems(string communityid, string subjectid, string favoriteid, integer recentcommentcount, string pageparam, integer pagesize, feedsortorder sortparam, connectapi.feeditempage result) parameters communityid type: string id for an experience cloud site, internal, or null. 457apex reference guide chatterfavorites class subjectid type: string id of the context user or the alias me. favoriteid type: string id of a favorite. recentcommentcount type: integer maximum number of comments to return with each feed item. the default value is 3. pageparam type: string page token to use to view the page. page tokens are returned as part of the response class, for example, currentpagetoken or nextpagetoken. if you pass in null, the first page is returned. pagesize type: integer number of feed items per page. valid values are from 1 through 100. if you pass in null, the default size is 25. sortparam type: connectapi.feedsortorder values are: • createddateasc—sorts by oldest creation date. this sort order is available only for directmessagemoderation, draft, moderation, and pendingreview feeds. • createddatedesc—sorts by most recent creation date. • lastmodifieddatedesc—sorts by most recent activity. • mostviewed—sorts by most viewed content. this sort order is available only for home feeds when the connectapi.feedfilter is unansweredquestions. • relevance—sorts by most relevant content. this sort order is available only for company, home, and topics feeds. sorts the returned feed by the most recently created feed item, or by the most recently modified feed item. if you pass in null, the default value createddatedesc is used. result type: connectapi.feeditempage object containing test data. return value type: void see also: getfeeditems(communityid, subjectid, favoriteid, recentcommentcount, pageparam, pagesize, sortparam) apex developer guide: testing connectapi code 458apex reference guide chatterfeeds class chatterfeeds class get, post, and delete feed elements, likes, comments, and bookmarks. you can also search feed elements, share feed elements, and vote on polls. namespace connectapi usage the chatter feed is a container of feed elements. the abstract class connectapi.feedelement is a parent class to the connectapi.feeditem class, representing feed posts, and the connectapi.genericfeedelement class, representing bundles and recommendations in the feed. for detailed information, see working with feeds and feed elements. important: feed item methods aren’t available in version 32.0. in version 32.0 and later, use feed element methods. message segments in a feed item are typed as connectapi.messagesegment. feed item capabilities are typed as connectapi.feeditemcapability. record fields are typed as connectapi.abstractrecordfield. these classes are all abstract and have several concrete subclasses. at runtime you can use instanceof to check the concrete types of these objects and then safely proceed with the corresponding downcast. when you downcast, you must have a default case that handles unknown subclasses. important: the composition of a feed can change between releases. write your code to handle instances of unknown subclasses. chatterfeeds methods the following are methods for chatterfeeds. all methods are static. in this section: |
createstream(communityid, streaminput) create a chatter feed stream. deletecomment(communityid, commentid) delete a comment. deletefeedelement(communityid, feedelementid) delete a feed element. deletelike(communityid, likeid) delete a like on a comment or post. deletestream(communityid, streamid) delete a chatter feed stream. getcomment(communityid, commentid) get a comment. getcommentbatch(communityid, commentids) get a list of comments. getcommentincontext(communityid, commentid, pagesize) get a threaded comment in the context of its parent comments and post. 459apex reference guide chatterfeeds class getcommentsforfeedelement(communityid, feedelementid) get comments for a feed element. getcommentsforfeedelement(communityid, feedelementid, threadedcommentscollapsed) get comments in a threaded style for a feed element. getcommentsforfeedelement(communityid, feedelementid, pageparam, pagesize) get a page of comments for a feed element. getcommentsforfeedelement(communityid, feedelementid, pageparam, pagesize, threadedcommentscollapsed) get a page of comments in a threaded style for a feed element. getcommentsforfeedelement(communityid, feedelementid, threadedcommentscollapsed, sortparam) get sorted comments in a threaded style for a feed element. getcommentsforfeedelement(communityid, feedelementid, pageparam, pagesize, threadedcommentscollapsed, sortparam) get a page of sorted comments in a threaded style for a feed element. getcommentsforfeedelement(communityid, feedelementid, sortparam) get sorted comments for a feed element. getcommentsforfeedelement(communityid, feedelementid, sortparam, threadedcommentscollapsed) get sorted comments in a threaded style for a feed element. getextensions(communityid, pageparam, pagesize) get extensions. getfeed(communityid, feedtype) get a feed. getfeed(communityid, feedtype, sortparam) get a sorted feed. getfeed(communityid, feedtype, subjectid) get a feed for a record or user. getfeed(communityid, feedtype, subjectid, sortparam) get a sorted feed for a record or user. getfeeddirectory(string) get a list of all feeds available to the context user. getfeedelement(communityid, feedelementid) get a feed element. getfeedelement(communityid, feedelementid, commentsort) get a feed element with sorted comments. getfeedelement(communityid, feedelementid, threadedcommentscollapsed) get a feed element and its comments in a threaded style. getfeedelement(communityid, feedelementid, threadedcommentscollapsed, commentsort) get a feed element and its sorted comments in a threaded style. getfeedelement(communityid, feedelementid, recentcommentcount, elementsperbundle) get a feed element with the specified number of elements per bundle including no more than the specified number of comments per feed element. 460apex reference guide chatterfeeds class getfeedelement(communityid, feedelementid, recentcommentcount, elementsperbundle, threadedcommentscollapsed) get a feed element with its comments in a threaded style with the specified number of elements per bundle and comments per feed element. getfeedelement(communityid, feedelementid, recentcommentcount, elementsperbundle, threadedcommentscollapsed, commentsort) get a feed element with its sorted comments in a threaded style with the specified number of elements per bundle and comments per feed element. getfeedelement(communityid, feedelementid, recentcommentcount, elementsperbundle, commentsort) get a feed element with the specified number of elements per bundle including no more than the specified number of sorted comments per feed element. getfeedelementbatch(communityid, feedelementids) get a list of feed elements. getfeedelementpoll(communityid, feedelementid) get the poll associated with a feed element. getfeedelementsfrombundle(communityid, feedelementid) get feed elements from a bundle. getfeedelementsfrombundle(communityid, feedelementid, pageparam, pagesize, elementsperbundle, recentcommentcount) get a page of feed elements from a bundle. specify the number of elements per bundle and include no more than the specified number of comments per feed element. getfeedelementsfromfeed(communityid, |
feedtype) get feed elements from the company, directmessagemoderation, directmessages, home, moderation, and pendingreview feeds. getfeedelementsfromfeed(communityid, feedtype, pageparam, pagesize, sortparam) get a page of sorted feed elements from the company, directmessagemoderation, directmessages, home, moderation, and pendingreview feeds. getfeedelementsfromfeed(communityid, feedtype, recentcommentcount, density, pageparam, pagesize, sortparam) get a page of sorted feed elements from the company, directmessagemoderation, directmessages, home, moderation, and pendingreview feeds. each feed element contains no more than the specified number of comments. getfeedelementsfromfeed(communityid, feedtype, recentcommentcount, density, pageparam, pagesize, sortparam, filter) get a page of sorted and filtered feed elements from the home feed. each feed element contains no more than the specified number of comments. getfeedelementsfromfeed(communityid, feedtype, recentcommentcount, density, pageparam, pagesize, sortparam, filter, threadedcommentscollapsed) get a page of filtered and sorted feed elements with comments in a threaded style from the home feed. each feed element contains no more than the specified number of comments. getfeedelementsfromfeed(communityid, feedtype, subjectid) get feed elements from any feed other than company, directmessagemoderation, directmessages, filter, home, landing, moderation, and pendingreview for a user or record. getfeedelementsfromfeed(communityid, feedtype, subjectid, pageparam, pagesize, sortparam) get a page of sorted feed elements from any feed other than company, directmessagemoderation, directmessages, filter, home, landing, moderation, and pendingreview. 461apex reference guide chatterfeeds class getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, density, pageparam, pagesize, sortparam) get a page of sorted feed elements from any feed other than company, directmessagemoderation, directmessages, filter, home, landing, moderation, and pendingreview. each feed element includes no more than the specified number of comments. getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, density, pageparam, pagesize, sortparam, showinternalonly) get a page of sorted feed elements from a record feed. each feed element includes no more than the specified number of comments. specify whether to return feed elements posted by internal (non-experience cloud site) users only. getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, density, pageparam, pagesize, sortparam, filter) get a page of sorted and filtered feed elements from the userprofile feed. getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, density, pageparam, pagesize, sortparam, filter, threadedcommentscollapsed) get a page of feed elements with comments in a threaded style from the userprofile feed. getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, density, pageparam, pagesize, sortparam, customfilter) get a page of sorted and filtered feed elements from the case feed. getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, elementsperbundle, density, pageparam, pagesize, sortparam, showinternalonly) get a page of sorted feed elements from a record feed. specify the number of elements per bundle and include no more than the specified number of comments per feed element. specify whether to return feed elements posted by internal (non-experience cloud site) users only. getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, elementsperbundle, density, pageparam, pagesize, sortparam, showinternalonly, filter) get a page of sorted and filtered feed elements from a record feed. specify the number of elements per bundle and include no more than the specified number of comments per feed element. specify whether to return feed elements posted by internal (non-experience cloud site) users only. getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, elementsperbundle, density, pageparam, pagesize, sortparam, showinternalonly, filter, threadedcommentscollapsed) get a page of sorted |
and filtered feed elements with comments in a threaded style for a record feed. specify the number of elements per bundle and include no more than the specified number of comments per feed element. specify whether to return feed elements posted by internal (non-experience cloud site) users only. getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, elementsperbundle, density, pageparam, pagesize, sortparam, showinternalonly, customfilter) get a page of sorted and filtered feed elements from a case feed. getfeedelementsfromfeed(communityid, feedtype, subjectid, recentcommentcount, elementsperbundle, density, pageparam, pagesize, sortparam, showinternalonly, customfilter, threadedcommentscollapsed) get a page of filtered and sorted feed elements with comments in a threaded style from a case feed. getfeedelementsfromfilterfeed(communityid, subjectid, keyprefix) get feed elements from a feed filtered by a key prefix for a user. getfeedelementsfromfilterfeed(communityid, subjectid, keyprefix, pageparam, pagesize, sortparam) get a page of sorted feed elements from a feed filtered by a key prefix for a user. 462apex reference guide chatterfeeds class getfeedelementsfromfilterfeed(communityid, subjectid, keyprefix, recentcommentcount, elementsperbundle, density, pageparam, pagesize, sortparam) get a page of sorted feed elements from a feed filtered by a key prefix for a user. each feed element contains no more than the specified number of comments. getfeedelementsfromfilterfeedupdatedsince(communityid, subjectid, keyprefix, recentcommentcount, elementsperbundle, density, pageparam, pagesize, updatedsince) get a page of feed elements from a feed filtered by a key prefix for a user. include only feed elements that have been updated since the time specified in the updatedsince parameter. getfeedelementsupdatedsince(communityid, feedtype, recentcommentcount, density, pageparam, pagesize, updatedsince) get a page of feed elements from the company, directmessagemoderation, home, and moderation feeds. include only feed elements that have been updated since the time specified in the updatedsince parameter. each feed element contains no more than the specified number of comments. getfeedelementsupdatedsince(communityid, feedtype, recentcommentcount, density, pageparam, pagesize, updatedsince, filter) get a page of filtered feed elements from the home feed. include only feed elements that have been updated since the time specified in the updatedsince parameter. each feed element contains no more than the specified number of comments. getfeedelementsupdatedsince(communityid, feedtype, subjectid, recentcommentcount, density, pageparam, pagesize, updatedsince) get a page of feed elements from the files, groups, news, people, and record feeds. include only feed elements that have been updated since the time specified in the updatedsince parameter. each feed element contains no more than the specified number of comments. getfeedelementsupdatedsince(communityid, feedtype, subjectid, recentcommentcount, density, pageparam, pagesize, updatedsince, showinternalonly) get a page of feed elements from a record feed. include only feed elements that have been updated since the time specified in the updatedsince parameter. specify whether to return feed elements posted by internal (non-experience cloud site) users only. getfeedelementsupdatedsince(communityid, feedtype, subjectid, recentcommentcount, elementsperbundle, density, pageparam, pagesize, updatedsince, filter) get a page of filtered feed elements from a userprofile feed. include only feed elements that have been updated since the time specified in the updatedsince parameter. getfeedelementsupdatedsince(communityid, feedtype, subjectid, recentcommentcount, elementsperbundle, density, pageparam, pagesize, updatedsince, customfilter) get a page of filtered feed elements from a case feed. include only feed elements that have been updated since the time specified in the updatedsince parameter. getfeedelementsupdatedsince(communityid, feedtype, subjectid, recentcommentcount, elementsperbundle, density, pageparam, pagesize, updatedsince, showinternalonly) get a page of feed elements from a record feed. include only feed elements that have been updated since the time specified in the updatedsince parameter. specify the maximum number of feed elements in a bundle and whether to return feed elements posted by internal (non-experience cloud site) users only |
. getfeedelementsupdatedsince(communityid, feedtype, subjectid, recentcommentcount, elementsperbundle, density, pageparam, pagesize, updatedsince, showinternalonly, filter) get a page of filtered feed elements from a record feed. include only feed elements that have been updated since the time specified in the updatedsince parameter. specify the maximum number of feed elements in a bundle and whether to return feed elements posted by internal (non-experience cloud site) users only. 463apex reference guide chatterfeeds class getfeedelementsupdatedsince(communityid, feedtype, subjectid, recentcommentcount, elementsperbundle, density, pageparam, pagesize, updatedsince, showinternalonly, customfilter) get a page of filtered feed elements from a case feed. include only feed elements that have been updated since the time specified in the updatedsince parameter. getfeedwithfeedelements(communityid, feedtype, pagesize) get information about a feed and a page of feed elements from the feed. getfeedwithfeedelements(communityid, feedtype, pagesize, recentcommentcount) get a page of information about the feed and the feed elements with the specified number of comments per feed element from the feed. getfilterfeed(communityid, subjectid, keyprefix) get a feed filtered by a key prefix for a user. getfilterfeed(communityid, subjectid, keyprefix, sortparam) get a sorted feed filtered by a key prefix for a user. getfilterfeeddirectory(communityid, subjectid) get a feed directory of filter feeds available to the context user. getlike(communityid, likeid) get a like on a post or comment. getlikesforcomment(communityid, commentid) get likes for a comment. getlikesforcomment(communityid, commentid, pageparam, pagesize) get a page of likes for a comment. getlikesforfeedelement(communityid, feedelementid) get likes for a feed element. getlikesforfeedelement(communityid, feedelementid, pageparam, pagesize) get a page of likes for a feed element. getlinkmetadata(communityid, urls) get link metadata for urls. getpinnedfeedelementsfromfeed(communityid, feedtype, subjectid) get pinned feed elements from a group or topic feed. getreadbyforfeedelement(communityid, feedelementid) get information about who read a feed element and when. getreadbyforfeedelement(communityid, feedelementid, pageparam, pagesize) get a page of information about who read a feed element and when. getrelatedposts(communityid, feedelementid, filter, maxresults) get posts related to the context feed element. getstream(communityid, streamid) get information about a chatter feed stream. getstream(communityid, streamid, globalscope) get information about a chatter feed stream, regardless of experience cloud site. getstreams(communityid) get the chatter feed streams for the context user. 464apex reference guide chatterfeeds class getstreams(communityid, sortparam) get and sort the chatter feed streams for the context user. getstreams(communityid, pageparam, pagesize) get a page of chatter feed streams for the context user. getstreams(communityid, pageparam, pagesize, sortparam) get a sorted page of chatter feed streams for the context user. getstreams(communityid, pageparam, pagesize, sortparam, globalscope) get a sorted page of chatter feed streams from all enterprise cloud sites for the context user. getsupportedemojis() get supported emojis for the org. getthreadsforfeedcomment(communityid, commentid) get threaded comments for a comment. getthreadsforfeedcomment(communityid, commentid, pageparam, pagesize) get a page of threaded comments for a comment. getthreadsforfeedcomment(communityid, commentid, threadedcommentscollapsed) access the comments capability for a comment. gettopunansweredquestions(communityid) (pilot) get top unanswered questions for the context user in aexperience cloud site. gettopunansweredquestions(communityid, filter) (pilot) get filtered top unanswered questions for the context user in an experience cloud site. gettopunansweredquestions(communityid, pagesize) (pilot) get a page of top unanswered questions for the context user in an |
experience cloud site. gettopunansweredquestions(communityid, filter, pagesize) (pilot) get a page of filtered top unanswered questions for the context user in an experience cloud site. getvotesforcomment(communityid, commentid, vote) get the first page of users who upvoted or downvoted a comment. getvotesforcomment(communityid, commentid, vote, pageparam, pagesize) get a page of users who upvoted or downvoted a comment. getvotesforfeedelement(communityid, feedelementid, vote) get the first page of users who upvoted or downvoted a feed element. getvotesforfeedelement(communityid, feedelementid, vote, pageparam, pagesize) get a page of users who upvoted or downvoted a feed element. iscommenteditablebyme(communityid, commentid) discover whether the context user can edit a comment. isfeedelementeditablebyme(communityid, feedelementid) discover whether the context user can edit a feed element. ismodified(communityid, feedtype, subjectid, since) discover whether a news feed has been updated or changed. use this method to poll a news feed for updates. likecomment(communityid, commentid) like a comment for the context user. 465apex reference guide chatterfeeds class likefeedelement(communityid, feedelementid) like a feed element. postcommenttofeedelement(communityid, feedelementid, text) post a plain-text comment to a feed element. postcommenttofeedelement(communityid, feedelementid, comment, feedelementfileupload) post a rich-text comment to a feed element. use this method to include mentions and to attach a file. postfeedelement(communityid, subjectid, feedelementtype, text) post a plain-text feed element. postfeedelement(communityid, feedelement) post a rich-text feed element. include mentions and hashtag topics, attach already uploaded files to a feed element, and associate action link groups with a feed element. you can also use this method to share a feed element and add a comment. postfeedelementbatch(communityid, feedelements) post a list of feed elements. publishdraftfeedelement(communityid, feedelementid, feedelement) publish a draft feed element. searchfeedelements(communityid, q) get the first page of feed elements that match the search criteria. searchfeedelements(communityid, q, sortparam) get the first page of sorted feed elements that match the search criteria. searchfeedelements(communityid, q, threadedcommentscollapsed) get the feed elements and comments that match the search criteria. searchfeedelements(communityid, q, pageparam, pagesize) get a page of feed elements that match the search criteria. searchfeedelements(communityid, q, pageparam, pagesize, sortparam) get a page of sorted feed elements that match the search criteria. searchfeedelements(communityid, q, pageparam, pagesize, threadedcommentscollapsed) get a page of feed elements with comments in a threaded style that match the search criteria. searchfeedelements(communityid, q, recentcommentcount, pageparam, pagesize, sortparam) get a page of sorted feed elements that match the search criteria. each feed element includes no more than the specified number of comments. searchfeedelementsinfeed(communityid, feedtype, q) get the feed elements from the company, directmessagemoderation, home, moderation, and pendingreview feeds that match the search criteria. searchfeedelementsinfeed(communityid, feedtype, pageparam, pagesize, sortparam, q) get a page of sorted feed elements from the company, directmessagemoderation, home, moderation, and pendingreview feeds that match the search criteria. searchfeedelementsinfeed(communityid, feedtype, recentcommentcount, density, pageparam, pagesize, sortparam, q) get a page of sorted feed elements from the company, directmessagemoderation, home, moderation, and pendingreview feeds that match the search criteria. each feed element includes no more than the specified number of comments. 466apex reference guide chatterfeeds class searchfeedelementsinfeed(communityid, feedtype, recentcommentcount, density, pageparam, pagesize, sortparam, q, filter) get a page of sorted and filtered feed elements from the home |
Subsets and Splits