Readme.htm:
Tiny Tool Readme
/* */
Using Tiny Tool
Table Of Contents
The GNU GPL License
What Tiny Tool Does
Requirements
Installing
Un-zip and Upload
Set Permissions
Editing Files and Customizing Tiny Tool
The config.php file
Two Forms in Order.php
The Welcome.php file
The TOS.htm file
Additional Commentary
Using heredoc Syntax
Your PayPal Setup
Pre-deployment Testing
Security
Flowcharts
The GNU GPL License
TeaToast Tiny Tool is a bare-bones PHP program that intends to automate new customer subscription processing for small WebHosting enterprises. Copyright (C) 2004 John Sinclair and/or Dennis Turner
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For more details see the FULL TEXT of the GNU General Public License at WWW.TEATOAST.COM/GNU_GPL_LICENSE.HTML
Interested parties may contact the authors by email addressed to
obfuscate('authors', 'teatoast.com')
or by writing to John Sinclair at 2597 West 5400 South, Salt Lake City, Utah 84118
TOP
What Tiny Tool Does
Tiny Tool co-ordinates the activities of PayPal Subscriptions, PayPal IPN (Instant Payment Notification), and the CPanel WHM (Webhost Manager) to securely complete new account setup.
Tiny Tool may satisfy the needs of small WebHosts who want to:
offer instant access to new users
make their WHM automatically create accounts
use PayPal Subscriptions to process bankcard payments
have Paypal manage their customer accounts
maintain a database of subscribers and payments
display a welcome page to new subscribers
email new users their logon and usage instructions
Using two program files and a configuration file, plus some ancillary pages to help educate new subscribers, Tiny Tool fully automates your new-user signup process.
Process.php
The primary program file, called Process.php, accepts customer information posted from an order form. It responds to PayPal's IPN and authenticates the subscription against SQL records. The Process.php module culls spoofs and false signups, and ensures that subscribers are genuine. Once it verifies the legitimacy of a new subscription, Process.php fully fills in the subscriber's SQL record and triggers new account creation in CPanel's WHM .
Order.php
A program called Order.php generates a new subscriber order form, validates the user input, creates a MySQL record for that user, and offers the potential subscriber a recap of their entered information. Once the user approves, the Order.php module passes the user to PayPal to complete their purchase. PayPal collects the subscriber's details which we'll get back (in Process.php) via IPN.
config.php
The config.php is the most important file for it contains all the information unique to your particular webhosting enterprise. This is the file you will most want to edit in order to make Tiny Tool work for you. This file contains your database access variables and variables used to access WHM. The config file also holds certain default values for PayPal subscriptions and it holds strings that define your specific product offerings. Site appearance is defined in $head and $foot strings in Order.php. By far the most important contents of config.php are the subscription variables passed to PayPal and package names passed to WHM. We'll go into detail later about how to edit these.
IPNlog.sql
This is the series of SQL instructions used to create the MySQL table for Tiny Tool to store transaction and subscriber details. It will set up a table in an existing database if you like. It has been designed to save all of the IPN variables that PayPal will be sending to the Process.php program ... perhaps more detail than you care to keep. Minor changes to the SQL layout shouldn't require code changes in Process.php or Order.php.
Welcome.php
The Welcome page is displayed to each new customer after they finish the PayPal subscription process.The Welcome.php file is HTML code with user-specific details inserted. It is where users re-enter your website after successfully completing the PayPal signup process, so this page is the return URL passed to PayPal.
TOS.htm
We've included a sample of a Terms Of Service page which you may require your new subscribers to read before starting service with you. It is linked to the order form generated by Order.php and there is a check-off required by the new subscriber to make sure they're aware of this page's content.
TOP
Requirements
PHP 4
Your PHP must have socket support ('enable-sockets') compiled in. You'll need sendmail if you want Tiny Tool to email you or your subscribers. Global variables may be ON or OFF (global variables OFF is highly recommended). Set magic_quotes for your own comfort.
MySQL
You'll need an existing database and a database user. Tiny Tool requires one table which will be added to that existing database.
YOU
You yourself are the most important requirement of all. You should be familiar with phpMyAdmin. You should understand Web Host Manager (WHM). You will absolutely have to have thorough skill with some text editor and an FTP program. Be able to UN-zip a zipped archive. Have a PayPal account and understand the basic concept behind IPN.
If you have defined a few hosting packages in WHM, if you've created and terminated a few accounts by yourself, you probably understand that process well enough to know what the ultimate outcome of Tiny Tool should be.
If you have configured and installed some PHP programs, you should not have any trouble editing the required variables in the TinyTool config.php file.
And if you have created a MySQL database and added a database user to it, then you should be able to create the IPNlog table.
However, if you have never installed or 'tweaked' any PHP/MySQL programs before, then we must dissuade you from starting with a skeletal block of code like TinyTool. TinyTool attempts to pull together several complex subsystems: PayPal's IPN, CPanel's WHM, and MySQL, not to mention the sometimes problematic realm of Form Inputs and User Data Verification. You should be at least minimally familiar with the concepts behind each of those subsystems before you try to bend them to your will. For those persons who don't enjoy tinkering with code, the outright purchase of a commercially available program is perhaps a better value than a free GPL script.
TOP
Installing
The first step toward using Tiny Tool is to un-ZIP the distribution archive. We don't offer a tar or gzip archive because we would rather you take a look at Tiny Tool on your local machine before you bother putting it on your server. Both Macintosh and PC's will unzip with Aladdin Stuffit.
You will find Tiny Tool (First release, May 2004) un-zips into eight separate files:
config.php
Order.php
Process.php
Welcome.php
TOS.htm
IPNlog.sql
GNU-GPL.htm
Readme.htm
Item number 1, config.php, must be edited for Tiny tool to work with your particular system. The welcome page (Welcome.php) and the Service Agreement (TOS.htm) must be customized. Two HTML input forms are generated in Order.php; you'll surely want to change their appearance.
From the above list, only the first five files, items 1 through 5, must be uploaded.
Upload via FTP in the ASCII (text) mode, or upload using CPanel's File Manager
The five files are intended to reside in the same directory
The name of that directory is unimportant
The filenames may be changed, however the issue of renaming and moving files around needs further clarification.
If you decide to rename or move files outside the primary Tiny Tool directory, please note the following:
To change the name of config.php, find the single 'include' command line near the beginning of Process.php, Order.php, and Welcome.php. Change 'config.php' there to your new filename.
Since it contains extremely sensitive information, you may wish to put the config.php file outside your public access directory. To do so, change the single 'include' command line near the beginning of Process.php, Order.php, and Welcome.php.
In Process.php and in Welcome.php there is a 'header()' call that references Order.php. (When someone attempts to directly access either, they are dumped back into the order form.) Change this 'header()' command line if you change the name of Order.php.
TOP
Permissions -- The Tiny Tool directory probably needs permission set to 777 (Read/Write/Execute All). The files may need to be 755 (Read/Execute All, Write Owner), and perhaps as loose as 644. "May" and "probably" are purposely vague words because the permission settings you need could be different depending upon your server environment.
On our server Tiny Tool is using:
chmod 777 drwxrwxrwx the directory
chmod 644 -rw-r--r-- the files
Authors' Note: For security reasons we've set up our server so our users can not change ownership of files (CHOWN) by themselves. So we have specific ownership quirks to resolve. You may also.
Permission levels depend on ownership. For example, in our environment PHP programs run as user 'nobody' and PHP programs create processes owned by 'nobody.' Therefore, when Tiny Tool creates the SCRUB_log.php file (in which Tiny Tool logs failed attempts) that file is owned by 'nobody.' In order for another owner to edit the scrub file, the scrub file must have a CHMOD 777 permission level.
On the other hand, suppose we use a PHP-based editor such as Daniel Wacker's webadmin.php to access our files and directories. In our system webadmin.php runs as 'nobody' and can edit nobody's files with permission levels as low as 600, but NOT files owned by 'root' unless they are Read/Write All.
Issues related to ownership and permission crop up between one system and another. We would expect you to use all the security you possibly can while still being able to access the files in question for cleaning, maintenance, editing, and so forth.
TOP
Editing Files and Customizing Tiny Tool
You'll find Tiny Tool is useless if you do not fully customize the config.php file. We have included a sample Welcome page to instruct new users and a sample Terms Of Service Agreement, both of which need to have the fictional company called Power-Hosting-at-Basic-Prices (phabp.com) replaced by something more poetic.
First, something you are probably familiar with, but we'll remind you anyway... after editing config.php, or any other Tiny Tool module, save the file in ASCII mode with Unix line endings (\n newline).
The config.php file
There is a great deal to change in config.php so let's jump right in and take a close look at it.
MySQL Access: Perhaps obvious are the MySQL access variables at the beginning. You have most likely seen these settings before in other PHP configuration files. Provide the name of the database, the user you've added to that database, and that user's password. Generally your host is 'localhost.'
$db_name = "phabp_data";
phabp.com (Power-Hosting-at-Basic-Prices) is a fictitious company we use for demonstration purposes. Please put your database name between the quotation marks.
$db_user = "phabp_user";
Your database user. Don't forget to add the user to the database if you create them with CPanel.
$db_pass = "snackerly7";
Your password.
$db_host = "localhost";
Leave this as 'localhost' in most cases.
$db_table= "IPNlog";
The default name of the table created by the SQL code in IPNlog.sql. If you want to change the table name do so here in config.php AND in the CREATE TABLE line of IPNlog.sql.
TOP
WHM Access: To access WHM from Tiny Tool you must supply several values in config.php:
$whm_host = "localhost";
'Localhost' is the same entity used when addressing SQL. If you are sending instructions from a remote host, change $whm_usessl to '1' for yes, meaning you will be using SSL.
$whm_user = "toadybob";
$whm_user is the user name you use when you log on to WHM.
$whm_pass = "bebop";
$whm_pass is the password you use when you log on to WHM.
$whm_accesshash = "yb9fc20c08x5c8...c200f9c4r2843c";
Your Remote Access Key found in WHM. The access hash is several hundred hexadecimal digits that must be transcribed character for character without spaces or linebreaks.
$whm_usessl = 0;
'0'=no, '1'=yes. Set this to 1 if you are sending instructions from a remote host.
In Process.php Tiny Tool instructs CPanel's Accounting Module to create a new account with this line of code:
createacct($host, $user, $accesshash, $usessl, $acctdomain, $acctuser, $acctpass, $acctplan);
Variables such as $acctdomain, $acctuser and $acctplan are gleaned from the new subscriber's inputs during the signup process. Tiny Tool will generate their password ($acctpass) and email it to them.
Authors' Note: The CPanel PHP Accounting Module provides an API for manipulating certain WHM abilities with external PHP programs. The CPanel Accounting Module is versatile and talented, however it won't do everything associated with a user account. For example, in Welcome.php we want to do something in WHM that the Accounting Module can't. In that case we use another method -- we post directly to the URL for the WHM page we want to change. Both methods work fine. If you find your version of WHM doesn't respond to Tiny Tool it may be because the Accounting Module isn't being accessed; the URL method would then be useful.
TOP
The IP Factor: Most webhosts are setting up accounts called name accounts. Name accounts share one server IP address among many subscribers.
$IP_none = "255.255.255.255";
Put your server's shared IP address as the value for $IP_none in the configuration file. At the end of the signup process we'll include the IP information in the new subscriber's 'Welcome' message along with their account details. We've put a field in the SQL database for you to store a unique IP number for those subscribers that purchase one later.
TOP
PayPal Subscription Variables: Some of these variables are absolutely required in your initial POST to PayPal. The other variables are not required by PayPal but will be useful if you want specific results.
$post_to_URL = "www.eliteweaver.co.uk";
use this URL for testing
$post_to_URL = "www.paypal.com";
use this URL when you go live
$post_to_URL is the destination of the IPN response. It is a variable and not hard-coded into Process.php because, as you can see, one may wish to post to an IPN test site. Eliteweaver is by far the most comprehensive IPN test site the authors found. In fact, Tiny Tool would not exist without extensive testing with Eliteweaver's excellent IPN Test.
PayPal requires the following variables in every subscription order:
$business = "sales phabp com";
This is YOUR PayPal ID, or email address. This email address must be confirmed and linked to your Verified Business or Premier account. This address is where the money goes so we verify it's in the IPN when PayPal sends it back.
$no_note = "1";
According to PayPal documentation this variable is absolutely required for subscription processing. The field must be included, and the value must be set to 1 according to the PayPal Subscription manual.
Optionally use these variables to control certain circumstances:
$sra = "1";
ReAttempt on failure. If set to "1, " and the payment fails, the payment will be reattempted two more times. After the third failure, the subscription will be cancelled. If this variable is omitted entirely and a payment fails, no reattempt will occur and the subscription will be immediately cancelled. You will be informed by IPN every step of the way.
$src = "1";
ReCurring payments. If set to "1, " the payment will recur unless your customer cancels the subscription before the end of the billing cycle. If omitted, the subscription payment will not recur at the end of the billing cycle.
$srt = null;
Recurring Times. This is the number of payments which will occur at the regular rate. If omitted, the subscription will continue to renew at the regular rate until it is cancelled. Since endless renewal is the most frequently desired action, we set $srt to null (not the same as "" or an empty string) and let the program test for its presence with empty().
$no_shipping ="1";
Shipping address. If set to '1, ' your customer will not be prompted for a shipping address. If omitted or set to '0, ' your customer will be prompted to include a shipping address.
$rm = "2";
Return Method. Set to '2' makes all the Subscription variables available to your 'return' URL via POST method. Set to '0' or '1' and they are not. Return Method is often misunderstood. We encourage you to read page 36 of PayPal's new 2004 edition of the Subscriptions and Recurring Payments Manual (PDF format only). We use rm to make subscription variables available to our 'Welcome' page.
$modify = "0";
'0'= new subscription signup only, '1'= modify existing subscription only, '2'= modify existing or signup for new subscriptions. Here's another often misunderstood switch that can be useful. Read pages 21 and 38 of PayPal's new 2004 edition of the Subscriptions and Recurring Payments Manual (PDF format only). For example, you would set modify to '1' or '2' if you wanted subscribers to change from monthly installments to annual payments by themselves. (Hint: We left a 'hook' in Process.php where you could write in a modify routine.)
$currency_code = "USD";
Essential if your currency is something other than US Dollars. If omitted, it defaults to USD, so setting it to USD is actually redundant.
$on0 ="Domain Name";
Tiny Tool uses Option 0 to display the subscriber's domain name.
$on1 ="User Name";
Tiny Tool uses Option 1 to display the subscriber's logon name.
$return = "http://phabp.com/TinyTool/Welcome.php";
This is the complete URL of your welcome page. This is where customers will come back into your website after a successful subscription signup.
$cancel_return = "http://phabp.com/TinyTool/Special-offers.html";
This is the complete URL of a page on your website where PayPal sends users that don't complete the signup process. In other words, those users who cancel rather than complete the PayPal signup procedure. This page is your chance to re-sell a vacillating buyer.
TOP
Looking at Package Strings: This section is at the heart of Tiny Tool. Package strings make the whole PayPal/WHM interaction occur. Essentially, package strings are the PayPal variables that determine subscription price and duration.
For example, let's say that at our fictional company Power-Hosting-at-Basic-Prices we sell 3 hosting packages: Value, Major, and Primo. We offer Value and Major on monthly recurring payments or on a single annual payment. Primo we only offer annually. Here's the way we defined them in the config.php file:
$hosting_options = array (
"Vm" => array (
"a3"=>"6.00",
"p3"=>"1",
"t3"=>"M",
"item_name"=>'VALUE 50 MB and 5 GB for $6 per month',
"whm_name"=>'phabp_VALUE',
),
"Vy" => array (
"a3"=>"61.00",
"p3"=>"1",
"t3"=>"Y",
"item_name"=>'VALUE 50 MB and 5 GB for $61 per year',
"whm_name"=>'phabp_VALUE',
),
"Mm" => array (
"a3"=>"11.00",
"p3"=>"1",
"t3"=>"M",
"item_name"=>'MAJOR 100 MB and 10 GB for $11 per month',
"whm_name"=>'phabp_MAJOR',
),
"My" => array (
"a3"=>"112.00",
"p3"=>"1",
"t3"=>"Y",
"item_name"=>'MAJOR 100 MB and 10 GB for $112 per year',
"whm_name"=>'phabp_MAJOR',
),
"Py" => array (
"a3"=>"27.00",
"p3"=>"1",
"t3"=>"Y",
"item_name"=>'PRIMO 10 MB and 1 GB for $27 per year',
"whm_name"=>'phabp_PROMO',
),
);
We have put the five possible options that buyers could select into one large array called $hosting_options so we can traverse (walk) the selections with common PHP array functions. Let's dissect the five similar sub-arrays.
$hosting_options is made up of 5 associative arrays that use PayPal variable names as keys. Looking first at our Value plan we see two arrays define Value, first as monthly payments then as an annual term. We arbitrarily chose "Vm" and "Vy" as the name for these arrays. The name isn't important, it's simply a code passed around in Order.php so the program can parse the correct user-selected option.
It takes three values to tell PayPal how to charge your customers: $a3, $p3, and $t3 which are amount, period, and term. (If you use Subscription Trial Periods you would add values for $a1, $t1, $p1, and $a2, $t2, $p2.) In the case of Vy (Value yearly), it costs $61 paid once each year. Therefore amount $a3 is '61.00', period $p3 is 1, term $t3 'Y' for yearly (case sensitive!).
(You could offer subscribers that pay a year in advance two free months of service by defining a year thus: period $p3 = 14, term $t3 = 'M' which means they would only be billed every 14 months.)
The value assigned to $item_name is the phrase that will appear in the dropdown window on your HTML form. This phrase is also passed to PayPal and will forever appear on the buyer's monthly or annual receipts, so it should remind them what they are paying for.
$whm_name is the WHM package that will be activated when someone subscribes to this particular $hosting_option.
TOP
Discount Strings:
If you want to offer coupons, specials, or other discounts, Tiny Tool makes it easy. Essentially you will create a new package string and add it to a master array called $coupon_codes. Discount strings are just package strings, but with new values for the subscription variables. The coupon values overwrite the original price and duration values before the order is sent to PayPal.
Lets look at the discounts Power-Hosting-at-Basic-Prices offers:
$coupon_codes = array (
"legacy" => array (
"a3"=>"5.00",
"p3"=>"1",
"t3"=>"M",
"item_name"=>'Loyal Customer Discount -- 20% off',
"whm_name"=>'phabp_VALUE',
),
"student" => array
(
"a3"=>"7.00",
"p3"=>"4",
"t3"=>"M",
"srt" => "1",
"item_name"=>'PRIMO Student $7 per Semester',
"whm_name"=>'phabp_PROMO',
),
"b3g4" => array (
"a1"=>"18.00",
"p1"=>"3",
"t1"=>"M",
"a2"=>"0.00",
"p2"=>"1",
"t2"=>"M",
"a3"=>"6.00",
"p3"=>"1",
"t3"=>"M",
"item_name"=>'Spring Special -- Pay 3 months and get the 4th month FREE',
"whm_name"=>'phabp_VALUE',
),
);
'legacy' is our Loyal Customer 20% Discount which is probably self-explanatory. It just substitutes a monthly rate that is twenty per cent lower than the regular monthly rate.
Notice Power-Hosting's 'Student Special' is offered on a per semester basis and so it terminates after 4 months. This is done with the $srt variable. Normally, all subscriptions default to continuous, never-ending service, but we can override any default we wish in the $coupon_codes or in $hosting_options. PayPal sends Tiny Tool an IPN when a subscription terminates either by user cancellation or, as in this case, when End Of Term (eot) has been reached. When eot happens Tiny Tool tells the CPanel WHM to suspend (but NOT terminate) an account. You'll receive an email notice from PayPal as well as one from Tiny Tool when this happens. Should the 'student' wish to re-start, they could in effect un-suspend their account.
In the 'Buy 3 Get 4' special (sub-array '$b3g4'), we use PayPal's Subscription Trial Periods. To take advantage of this promotion the subscriber enters 'b3g4' in the Coupon Code box on the HTML Order Form. We instruct PayPal to charge for three months of service all at once, then give a free month of service. After that, subscribers are billed at the regular six-dollar-a-month rate for the Value plan.
None of the $coupon_codes appear in the dropdown selections; they remain invisible to new subscribers. The only way for a new subscriber to get a discount is to (a) know the proper code, and (b) type it into the blank on the HTML Order Form. Further verifying a subscriber's eligibility is beyond the scope of Tiny Tool. If you wanted, for example, to offer a Triple AAA discount or an employee discount you would have to incorporate some method of verifying a membership number or an employee number.
TOP
Changing the $head and $foot Strings:
The Order Form generated by Order.php begins and ends with $head and $foot respectively. Both $head and $foot are simply HTML code enclosed in PHP 'heredoc' syntax. The Tiny Tool authors use heredoc syntax often to define long passages of HTML code. There is no need for endless lines of echo() statements when you use the heredoc syntax. We consider the heredoc construct so important that we've included a longer, more detailed essay below in the Additional Commentary section of this Readme.
Since $head and $foot determine the appearance of your order page, you'll probably want to customize the HTML code in them.
TOP
Functions:
The essential Tiny Tool functions in config.php are ...
clean_domain($toclean)
Takes a potential domain name and strips away "http://" and "www." as well as any trailing directories and filenames. Returns the basic domain name dot TLD portion of a user input.
valid_domain($tocheck)
Takes the cleaned domain name (from above) and validates the TLD or CC extension. Accommodates all the valid Country Codes like .co.uk and it accommodates new TLDs like .info, .museum, and others.
valid_username($test)
A valid username in CPanel's Web Host Manager must start with a letter, be up to 8 characters long, alphanumeric only.
genpassword($length)
This particular incarnation of a random password generator alternates consonants and vowels to form a somewhat pronounceable password.
LIST_CONTENTS($array, $tab="    ", $indent=1)
Recursively displays contents of an array and sub-arrays. Our thanks go out to Peter Kionga-Kamau (http://www.pmkmedia.com) for this particularly attractive way to visualize array contents. He says it is free for unrestricted use, except sale. $array = array name, $tab = string to use as a tab, $indent = number of tabs to indent result. This function isn't used anywhere in Tiny Tool ... you can delete it. We left it here because it was essential during program development and we thought others might like to have it in their toolbox.
TOP
Two Forms in Order.php
The $flip and $flop strings are two large chunks of HTML in Order.php that produce forms for the user. Think of $flip as the Input form and $flop as the Output form. $flip is the form that gathers user inputs: domain name, user name, service option, et cetera. $flop arranges the cleaned and validated inputs on a recap screen for the subscriber's final approval. If approved, $flop POST's the data to PayPal. If the user does not approve, but instead goes back, the $flip form will still be populated with prior inputs so the user can make a change without filling in all the blanks again.
Since the HTML code has PHP values embedded, it needs to be parsed and re-evaluated each time it is sent to the user's browser. The PHP values in the $flip and $flop strings are not static and therefore cannot be delivered just once from the config.php. To change the form's appearance, you would edit Order.php, specifically the HTML in $flip and $flop.
[The Tiny Tool authors agree that <table> is a poor way to format an HTML page. We compromised ourselves for the sake of readability and expediency, which you would never do of course.]
TOP
The Welcome.php file
The sample Welcome page re-iterates the customer's subscription details and provides a few basic access instructions. This page isn't meant to be a tutorial, nor will it answer any deep questions. A good FAQ or some well-written articles will accomplish that better. Also, the CPanel.net documentation is readily available and well-written.
listpkgs() -- The CPanel PHP Accounting Module will list all the packages you have defined and will return an array of values for each package. The returned variables give you fifteen pieces of information:
[0] = dedicated IP, yes or no
[1] = CGI available, yes or no
[2] = Quota (disk space) in megabytes
[3] = FrontPage extensions enabled, yes or no
[4] = Theme
[5] = FTP Accounts
[6] = SQL Databases
[7] = Email Accounts
[8] = Email Lists
[9] = Sub-domains
[10] = Bandwidth in megabytes
[11] = Shell access, yes or no
[12] = Parked Domains
[13] = Addon Domains
[14] = Features List
Because some of these items are of interest to your subscribers, the Welcome.php page pulls specific items from the above list. Also this page provides basic user logon details for CPanel and some very basic Email information of immediate interest to new subscribers.
The Welcome.php page emails itself to the user in both Plain Text and Hyper Text formats. As with other large segments of HTML code in Tiny Tool, this page is drafted using php's heredoc syntax.
Of interest is the function called html2text() which translates the HTML into plain text. This is a useful function to have in your toolbox. We didn't put it in config.php with the other functions because it is only used on this one page and therefore just useless overhead in other program modules.
TOP
The TOS.htm file
Perhaps you intend your Terms Of Service to be a legal document. If so, consult an attorney. In some jurisdictions such a web page is at best only quasi-legal and semi-binding depending upon (a) how you enforce it, and (b) what laws govern contracts and torts where you operate and where your customer resides. For example, you could (God forbid) wind up in a courtroom on the wrong side of a tortious lawsuit for turning off some schmo's web site.
Proceed with caution. Be reasonable. Chop anything out of our sample page that doesn't sound right or isn't critical to your well-being. It may be better to operate with no agreement at all than to operate with one that isn't ironclad and 100% all-encompassing. The authors personally work with one reputable and very successful international hosting company that has absolutely no legal page or disclaimers at all.
TOP
Additional Commentary
Using heredoc Syntax
You'll find the $head and $foot strings in config.php, and the $flip and $flop strings in Order.php are defined with PHP's unusual 'heredoc' syntax. Read more about heredoc in the PHP manual. We frequently use heredoc to define large blocks of HTML because...
we can easily cut-and-paste fully refined code from an HTML page into a PHP program
we need only a single heredoc start and stop tag, not endless lines of echo() or .= instructions
heredoc simplifies using double quotes in our HTML without escaping them
heredoc simplifies embedding PHP variables in HTML
We've excerpted this from the PHP manual: "... heredoc text behaves just like a double-quoted string ... this means that you do not need to escape quotes in your here docs". The PHP manual also says: "... variables are expanded, but ... care must be taken when expressing complex variables ..." [which means variables may need curly braces '{' and '}' around them].
A heredoc definition starts with "<<<identifier." The identifier word can be any valid variable name like 'content, ' 'Burger_King, ' or '_jitterbug.' The heredoc string continues until it encounters the identifier word again on a line by itself. Here's how the PHP manual puts it:
"It is very important to note that the line with the closing identifier contains no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs after or before the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by your operating system."
TOP
Your PayPal Setup
Don't forget to:
Enable IPN under your business account's Profile tab. The URL you'll use there is the complete Tiny Tool URL (for example: http://your.domain.com/TinyTool/Process.php).
Let's pause for a short commercial announcement.
We use PayPal because we don't want to spend a lot of time keeping books and tracking customer accounts. PayPal keeps a ledger of our Subscribers, provides us with statements and up to the minute balances on demand. PayPal manages recurring payments, debits bankcards on time, and re-attempts failed transactions. PayPal takes care of the SSL and provides maximum security for our Subscribers. PayPal does our screening for us by verifying the Subscriber's address and bankcard. That makes us confident we are supplying legitimate buyers, not rip-off artists, scammers or SPAM ho's.
PayPal serves our customers by providing them with an account they can use almost everywhere on the Internet. PayPal watches our customers' bankcard expiration date which keeps them up to date, thus helping us retain them with no hassle at all. We even like PayPal Shops and EBay which provide our customers other goods and services that may interest them. And is any other payment processor FDIC insured?
PayPal does all this for a tiny percentage of each sale. In fact, PayPal takes far less than our bank would if we asked them to process Visa and MasterCard for us.
PayPal sends us email for every transaction. That alone would be enough, but they've gone the extra mile with super-simple Subscription Buttons and IPN. Where else on the Web can you get instant notification for free with PayPal's degree of security. And no one else provides documentation and support equal to PayPal.
That's at least ten good reasons why we (and four million other merchants) use PayPal exclusively.
End of commercial.
TOP
Pre-deployment Testing
Tiny Tool is a small program that executes some complex tasks. It sends and receives data behind the scenes that is critical to your business, your image, and your customers' well-being. You will benefit greatly from extensive testing. The Tiny Tool authors recommend you test Tiny Tool until you feel quite confident that it is functioning properly 100% of the time over a wide range of inputs and in all circumstances.
Live test your installation. No two ways about it. Go through the subscription process several times yourself to see if the accounts are being created properly in WHM.
You may pay your PayPal business account with your PayPal Personal account as long as they are tied to separate bank accounts or separate credit cards.
Another method is to enlist a friend's help. Afterward, go to PayPal and cancel their subscription(s) and refund the money to their bankcard.
Read the PayPal IPN Manual (PDF format only), pages 19 and 20, for testing tips that you cannot afford to ignore.
Bear in mind that nuances in your server's setup may cause Tiny Tool to behave differently from how it acts in our environment. If it doesn't exactly fit your needs as it is, perhaps it will at least be a helpful starting place. It's our sincere hope that we'll see other minds working on Tiny Tool and changing the code...
to accommodate a wider range of environments
to offer more functions
to improve its human interface
TOP
Security
Tiny Tool uses a simple and effective method for dis-allowing internet passers-by from directly accessing your Process.php file and triggering their own account creation. Users must first go through the Order.php process which creates an SQL record. If that initial record isn't in your database when an IPN-like posting is received by Process.php then it ignores the request.
Additionally, whenever a legitimate user touches the SQL database via the Order.php program, a unique number is generated that must then be present in any IPN post coming to Process.php. (PayPal uses much the same method when they pass a hashed (encoded) IPN value called verify_sign. They expect to get that same value back.)
The processing program also verifies that the other subscription parameters match. In other words, a subscriber can only get the service paid for, not some high-grade service at a cheaper price by fabricating a phoney IPN to Tiny Tool.
TOP
Flow Charts and Logic
The following charts approximate the logic flow in the Order.php and Process.php files:
File: Order_Form.php
=======================
if $_POST['package'] ( presence of $package indicates form data was submitted )
set error_tally and localize $_POST['vars']
switch($package):
sift through your services and set package parameters
endswitch;
// Next, we validate 3 pieces of data: domain name, user name, and
// compliance with a Service Agreement.
// On error, we increment $error_tally.
if domainname was submitted:
clean away any overhead like 'http://' or 'www' or trailing directory names, then
validate the remaining alpha-numeric content and the TLD or Country Code
look through database to see if we've processed it before -- if so, reset form.
// Since we create a database record for every domain name we send to PayPal,
// and potential subscribers may cancel out before they complete the entire
// subscription ritual, we should clean them out from time to time. However, if that
// previous record is still hanging around, we retrieve it and simply assume the
// potential customer is vacillating or got interrupted somewhere along the way.
if username is sent, validate length, alpha-numeric content, and
look through database to make sure it is unique
if 'terms' checkbox is checked, they've read our Service Agreement
if $error_tally is zero it means the data is error free
create a new database record
generate a 'last look' screen for the enduser to double check their entries:
they can go back and edit or
they can continue on to PayPal
-----------------------------------------------------------------------------------------------
else
there's no data to validate so we present the initial data entry form and
post that form back to this program for validation
-----------------------------------------------------------------------------------------------
// the end of Order.php
File: Process.PHP
=======================
if empty ( $_POST['txn_type'] )
save this event in the spoof file (SCRUB)
exit to Order.php
else
set static vars for $db: db_name, db_user, db_pass, db_host, db_table
set $business_email and $paypalURL,
make $postipn string
make $header string
open socket
post $domain.$header.$postipn to PayPal
get $response string
close socket
localize $_POST['vars']
if ( $response == VERIFIED && business_email_address is correct )
| open DataBase
| search DB for txn_id
| if ( txn_id NOT found )
| : search DB for item_number
| : if ( item_number found )
| : , switch($payment_status):
| : , . case 'Completed';
| : , . switch txn_type
| : , . subscr_payment
| : , . if ( valid payment_gross )
| : , . update DB record
| : , . subscr_failed (payment failed. retry twice then subscr_eot)
| : , . update DB record
| : , . subscr_signup
| : , . if ( valid period3 ) && ( valid amount3 )
| : , . update database record
| : , . close database
| : , . post setup variables to WHM's create account function
| : , . subscr_cancel
| : , . update DB record
| : , . send so-long email to subscriber
| : , . select future-date to terminate WHM acct
| : , . email webmaster
| : , . subscr_eot
| : , . update DB record
| : , . send so-long email to subscriber
| : , . select future-date to terminate WHM acct
| : , . email webmaster
| : , . subscr_modify
| : , . default: send_money, web_accept, cart ( shouldn't ever happen )
| : , . endswitch
| : , . close DB
| : , . exit
| : , . break
| : , . case 'Pending';
| : , . switch pending_reason:
| : , . echeck; break;
| : , . intl; break;
| : , . verify; break;
| : , . address; break;
| : , . upgrade; break;
| : , . unilateral; break;
| : , . other (default);
| : , . endswitch;
| : , . break;
| : , . case 'Failed'; // e-check failed/declined by bank ; break;
| : , . case 'Refunded'; // merchant refunds ; break;
| : , . case 'Canceled'; // e-check failed/declined by bank ; break;
| : , . case 'Denied'; // merchant denies for one of the pending reasons ;
| : , endswitch;
| : close $DB
-----------------------------------------------------------------------------------------------
Everything that's NOT a legitimate payment ( like INVALID, spoofs, and
code errors ) go into a 'spoof' file.
Anything that falls through the sieve above goes into the 'spoof' file for further investigation.
Append date, $response, $_POST['vars'] and $_SERVER['vars'] into spoof file
Send email to webmaster.
exit
-----------------------------------------------------------------------------------------------
// the end of Process.php
TOP
Other Web Hosting Tools Scripts: