Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active November 13, 2023 11:07
Show Gist options
  • Save code-boxx/3f00e34fd6d21539dbb46507d7149898 to your computer and use it in GitHub Desktop.
Save code-boxx/3f00e34fd6d21539dbb46507d7149898 to your computer and use it in GitHub Desktop.
PHP MYSQL Referral System

PHP MYSQL REFERRAL SYSTEM

https://code-boxx.com/simple-php-referral-system/

IMAGES

sales

NOTES

  1. Create a database and import the 1-database.sql file.
  2. Change the database settings in 2-lib.php to your own.
  3. Launch 3a-sales.php?ref=jondoe in your browser and click the "buy now" button.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

-- (A) AFFILIATES TABLE
CREATE TABLE `affiliates` (
`ref_code` varchar(32) NOT NULL,
`aff_email` varchar(255) NOT NULL,
`aff_name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `affiliates`
ADD PRIMARY KEY (`ref_code`),
ADD UNIQUE KEY `aff_email` (`aff_email`),
ADD KEY `aff_name` (`aff_name`);
-- (B) COMMISSIONS TABLE
CREATE TABLE `commissions` (
`ref_code` varchar(32) NOT NULL,
`comm_date` datetime NOT NULL DEFAULT current_timestamp(),
`comm_amount` decimal(10,2) NOT NULL,
`order_id` bigint(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `commissions`
ADD PRIMARY KEY (`ref_code`,`comm_date`);
-- (C) DUMMY AFFILIATE
INSERT INTO `affiliates` (`ref_code`, `aff_email`, `aff_name`) VALUES
('jondoe', 'jon@doe.com', 'Jon Doe');
<?php
class Referral {
// (A) CONSTRUCTOR - CONNECT TO DATABASE
private $pdo;
private $stmt;
public $error;
function __construct () {
$this->pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_NAMED
]);
}
// (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
function __destruct () {
$this->pdo = null;
$this->stmt = null;
}
// (C) HELPER - RUN SQL QUERY
function query ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) REGISTER REFERRAL CODE - FIRST COME FIRST SERVE
// I.E. CUSTOMER ACCESS YOUR SITE WITH 2 REFERRAL CODES.
// THE FIRST REFERRAL CODE WILL BE VALID FOR 24 HRS.
// THE SECOND REFERRAL CODE WILL NOT OVERRIDE THE FIRST.
function set () {
// (D1) CHECK IF EXISTING REFERRAL CODE HAS EXPIRED
if (isset($_SESSION["referral"])) {
if (strtotime("now") >= ($_SESSION["referral"]["t"] + REF_VALID)) {
unset($_SESSION["referral"]);
}
}
if (!isset($_SESSION["referral"]) && isset($_GET["ref"])) {
// (D2) CHECK IF VALID AFFILIATE MEMBER
$this->query("SELECT * FROM `affiliates` WHERE `ref_code`=?", [$_GET["ref"]]);
$aff = $this->stmt->fetch();
// (D3) REGISTER INTO SESSION IF VALID
if (is_array($aff)) {
$_SESSION["referral"] = [
"c" => $aff["ref_code"],
"t" => strtotime("now")
];
}
// (D4) INVALID REFERRAL CODE
else {
$this->error = "Invalid referral code";
return false;
}
}
return true;
}
// (E) REGISTER SALES COMMISSION
function commission ($oid, $amt) {
if (isset($_SESSION["referral"])) {
// (E1) CHECK IF EXISTING REFERRAL CODE EXPIRED
if (strtotime("now") >= ($_SESSION["referral"]["t"] + REF_VALID)) {
unset($_SESSION["referral"]);
$this->error = "Referral code expired";
return false;
}
// (E2) REGISTER COMMISSIONS
$this->query(
"INSERT INTO `commissions` (`ref_code`, `comm_amount`, `order_id`) VALUES (?,?,?)",
[$_SESSION["referral"]["c"], $amt, $oid]
);
// (E3) UP TO YOU - KEEP REFERRAL CODE AFTER SALES?
unset($_SESSION["referral"]);
return true;
}
}
}
// (F) SETTINGS - CHANGE THESE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("REF_VALID", 86400); // 24 hours = 86400 secs
// (G) START SEESSION + CREATE NEW REFERRAL OBJECT
session_start();
$REF = new Referral();
<?php
// (A) REGISTER REFERRAL CODE (IF ANY)
require "2-lib.php";
$REF->set();
// (B) HTML SALES PAGE ?>
<!DOCTYPE html>
<html>
<head>
<title>DUMMY SALES PAGE</title>
<meta charset="utf-8">
<link rel="stylesheet" href="x-dummy.css">
</head>
<body>
<img src="sales.png">
<p>Sales pitch here - Buy now and get this that everything!</p>
<div class="note"><?php
if (isset($_SESSION["referral"])) {
echo "Current referral - ";
print_r($_SESSION["referral"]);
} else {
echo "No referral set - Please access this page with 3a-sales.php?ref=jondoe";
}
?></div>
<form method="post" action="3b-checkout.php">
<input type="submit" value="BUY NOW!">
</form>
</body>
</html>
<?php
// (A) DO YOUR PAYMENT & ORDER PROCESSING
// LET'S SAY PAYMENT + CHECKOUT OK - ORDER ID 999, COMMISSION AMOUNT OWED IS $87.65
$orderID = 999;
$commission = 87.65;
// (B) REGISTER COMMISSION
require "2-lib.php";
$pass = $REF->commission($orderID, $commission);
echo $pass ? "OK" : $REF->error ;
/* (X) NOT IMPORTANT - CSS COSMETICS */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
body {
max-width: 400px;
padding: 10px;
margin: 0 auto;
color: #fff;
background: #000;
}
img {
width: 100%;
}
div.note {
padding: 15px;
color: #fbff00;
background: #373737;
}
input[type=submit] {
color: #fff;
border: 0;
background: #cb0000;
font-size: 18px;
width: 100%;
padding: 10px;
margin-top: 20px;
cursor: pointer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment