====== The Myriad Uses of Session Variables ====== ===== What Session Variables Are ===== "Session Variables" allow you to store information (as name/value pairs) in a user's cart, independently of any [[.:products|products]] in [[.:cart|the cart]]. Unlike a product, which is visible in the cart and added by the customer, session variables aren't necessarily visible to the visitor, nor would the visitor know that a session variable has been set. You can think of session variables as a way to attach extra information to the //session// (fancy that) for you to use later. ===== Potential Uses of Session Variables ===== Though you could use session variables for any number of integration or data tracking purposes, the most common uses are: * **Analytics.** For example, the [[:integration:googleanalytics_async|Google Analytics integration]] relies on session variables to maintain (Google, not FoxyCart) session states between your site, the cart, the checkout, and the receipt. * **Affiliate tracking systems.** While most affiliate systems track primarily with cookies, there are situations where using a session variables may be more desirable. * **Storing user information.** Sometimes it may be necessary to attach data to a customer that impacts later functionality. Perhaps adding a flag if they've already visited an upsell page (to prevent showing them the same page). Or adding an ID for a separate system for use with later synching. * And much more. ===== How to Set Session Variables ===== Setting a session variable is as easy as adding an ''h:'' prefix to any value being passed to the cart. Here's a quick example of adding a //product// with a ''color'' value equal to ''blue'', and a //session// variable named ''referrer'' set to ''charlie''. Buy this Great Product!
Either of those would add the product to the cart, but would also add the ''referrer'' value to the session, so your JSON would include something like this: { ... "custom_fields":{ "referrer":"charlie" }, ... } Notice that the ''custom_fields'' is at the top level of the JSON, //not// associated with specific products being added to the cart. ===== How to Access Session Variables ===== Given the intended usage of session variables, it shouldn't be surprising that these values are not displayed to the user at any point, but they are accessible via the [[.:json|JSON cart object]] during the user's visit, and via the [[.:transaction_xml_datafeed|transaction XML datafeed]] or [[.:api|the API]] after the transaction is completed. For the example above, you can access the value with twig like this {{ custom_fields.referrer.value }}