Adding eCommerce to a Wappler Site

Okay i will try to explain the logic here, so you can get the idea.

First you need a session cookie and a session which we use to identify the users (no matter if they are logged in or not).
This can be done using the following code, placed on top of your page:

<?php
	session_set_cookie_params(86400,"/");
	session_start();
	$randNumber = mt_rand();
	if(!isset($_SESSION['cart_session'])) {
			$_SESSION['cart_session'] = + $randNumber;
	}
?>

What this code does is to set a session cookie for 86400 seconds - i.e. it will keep the cookie for 1 day. Change this to whatever you like it to be. This is what keeps the products in the cart when the users enter the site after a certain amount of time.
Then it sets a session called “cart_session” which gets a random (unique value) for each user.

Then you define this session under globals in every server action related to the cart - in add, update, delete actions and in the cart contents action:
Screenshot_36

Create a table which stores cart content. It will store the content for all the users carts. Then we filter it by this cart_session value.

So in add products to cart server action you insert the product ID and use cart_session in the database:
Screenshot_37

And when displaying the cart content you use the same cart_session for the cart content action to filter the cart content table.

Same for update and delete actions - filter by the cart_session value. Then on successful checkout, you just remove everything related to this cart_session value from the cart content table.

These are the basics required for basic shopping cart functionality. Of course, you can extend it to check if a product exists in the cart content table for this user on add product - run database update instead of insert.

You can extend it to use coupon codes etc. but for basic shopping cart/wish list functionality the above is functioning perfectly.

5 Likes