Software, your way.
How To Get Good Custom Software
(Download)
(PDF)
burger menu icon
WillMaster

WillMaster > LibraryMarketing With Software

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

PayPal Coffee Fund Button

Probably you've seen appeals to contribute to a coffee fund on websites. They generally are used in lieu of donation or contribution requests.

If you have a PayPal account, this article describes how to implement the feature on your web sites.

When you have this implemented, consider obtaining or creating a downloadable gift of value and making the download available on your PayPal payment thank-you page. Properly introduced on your website, it may get a bunch of extra coffee-fund contributions.

The system lets you log the submitted form information. The system also lets you get an email with the form information.

To implement, two things are needed:

  1. A form to specify the amount they want to contribute.

  2. A PHP script to handle the contribution form submission.

Here is an example form — not activated because we aren't asking for a contribution here. (The source code is much further below.)

Select an amount here:

Or use this to specify an amount:
$

Before a coffee-fund form can work, the PHP script to handle the form submission needs to be installed.

The primary reason for using the PHP script (instead of submitting the form directly to PayPal) is to hide sensitive information like your PayPal email address and your thank-you page URL. (The thank-you page URL should generally be hidden if you are giving away downloads specifically for those who contribute to your coffee fund.)

The PHP script also lets you log the submitted form information. Further, form information can be sent to you via email.

Therefore, let's get the PHP script installed. Then, you can publish your form and accept coffee-fund contributions.

The PHP Script

The source code is below. Save the PHP script as coffee.php or, if you prefer, a different *.php file name. (The instructions assume a coffee.php file name.) Below the source code are customization notes.

<?php
/*
    PayPal Coffee Fund Form Handler
    Version 1.0
    December 30, 2022
    Will Bontrager Software LLC
    https://www.willmaster.com/
*/

/* Customization section */

// Specify the minimum donation.
//    If blank, the software will assume 1.00.
$MinimumPayment = 3.00;

// Specify what to do when the person specifies more than one payment amount on the 
//    form, such as a dropdown selection and also an "other amount" specification.
// Specify "low" or "l" (letter "l") to send the lowest amount to PayPal.
// Specify "high" or "h" to send the highest amount to PayPal.
// Specify "total" or "t" to send the total of all amounts to PayPal.
// If blank, "total" is assumed.
$MultipleAmountHandling = "high";

// Specify your PayPal email address or your PayPal Merchant ID, 
//    so PayPal knows where to send the money.
$PayPalMerchantID = "paypal@example.com";

// Specify the URL the buyer's browser shall go to after payment is arranged.
$AfterPaymentURL = "https://example.com/appreciate.php";

// Specify the URL the buyer's browser shall go to if they decide not to follow through.
$ProcessCanceledURL = "https://example.com/";

// The name to use for the contribution/donation.
//    If left blank, the software will make one up.
$ItemName = "Coffee contribution for example.com";

// The item id to be used.
//    If left blank, the software will make one up with mostly random characters.
$ItemID = "COFF";

// Specify the currency you want to be paid in.
//    If left blank, "USD" will be used.
$CurrencyCode = "USD";

// Specify where to send an email with all submitted form information.
//    Leave blank for no email.
//    Note: A few, very few, hosting companies remove the PHP mail() 
//      functionality, in which case this software could not send email.
$EmailDestination = "name@example.com";

// Specify the subject line to use when an email is sent with submitted form information.
//    If blank, the software will make one up.
$DestinationEmailSubject = "Coffee Contribution! Yay!";

// Specify where a log should be at (formatted CSV). Leave blank for no log file.
$LogFileLocation = "CoffeeContributions.csv";

/* End of customization section. */

date_default_timezone_set('UTC');
if( empty($_POST) and (count($_POST)<2) ) { echo 'Inappropriate Access'; exit; }
mb_regex_encoding('UTF-8');
mb_internal_encoding('UTF-8');
if( empty($PayPalMerchantID) ) { echo 'Setup has not been completed.'; exit; }
if( empty($MinimumPayment) or $MinimumPayment<1.00 ) { $MinimumPayment = '1.00'; }
if( $MultipleAmountHandling ) { $MultipleAmountHandling = substr(strtoupper($MultipleAmountHandling),0,1); }
if( empty($MultipleAmountHandling) or (!preg_match('/[LHT]/',$MultipleAmountHandling)) ) { $MultipleAmountHandling = 'T'; }
if( empty($EmailDestination) or (!preg_match('/[\w\-\_]\@[\w\-\_].*?\.[\w\-\_]/',$EmailDestination)) ) { $EmailDestination = false; }
if( empty($DestinationEmailSubject) ) { $DestinationEmailSubject = 'Contribution/Donation'; }
if( empty($LogFileLocation) ) { $LogFileLocation = false; }
if( empty($AfterPaymentURL) ) { $AfterPaymentURL = ((isset($_SERVER['HTTPS']) and $_SERVER['HTTPS']=='on') ? 'https://':'http://') . "{$_SERVER['HTTP_HOST']}/"; }
if( empty($ProcessCanceledURL) ) { $ProcessCanceledURL = preg_replace('![^/]*$!','',$AfterPaymentURL); }
if( empty($ItemName) ) { $ItemName = 'Contribution/Donation'; }
if( empty($ItemID) ) { $ItemID = 'CONTRIB'; }
if( empty($CurrencyCode) ) { $CurrencyCode = 'USD'; }
$Lowest = $Highest = $Total = 0.0;
$FieldsList = array();
$Names = $Numbers = array();
foreach( $_POST as $k => $v )
{
   if( preg_match('/_(x|y)$/',$k) or preg_match('/^(x|y)$/',$k) ) { continue; }
   if( preg_match('/_CDform$/',$k) )
   {
      foreach( $v as $kk => $vv )
      {
         $vv = floatval(preg_replace('/[^\.\d]/','',$vv));
         if( $vv<$Lowest or $Lowest==0.0 ) { $Lowest = $vv; }
         if( $vv>$Highest or $Highest==0.0 ) { $Highest = $vv; }
         $Total += $vv;
         $FieldsList[] = $k . '[] = ' . $vv;
      }
   }
   else
   {
      if( preg_match('/\n/',$v) )
      {
         $v = str_replace("\r",'',$v);
         $v = str_replace("\n","\r\n",$v);
      }
      $FieldsList[] = "$k = $v";
   }
}
$Charge = $Total;
if( $MultipleAmountHandling == 'L' ) { $Charge = $Lowest; }
if( $MultipleAmountHandling == 'H' ) { $Charge = $Highest; }
if( $MinimumPayment > floatval($Charge) )
{
   echo "The minimum payment is \$$MinimumPayment";
   exit;
}
array_unshift($FieldsList,'-- Form field values --');
array_unshift($FieldsList,"The item id: {$ItemID}");
array_unshift($FieldsList,"The item name: {$ItemName}");
if( $LogFileLocation )
{
   $LogLine = array();
   $LogLine[] = str_replace('"','""',date('r'));
   $LogLine[] = $_SERVER['REMOTE_ADDR'];
   $LogLine[] = str_replace('"','""',$ItemID);
   $LogLine[] = str_replace('"','""',$ItemName);
   $LogLine[] = str_replace('"','""',$AfterPaymentURL);
   $LogLine[] = $Total;
   $LogLine[] = $Charge;
   $LogLine[] = str_replace('"','""',implode("\r\n",$FieldsList));
   $LogLine[] = str_replace('"','""',$_SERVER['HTTP_USER_AGENT']);
   file_put_contents($LogFileLocation,'"'.implode('","',$LogLine)."\"\r\n",FILE_APPEND);
}
if( $EmailDestination )
{
   array_unshift($FieldsList,'Date and time: '.date('r'));
   mail($EmailDestination,$DestinationEmailSubject,implode("\r\n\r\n",$FieldsList),"From: $EmailDestination");
}
$items = array();
$items[] = "amount=$Charge";
$items[] = 'item_name='.rawurlencode($ItemName);
$items[] = 'item_number='.rawurlencode($ItemID);
$items[] = 'return='.rawurlencode($AfterPaymentURL);
$items[] = 'cancel_return='.rawurlencode($ProcessCanceledURL);
$items[] = 'business='.rawurlencode($PayPalMerchantID);
$items[] = "currency_code=$CurrencyCode";
$items[] = 'no_shipping=0';
$items[] = 'charset=UTF-8';
$items[] = 'no_shipping=1';
$PayPalURL = 'https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&'.implode('&',$items);
if( headers_sent() ) { echo "<script>location.href='$PayPalURL';</script>"; }
else { header("Location: $PayPalURL"); }
exit;
?>

Customization notes: Each of the customization spots within the above coffee.php source code has instructions. I'll go over them here.

  1. $MinimumPayment = 3.00;
    

    Replace 3.00 with the minimum amount for the PayPal payment (digits and period only, no currency symbol). If left blank, 1.00 will be assumed.

  2. $MultipleAmountHandling = "high";
    

    Your form might have two or more payment-amount fields. Perhaps there is a radio button choice and also a text field to type in an alternate amount.

    JavaScript could be used to ensure only one payment amount is submitted. But if you don't want to write custom JavaScript, this customization can tell the PHP script what to do if it receives more than one payment amount.

    The "high" value tells the script to choose the highest amount for the PayPal payment. If you change "high" to "low" then the lowest amount will be chosen. And, if you change "high" to "total" then the total of all amounts will be chosen for the PayPal payment.

    If the value is blank, then the total of all amounts will be chosen for the PayPal payment.

  3. $PayPalMerchantID = "paypal@example.com";
    

    Replace "paypal@example.com" with either your PayPal email address or your PayPal Merchant ID. Either will work to tell PayPal where to send your money.

    If you wish to find your PayPal Merchant ID:

    • At your PayPal merchant control panel, tap Account Settings for a dropdown. (Account Settings will probably be found with the account name.)

    • Find Business Profile and tap on Business information.

    • Copy the PayPal Merchant ID.

  4. $AfterPaymentURL = "https://example.com/appreciate.php";
    

    Replace "https://example.com/appreciate.php" with the URL to your thank-you page — the URL the buyer's browser shall go to after payment is arranged. (On the thank-you page is where you might provide a download in appreciation.)

    If left blank, PayPal is likely to send the browser somewhere related to your website.

  5. $ProcessCanceledURL = "https://example.com/";
    

    Replace "https://example.com/" with the URL the buyer's browser shall go to if they cancel their intent to pay.

    If left blank, coffee.php will make one up.

  6. $ItemName = "Coffee contribution for example.com";
    

    Replace "Coffee contribution for example.com" with an item name for use by PayPal and for your recognition.

    If left blank, coffee.php will make one up.

  7. $ItemID = "COFF";
    

    Replace "COFF" with an item id or number for use by PayPal and for your recognition.

    If left blank, coffee.php will make one up.

  8. $CurrencyCode = "USD";
    

    Replace "USD" with the currency abbreviation you want to be paid in ("USD" stands for "United States Dollar").

    If left blank, coffee.php will use USD.

  9. $EmailDestination = "name@example.com";
    

    If you want the PHP script to send you an email with the submitted form information, replace "name@example.com" with the email address to use.

    If this is left blank, no email will be sent.

  10. $DestinationEmailSubject = "Coffee Contribution! Yay!";
    

    Replace "Coffee Contribution! Yay!" with the email subject line to use whenever you are sent an email with the submitted form information.

    If this is left blank, coffee.php will make one up.

  11. $LogFileLocation = "CoffeeContributions.csv";
    

    If you want the PHP script to maintain a log file of submitted form information, replace "CoffeeContributions.csv" with the file location for the log. If left as is, the file name will be "CoffeeContributions.csv" located in the same directory as the PHP script. For other locations, correct directory information needs to be specified.

    The file information is formatted as CSV (comma-separated values) for relatively easy importing into spreadsheet software.

    If this is left blank, no log file is maintained.

When the customization has been done to your satisfaction, upload coffee.php to your server. Make a note of its URL (for use in the form).

The Form

The field name of every form field intended for a payment amount must end with:
_CDform[]
Here are payment-amount field examples from the earlier example form, a select dropdown for selecting an amount and a text field for typing in an amount:

Select an amount here:<br>
<select name="selected_contribution_CDform[]" style="font-size:1em; margin-bottom:.5em;">
<option value="0">- Selections -</option>
<option value="9.00">$3.00</option>
<option value="5.00">$5.00</option>
<option value="7.00">$7.00</option>
<option value="15.00">$15.00</option>
</select><br>
Or use this to specify an amount:<br>
$<input type="text" name="give_other_CDform[]" inputmode="numeric" pattern="[\d\.]*" title="Only numbers and periods; no $ symbol." style="max-width:150px; min-width:70px;">

The names of all other fields in the form must not end with _CDform[].

Any information in form fields with names that do not end with _CDform[] is not sent to PayPal. But the information is included in the optional email that coffee.php sends to you and/or in the data of the optional log file coffee.php maintains for you.

Minimum Form

A payment amount field and a submit button are the minmum to make the form work.

Here is an example of a minimum form.

Here is source code for you to put the above form on your web page.

<form method="post" action="[URL to your coffee.php installation]">
<select name="selected_contribution_CDform[]" style="font-size:1em; margin-bottom:.5em;">
<option value="0">- Select Amount -</option>
<option value="3.00">$3.00</option>
<option value="10.00">$10.00</option>
<option value="15.00">$15.00</option>
<option value="25.00">$25.00</option>
<option value="50.00">$50.00</option>
</select> 
<input type="submit" value="Donate to Coffee Fund">
</form>

In the above source code, replace [URL to your coffee.php installation] with the URL to the installation of coffee.php on your server.

Example Form Source Code

If you wish to duplicate the example form near the top of this article, here is the source code.

<form method="post" action="[URL to your coffee.php installation]">
<p>
Select an amount here:<br>
<select name="selected_contribution_CDform[]" style="font-size:1em; margin-bottom:.5em;">
<option value="0">- Selections -</option>
<option value="9.00">$3.00</option>
<option value="5.00">$5.00</option>
<option value="7.00">$7.00</option>
<option value="15.00">$15.00</option>
</select><br>
Or use this to specify an amount:<br>
$<input type="text" name="give_other_CDform[]" inputmode="numeric" pattern="[\d\.]*" title="Only numbers and periods; no $ symbol." style="max-width:150px; min-width:70px;">
</p>
<p>
<input type="submit" value="Buy Coffee for the Staff">
</p>
</form>

As for the previous source code, replace [URL to your coffee.php installation] with the URL to the installation of coffee.php on your server.

Additional Form Fields

As alluded to earlier, you may have form fields in addition to fields that specify an amount. An email field and a textarea field are examples. These form fields have names that do not end with _CDform[] or with _CDform.

Fields that do not end with _CDform[] will not be sent to PayPal and will not be used to determine amount information.

All named fields and values (except unchecked checkboxes, because browsers don't send that information to a script), whether or not ending with _CDform[], will be sent in the optional email that coffee.php sends and will be recorded in the optional log file that coffee.php maintains.

Here is an example form with additional fields.

Email (so we can thank you personally):

Tap an amount:

Optional note to website personel:

And here is the source code for the example.

<form method="post" action="[URL to your coffee.php installation]">
<p>
Email (so we can thank you personally):<br>
<input type="email" name="email" required style="max-width:300px; min-width:250px;">
</p>
<p>
Tap an amount:<br>
<label><input type="radio" name="myradio_CDform[]" value="7.00">$7.00</label> 
<label><input type="radio" name="myradio_CDform[]" value="13.00">$13.00</label> 
<label><input type="radio" name="myradio_CDform[]" value="30.00">$30.00</label> 
<label><input type="radio" name="myradio_CDform[]" value="90.00">$90.00</label>
</p>
<p>
Optional note to website personel:<br>
<textarea name="message" style="height:1in; max-width:300px; min-width:250px;"></textarea>
</p>
<p>
<input type="submit" value="Coffee Fund Contribution">
</p>
</form>

Replace [URL to your coffee.php installation] with the URL to the installation of coffee.php on your server.

When you have a form ready, insert it into the source code of a web page (or into a "Custom HTML" block for a WordPress article or widget area) and test it. For the test, funds need to come out of a credit card or out of a PayPal account different than the account that is receiving the money.

I wish you luck in your funding endeavors.

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC