]> granicus.if.org Git - php/commitdiff
new credit card processing module for TrustCommerce
authorDan Helfman <witten@php.net>
Wed, 17 Jul 2002 22:07:05 +0000 (22:07 +0000)
committerDan Helfman <witten@php.net>
Wed, 17 Jul 2002 22:07:05 +0000 (22:07 +0000)
http://trustcommerce.com/tclink.html

ext/tclink/README [new file with mode: 0644]
ext/tclink/config.m4 [new file with mode: 0644]
ext/tclink/doc/TCDevGuide.html [new file with mode: 0644]
ext/tclink/doc/TCDevGuide.txt [new file with mode: 0644]
ext/tclink/php_tclink.c [new file with mode: 0644]
ext/tclink/php_tclink.h [new file with mode: 0644]
ext/tclink/tcexample.php [new file with mode: 0644]
ext/tclink/tclink.c [new file with mode: 0644]
ext/tclink/tctest.php [new file with mode: 0644]

diff --git a/ext/tclink/README b/ext/tclink/README
new file mode 100644 (file)
index 0000000..ecb0ca4
--- /dev/null
@@ -0,0 +1,65 @@
+
+
+                                TCLink v3.3
+                             PHP Implementation
+                       copyright (C) TrustCommerce 2002
+                         http://www.trustcommerce.com
+                         developer@trustcommerce.com
+
+                                July 17, 2002
+
+I. DESCRIPTION
+
+  TCLink is a thin client library to allow your e-commerce servers to
+connect to the TrustCommerce payment gateway easily and consistently.
+The protocol (which is the same across all platforms and languages) is
+well-documented in the Web Developer's Guide, so please consult it for
+any questions you may have about the protocol syntax itself.
+
+  If you are using Python on Win32, do not use this client.  Please
+download the COM object from the Vault website instead.
+
+  TCLink was originally ported to PHP by Andrew Barnett of Data Clarity.
+Thanks go to both him (for the code) and his business (for their support
+of open source).
+
+
+II. COMPILATION
+
+  If you would like to recompile PHP with support for TCLink, be sure
+to run "./configure --with-openssl" first, as TCLink relies on OpenSSL.
+Note that if your PHP installation already includes TCLink, there is
+no need to do any compilation.
+
+
+III. INSTALLATION
+
+  If you have root access to the machine, you will probably want to
+install TCLink as a global extension.  You can do this by copying the
+module library (modules/tclink.so) to your PHP extensions directory
+(typically /usr/lib/php4) if it is not already installed there by
+default.  Your extensions directory is defined by the "extension_dir"
+directive in php.ini.
+
+  Edit php.ini (typically found in /etc) and add the following line:
+
+    extension=tclink.so
+
+  Restart your webserver, and all PHP scripts will have access to TCLink.
+
+  If you can't or don't want to install the module system wide, you can
+still load it manually in each script that needs to access it through
+the dl() call.  See the top of tctest.php for an example.
+
+
+IV. USAGE
+
+  The tctest.php script shows a simple example of running transactions
+through the TCLink API.  A more complex example is contained in
+tcexample.php.  For further information, please consult the TC
+Developer's Guide, located in the doc subdirectory.
+
+  A note to users of TCLink PHP prior to 3.3: the API has changed from
+the C-style interface, to a single tclink_send() function which accepts
+a hash (associative array) of input parameters, and returns a hash with
+the output parameters.  Please see the examples to update your code.
diff --git a/ext/tclink/config.m4 b/ext/tclink/config.m4
new file mode 100644 (file)
index 0000000..2cd1286
--- /dev/null
@@ -0,0 +1,6 @@
+if test "$PHP_TCLINK" != "no"; then
+  PHP_NEW_EXTENSION(tclink, tclink.c, $ext_shared)
+  TCLINK_SHARED_LIBADD="-lcrypto -lssl"
+  PHP_SUBST(TCLINK_SHARED_LIBADD)
+  AC_DEFINE(HAVE_TCLINK_EXT,1,[ ])
+fi
diff --git a/ext/tclink/doc/TCDevGuide.html b/ext/tclink/doc/TCDevGuide.html
new file mode 100644 (file)
index 0000000..2a02563
--- /dev/null
@@ -0,0 +1,1039 @@
+<html>
+
+<head>
+<title> TrustCommerce Developer's Guide 2.2 </title>
+</head>
+
+<body bgcolor=white text=black link=blue vlink=darkblue>
+
+<hr>
+<h1>TrustCommerce Developer's Guide 2.2</h1>
+<a href=http://www.trustcommerce.com>http://www.trustcommerce.com</a><br>
+<a href=mailto:developer@trustcommerce.com>developer@trustcommerce.com</a><p>
+January 25, 2002<br>
+
+<hr><p>
+
+<h2>Table of Contents</h2>
+<table>
+       <tr><td> <a href=#intro>I. Introduction</a> </td></tr>
+       <tr><td> <a href=#tclink>II. Connecting via TCLink</a> </td></tr>
+       <tr><td> <a href=#transtypes>III. Transaction Types</a> </td></tr>
+       <tr><td> <a href=#inputparam>IV. Input Parameters</a> </td></tr>
+       <tr><td> <a href=#returnparam>V. Return Parameters</a> </td></tr>
+       <tr><td> <a href=#sales>VI. Credit Card Preauths and Sales</a> </td></tr>
+       <tr><td> <a href=#cvv>VII. Card Verification Value (CVV)</a> </td></tr>
+       <tr><td> <a href=#cardpresent>VII. Card-Present Transactions</a> </td></tr>
+       <tr><td> <a href=#ach>IX. ACH</a> </td></tr>
+       <tr><td> <a href=#credits>X. Postauths, Credits, and Chargebacks</a> </td></tr>
+       <tr><td> <a href=#billingids>XI. Billing IDs</a> </td></tr>
+       <tr><td> <a href=#recurring>XII. Recurring Billing</a> </td></tr>
+       <tr><td> <a href=#wallet>XIII. TCS Wallet</a> </td></tr>
+       <tr><td> <a href=#fulfillment>XIV. Automated Fulfillment</a> </td></tr>
+       <tr><td> <a href=#query>XV. Vault Query API</a> </td></tr>
+       <tr><td> <a href=#testdata>Appendix A - Test Data</a> </td></tr>
+       <tr><td> <a href=#troubleshooting>Appendix B - Troubleshooting</a> </td></tr>
+       <tr><td> <a href=#httpspost>Appendix C - Connecting via HTTPS POST</a> </td></tr>
+       <tr><td> <a href=#currency>Appendix D - Currency Table</a> </td></tr>
+</table>
+
+<hr><p>
+
+<a name=intro></a><h2>I. Introduction</h2>
+
+
+
+       This guide covers the TrustCommerce transactional processing API.  It is platform- and language-neutral.  If you are a developer programming processing functionality to a software package or website, then this guide is for you.  If you are connecting via a pre-integrated commerce package, including shopping carts such as StoreForge, Mal's e-Commerce, PDG Cart, or AllCommerce, then you do not need this document.
+<p>
+       Definitions of credit card processing terms and information about the Vault website are contained in the TrustCommerce User's Guide, and will not be covered here.  If you are not familiar with the basics of credit card processing (such as the difference between an auth and capture), then you should probably read the User's Guide first.  The User's Guide also describes use of the Vault website's reporting capabilities, which you may find useful to confirm that your test transactions are working as expected.
+<p>
+       There are two methods of connecting to the TrustCommerce gateway at the programming level: the TCLink client software, and an HTTPS POST to the Vault server.  TCLink is HIGHLY recommend, as it offers support for TrustCommerce's unique features such as automated failover and enhanced security through server certificate verification.  It's available for many platforms and languages, and installation is straightforward, so you should try to use it if possible.  If you are unable to use TCLink for whatever reason, the HTTPS POST method will still allow you to access most features of the TrustCommerce processing engine, but be aware that it cannot match the speed and especially the reliability of TCLink.
+<p>
+
+
+
+<a name=tclink></a><h2>II. Connecting via TCLink</h2>
+
+
+
+       The TCLink API is available for download from the Vault website, in the "Downloads" section.  Be sure to chose the version that matches the platform and language that you are using.  In particular, Win32 developers will probably always want the COM object, which contains support for a number of different languages on the Win32 platform, including ASP, ColdFusion, Perl, PHP, and Python.
+<p>
+       Installation instructions specific to the TCLink version you've downloaded can be found in the readme file contained with the archive.  It will also contain a version of the TCTest program specific to the language you're using.  It's highly recommended that you look over this example, and even use it as the basis for your own code.  In fact, you should look over the code sample first to get a feel for the API, then return to reading this document.
+<p>
+       Versions of TCLink for high-level languages (including PHP, Perl, Python, and Java) with built in support for hashes only have one method: Send().  This method accepts a single parameter, a hash of input values, and returns a single parameters, a hash of output values.  The only other method avaliable is GetVersion(), which returns the version string for TCLink.
+<p>
+       TCLink for other languages (including C/C++, Win32 COM, and CFX) contains four basic methods: Create(), PushParam(), Send(), and GetResponse().  C-style TCLink functions are described in the table below.
+<p>
+
+
+
+       <center><h3>TCLink Function Names</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th> Function Name </th><th> Description </th></tr>
+       <tr><td> CreateLink() </td><td> Create a new transaction handle. </td></tr>
+       <tr><td> PushParam() </td><td> Push a parameter into the transaction. </td></tr>
+       <tr><td> Send() </td><td> Submit a transaction to the gateway. </td></tr>
+       <tr><td> GetResponse() </td><td> Retrieve a response parameter from the transaction. </td></tr>
+       <tr><td> GetEntireResponse() </td><td> Get the entire response for the transaction, primarily use for debugging or logging. </td></tr>
+       <tr><td> GetVersion() </td><td> Get the version string for the TCLink API in use. </td></tr>
+       </table>
+<p>
+
+
+
+       These four methods map to the four stages of running a transaction: initialize, push a number of parameters describing the transaction, send the transaction to the TrustCommerce gateway for processing, and finally get details about the transaction results.
+<p>
+       The only method which contacts the TC servers is Send().  This function will block for one or two seconds while the transaction is processed.  Afterward, you can retrieve response parameters at your leisure; they are stored internally in TCLink.
+<p>
+
+
+<a name=transtypes></a><h2>III. Transaction Types</h2>
+
+
+       You may wish to read the section of the TCS User's Guide which describes the transaction types and the authorization/capture process, especially if you are not already familiar with credit card processing.
+<p>
+       In terms of parameters passed, preauths and sales are almost identical.  They take account data and personal information about the customer, along with a transaction amount.  The transaction is authorized and the response values returned.  In the case of a sale, the item is also immediately submitted for capture.  Preauths are not captured until they are postauthed.
+<p>
+       Postauths and credits are also very similar to one another.  They indicate a capture or a return of funds for a previous transaction, and no personal data about the customer or their payment method is passed.
+<p>
+       There are three other types of transaction.  Store and unstore are covered in the Billing ID section of this document.  Walletsale is covered under the TCS Wallet section.
+<p>
+
+
+<a name=inputparam></a><h2>IV. Input Parameters</h2>
+
+
+       There are a large number of parameters available for describing transactions.  Not all parameters are accepted for all transaction types, and most parameters are optional.  Most transactions can be sent with only a few parameters.  The only parameters always required are custid, password, and action.
+<p>
+       Parameters are carefully checked for format and size before the transaction is sent.  If there are any errors in the parameters you've entered, the transaction will be aborted and detailed information about the errors will be returned.  These return values are described in more detail in the next section.
+<p>
+       The parameters presented in the following tables are used by all transaction types.
+
+
+       <center><h3>Required Parameters</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Parameter Name</th><th>Description</th></tr>
+       <tr><td>amount</td><td>Amount of the transaction, in cents.  (example: "500" is $5.00)</td></tr>
+       <tr><td>custid</td><td>Your customer ID number assigned to you by TrustCommerce.</td></tr>
+       <tr><td>password</td><td>The password for your custid as assigned by TrustCommerce.</td></tr>
+       <tr><td>action</td><td>The transaction type; can be one of preauth, sale, postauth, credit, store, unstore, walletsale, or chargeback</td></tr>
+       </table>
+<p>
+
+
+       <center><h3>Optional Parameters</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Parameter Name</th><th>Description</th></tr>
+       <tr><td>amount</td><td>Amount of the transaction, in cents.  (example: "500" is $5.00)</td></tr>
+       <tr><td>demo</td><td>When set to "y", the transaction will be a test transaction only.</td></tr>
+       <tr><td>ticket</td><td>Free-form text field intended for storing ticket number or order number associated with the transaction, to aid merchants in order tracking and reporting.</td></tr>
+       <tr><td>operator</td><td>Free-form text field intended for recording the operator that entered the transaction, to aid merchants in order track and reporting.</td></tr>
+       </table>
+<p>
+
+
+       The demo parameter is of particular note for testing.  Demo transactions allow you to test your processing system without charging real money to a card, and you will not be charged and transaction fees.  They are also flagged separately in the Vault database and will not appear in the regular accounting reports.
+<p>
+       On card-not-present transactions, the ticket parameter is passed to the acquiring bank in the settlement process as the "purchase identifier."  This may aid in reconciling the TrustCommerce transactions with the deposits made into the merchant bank account.  If no ticket is passed, then the TrustCommerce transID will be sent to the bank instead.
+<p>
+
+
+<a name=returnparam></a><h2>V. Return Parameters</h2>
+
+
+       Any transaction sent will return several parameters describing the success or failure of the transaction.  Properly formatted transactions will always return a transaction ID (or "transID') this is the unique identifier for this transaction, and can be used to retrieve the transaction from the Vault website, or otherwise access the transaction in the future.  (For example, in order to credit a previous transaction, you will need to send the transID of said transaction.)
+<p>
+       Transactions also always return a status parameter which describes the success or failure of the transaction.  Status can be set to one of the following:
+
+
+       <center><h3>Status</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Status Value</th><th>Description</th></tr>
+       <tr><td>approved</td><td>The transaction was successfully authorized.</td></tr>
+       <tr><td>accepted</td><td>The transaction has been successfully accepted into the system.</td></tr>
+       <tr><td>decline</td><td>The transaction was declined, see declinetype for further details.</td></tr>
+       <tr><td>baddata</td><td>Invalid parameters passed, see error for further details.</td></tr>
+       <tr><td>error</td><td>System error when processing the transaction, see errortype for details.</td></tr>
+       </table>
+<p>
+
+
+       The difference between approved and accepted is subtle, but important.  Approved means that the transaction was an authorization of some sort, and has been successfully cleared with the bank.  Accepted only means that the transaction was queued into the system without errors, but may be rejected at some later time.  An example of the difference is a sale versus a credit.  A sale is a realtime authorization, so it returns approved on success.  A credit is not realtime; there is no such thing as a "credit authorization."  Instead it is queued up for processing by the bank and there is the small but non-zero posibility that it will be rejected at a later time.  In practice, however, this rarely happens, so the developer need not worry unduly.
+<p>
+       When status is set to decline, the parameter declinetype will contain one of the following:
+
+
+       <center><h3>Decline Type</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Declinetype Value</th><th>Description</th></tr>
+       <tr><td>decline</td><td>This is a "true" decline, it almost always is a result of insufficient funds on the card.</td></tr>
+       <tr><td>avs</td><td>AVS failed; the address entered does not match the billing address on file at the bank.</td></tr>
+       <tr><td>cvv</td><td>CVV failed; the number provided is not the correct verification number for the card.  (See section X for details on CVV.)</td></tr>
+       <tr><td>call</td><td>The card must be authorized manually over the phone.  You may choose to call the customer service number listed on the card and ask for an offline authcode, which can be passed in the offlineauthcode field.</td></tr>
+       <tr><td>carderror</td><td>Card number is invalid, usually the result of a typo in the card number.</td></tr>
+       <tr><td>authexpired</td><td>Attempt to postauth an expired (more than 7 days old) preauth.</td></tr>
+       <tr><td>dailylimit</td><td>Daily limit in transaction count or amount as been reached.</td></tr>
+       <tr><td>weeklylimit</td><td>Weekly limit in transaction count or amount as been reached.</td></tr>
+       <tr><td>monthlylimit</td><td>Monthly limit in transaction count or amount as been reached.</td></tr>
+       </table>
+<p>
+
+
+       A status of baddata indicates that no transaction was attempted because one or more parameters was invalid.  In this case, the parameter error will indicate the problem, and the offenders parameter will list the offending input fields.  The error parameter may be set to one of the following:
+
+
+       <center><h3>Bad Data</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Error Value</th><th>Description</th></tr>
+       <tr><td>missingfields</td><td>Some parameters required for this transaction type were not sent.</td></tr>
+       <tr><td>extrafields</td><td>Parameters not allowed for this transaction type were sent.</td></tr>
+       <tr><td>badformat</td><td>A field was improperly formatted, such as non-digit characters in a number field.</td></tr>
+       <tr><td>badlength</td><td>A field was longer or shorter than the server allows.</td></tr>
+       <tr><td>merchantcantaccept</td><td>The merchant can't accept data passed in this field.  If the offender is "cc", for example, it usually means that you tried to run a card type (such as American Express or Discover) that is not supported by your account.  If it was "currency", you tried to run a currency type not supported by your account.</td></tr>
+       <tr><td>mismatch</td><td>Data in one of the offending fields did not cross-check with the other offending field.</td></tr>
+       </table>
+<p>
+
+
+  A status of error indicates the an error occurred while processing the transaction.  These are almost always networking errors; see the Troubleshooting section for more.  If the status is error, then the errortype parameter will be set to one of the following:
+
+
+       <center><h3>Error</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Errortype Value</th><th>Description</th></tr>
+       <tr><td>cantconnect</td><td>Couldn't connect to the TrustCommerce gateway.  Check your Internet connection to make sure it is up.</td></tr>
+       <tr><td>dnsfailure</td><td>The TCLink software was unable to resolve DNS hostnames.  Make sure you have name resolving ability on the machine.</td></tr>
+       <tr><td>linkfailure</td><td>The connection was established, but was severed before the transaction could complete.</td></tr>
+       <tr><td>failtoprocess</td><td>The bank servers are offline and unable to authorize transactions.  Try again in a few minutes, or try a card from a different issuing bank.</td></tr>
+       </table>
+<p>
+
+
+       Other parameters (such as avs or billingid) may be returned by the transaction depending on the action; see sections covering the transaction type you're running for detailed information on the specialized return values.
+<p>
+
+
+<a name=sales></a><h2>VI. Credit Card Preauths and Sales</h2>
+
+
+       The 'preauth' and 'sale' actions are identical in terms of parameters and function.  The only difference is that a sale submits the item for capture as well, while preauths run the authorization only and can be postauthed at another time.
+<p>
+       The parameters that can be passed with these action types are described in the following two tables.  The first table list required fields that you must pass in order to send the transaction.  The second table lists optional fields that you can pass if you wish, but are not required.
+<p>
+
+
+
+       <center><h3>Required Parameters</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Parameter Name</th><th>Description</th></tr>
+       <tr><td>amount</td><td>Amount of the transaction, in cents.  (example: "500" is $5.00)</td></tr>
+       <tr><td>cc</td><td>Credit card number, digits only (no spaces or dashes)</td></tr>
+       <tr><td>exp</td><td>Credit card expiration date, in MMYY format</td></tr>
+       </table>
+<p>
+
+
+       <center><h3>Optional Parameters</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Parameter Name</th><th>Default Value</th><th>Description</th></tr>
+       <tr><td>media</td><td>cc</td><td>"cc" for credit card or "ach" for ACH.
+       <tr><td>currency</td><td>usd</td><td>Currency code (see section X for the table of codes)
+       <tr><td>avs</td><td>y</td><td>AVS requested, "y" or "n" (see notes below).
+       <tr><td>name</td><td>&nbsp;</td><td>Cardholder's name.
+       <tr><td>address1</td><td>&nbsp;</td><td>First line of cardholder's street address.
+       <tr><td>address2</td><td>&nbsp;</td><td>Second line of cardholder's street address.
+       <tr><td>city</td><td>&nbsp;</td><td>Cardholder's city.
+       <tr><td>state</td><td>&nbsp;</td><td>Two-character code for the cardholder's state.
+       <tr><td>zip</td><td>&nbsp;</td><td>Cardholder's zipcode, five or nine digits (no spaces or dashes).
+       <tr><td>country</td><td>&nbsp;</td><td>Cardholder's country, leave blank for US.
+       <tr><td>phone</td><td>&nbsp;</td><td>Cardholder's phone number.
+       <tr><td>email</td><td>&nbsp;</td><td>Cardholder's email address.
+       <tr><td>offlineauthcode</td><td>&nbsp;</td><td>Six-digit numeric code used to "force" the transaction (see notes below).
+       </table>
+<p>
+
+
+A note about AVS: The AVS system is a useful way to help screen for fraud, as it requires that whomever is sending the transaction know the billing address for the card in question.  As a merchant, you should know that AVS is not uniformly supported by card issuers; approximately 30% of US-based credit cards will not have AVS capability, and AVS is not available with any non-US cards at all.  If avs of "y" (the default) is used, it will attempt to verify the address data with AVS, but if it is unavailable, it will not cause the transaction to fail.  Only if AVS is available and the address data does not match will the transaction be declined due to AVS.  You may wish to screen AVS results more closely.  For this reason, sales and preauths will return the AVS code in a parameter named avs.  It returns a single character code, which are enumerated in the table below.
+
+
+       <center><h3>AVS Returns Codes</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Code</th><th>Description</th></tr>
+       <tr><td align=center>X</td><td>Exact match, 9 digit zipcode.</td></tr>
+       <tr><td align=center>Y</td><td>Exact match, 5 digit zipcode.</td></tr>
+       <tr><td align=center>A</td><td>Street address match only.</td></tr>
+       <tr><td align=center>W</td><td>9 digit zipcode match only.</td></tr>
+       <tr><td align=center>Z</td><td>5 digit zipcode match only.</td></tr>
+       <tr><td align=center>N</td><td>No match on street address or zipcode.</td></tr>
+       <tr><td align=center>U</td><td>AVS unavailable on this card.</td></tr>
+       <tr><td align=center>G</td><td>Non-US card issuer, AVS unavailable.</td></tr>
+       <tr><td align=center>R</td><td>Card issuer system currently down, try again later.</td></tr>
+       <tr><td align=center>E</td><td>Error, ineligible - not a mail/phone order.</td></tr>
+       <tr><td align=center>S</td><td>Service not supported.</td></tr>
+       <tr><td align=center>0</td><td>General decline or other error.</td></tr>
+       </table>
+<p>
+
+
+Only the numeric parts of the address (street address and zipcode) are verified.  It should also be noted that oftentimes AVS data is incorrect or not entirely up-to-date, dependent upon the card issuing bank.  For these reasons, you should treat AVS as a helpful tool which should be used in combination with other methods (dependent upon your business model) for screening transactions.  If you trust AVS too blindly, you may risk losing legitimate sales.  Some merchants (again, dependent upon business model) choose to turn AVS off altogether.  You should analyze your customer base and make the decision that will work best for your business.
+<p>
+A note on offlineauthcode: Some cards returned a declinetype of call.  This indicates that the card cannot be automatically authorized, but if you call the card issuers, they may be able to give you a manual authorization, which will consist of a six-digit auth code.  You may then push the transaction through by entering that code into the offlineauthcode field.  Be warned: offlineauthcode is NOT a realtime authorization, and is not guaranteed in the same way as a normal authorization.  Be careful with the use of this parameter.
+<p>
+
+
+
+
+<h3>Preauth/Sale Example</h3>
+<pre>
+       params = {
+               'custid':    'mycustid',
+               'password':  'mypasswd',
+               'action':    'preauth',
+               'amount':    '500',
+               'cc':        '4111111111111111',
+               'exp':       '0404',
+               'name':      'Jennifer Smith',
+               'address1':  '123 Test St.',
+               'city':      'Somewhere',
+               'state':     'CA',
+               'zip':       '90001',
+               'avs':       'y'
+       }
+
+       result = tclink.send(params)
+
+       if (result['status'] == 'approved'):
+               print  'Transaction was successful'
+       elif (result['status'] == 'decline'):
+               print 'Transaction declined.  Reason: ', result['declinetype']
+       elif (result['status'] == 'baddata'):
+               print 'Improperly formatted data.  Offending fields: ', result['offenders']
+       else:
+               print 'An error occured: ', result['errortype']
+
+       print 'Here are the full details:'
+       print result
+</pre>
+<p>
+
+
+<a name=cvv></a><h2>VII. Card Verification Value (CVV)</h2>
+
+
+       Another method for cardholder verification is the CVV system.  Visa cards use what is called a CVV2 code; Mastercards call it CVC2, and American Express calls it CID.  CVV2 and CVC2 (Visa/MC) are located on the back of the credit card, printed in ink on the signature strip.  The number is the last three digits on the righthand side of the long string of numbers on the strip.  In the case of CID (AmEx), the number is a four-digit value located on the front of the card, printed just above the card number on the lefthand side.  This value is passed to TCLink through the following parameter.
+
+
+       <center><h3>CVV Parameters</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Parameter Name</th><th>Description</th></tr>
+       <tr><td>cvv</td><td>A three or four digit CVV number.</td></tr>
+       </table>
+<p>
+
+
+       The CVV value will be checked if anything is passed in this parameter.  (If you don't include the parameter, no CVV test will be run.)  If the CVV matches, the transaction will run as normal.  If it does not, you will receive a status of decline, and a declinetype of cvv.
+<p>
+
+
+
+<h3>CVV Example</h3>
+<pre>
+       params = {
+               'custid':    'mycustid',
+               'password':  'mypasswd',
+               'action':    'sale',
+               'amount':    '500',
+               'cc':        '4111111111111111',
+               'exp':       '0404',
+               'cvv':       '123'
+       }
+
+       result = tclink.send(params)
+
+       if (result['status'] == 'decline')
+               if (result['declinetype'] == 'cvv')
+                       print 'The CVV number is not valid.'
+</pre>
+<p>
+
+
+<a name=cardpresent></a><h2>VII. Card-Present Transactions</h2>
+
+
+       In a retail environment with a card swiper, you may wish to pass magnetic stripe data along with the other credit card information on a preauth or sale.  There are two parameters which you can use to send this data, named track1 and track2.  Each one is for a different type of track data, and depends on the type of card reader being used.
+
+
+       <center><h3>Card-Present Parameters</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Parameter Name</th><th>Description</th></tr>
+       <tr><td>track1</td><td>Up to 79 bytes of Track 1 data.</td></tr>
+       <tr><td>track2</td><td>Up to 40 bytes of Track 2 data.</td></tr>
+       </table>
+<p>
+
+
+       You can include all data read from the track, but only data between the start sentinel (a '%' character for track1 and a ';' for track2) and the end sentinel ('?') will be used.  Everything outside the start and end sentinels (such as the trailing LRC character) will be discarded.
+<p>
+       The cc and exp fields may be passed, but are not required, since they will be extracted from the track data.  If you do pass one or both of these fields, however, and it does not match the data extracted from the track data, a status of baddata and an error mismatch will be returned.
+<p>
+       If both track1 and track2 data are passed, only the system will choose track1 by default for the authorization, and track2 will be discarded.
+<p>
+       Generally AVS and address data are not necessary for swiped transactions, but you may pass them anyway if you choose.
+<p>
+
+
+<h3>Card Present Example</h3>
+<pre>
+       params = {
+               'custid':    'mycustid',
+               'password':  'mypasswd',
+               'action':    'sale',
+               'amount':    '500'
+       }
+
+       params['track1'] = CardReader.readMagStripe()
+
+       result = tclink.send(params)
+</pre>
+<p>
+
+
+<a name=ach></a><h2>IX. ACH</h2>
+
+
+       ACH, also known as electronic checks, are very different from credit cards in that they allow a direct debit or credit to a checking account.  The concept of "authorization" does not exist; it is purely a money transfer.  For this reason, the only transaction types available for ACH are sale and credit.  ACH credits are identical to all other types of credits in the TrustCommerce system, so please refer to section X for details on issuing credits.
+<p>
+       ACH sales take the same parameters as credit card sales, with the exception of the "cc" and "exp" fields.  Instead, use the following parameters.
+
+
+       <center><h3>ACH Parameters</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Parameter Name</th><th>Description</th></tr>
+       <tr><td>routing</td><td>The routing number of the bank being debited.</td></tr>
+       <tr><td>account</td><td>The account number of the person or business being debited.</td></tr>
+       </table>
+<p>
+
+
+       AVS is not available for ACH transactions, so the AVS setting is ignored.
+<p>
+       There is only one declinetype returned from unsuccessful ACH sales, and that is "decline."
+<p>
+
+
+<h3>ACH Example</h3>
+<pre>
+       params = {
+               'custid':    'mycustid',
+               'password':  'mypass',
+               'action':    'sale',
+               'media':     'ach',
+               'amount':    '1000',
+               'routing':   '123456789',
+               'account':   '55544433322211'
+       }
+
+       tclink.send(params)
+</pre>
+<p>
+
+
+<a name=credits></a><h2>X. Postauths, Credits, and Chargebacks</h2>
+
+
+       These three transaction types are similar in that they reference a successful transaction previously executed through the TrustCommerce system.  No credit card information or other personal information fields will be accepted by this transaction types; there is only one required parameter.
+<p>
+
+
+       <center><h3>Required Parameters</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Parameter Name</th><th>Description</th></tr>
+       <tr><td>transid</td><td>The transaction ID (format: nnn-nnnnnnnnnn) of the referenced transaction.</td></tr>
+       </table>
+<p>
+
+
+       In addition, postauths and credits can take an optional amount parameter.
+
+       <center><h3>Optional Parameters</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Parameter Name</th><th>Description</th></tr>
+       <tr><td>amount</td><td>The amount, in cents, to credit or postauth if it is not the same as the original amount.</td></tr>
+       </table>
+<p>
+
+
+       If no amount is passed, the default will be to take the amount from the original transaction.  If, however, you wish to credit or postauthorize less than the original amount, you may pass this parameter.
+<p>
+
+
+<h3>Credit Example</h3>
+<pre>
+       params = {
+               'custid':    'mycustid',
+               'password':  'mypass',
+               'action':    'credit',
+               'transid':   '001-0000111101'
+       }
+
+       tclink.send(params)
+
+       if (result['status'] != 'accepted')
+               print 'Credit unsuccesful.'
+</pre>
+<p>
+
+
+<a name=billingids></a><h2>XI. Billing IDs</h2>
+
+
+       The Billing ID system enables you to store the billing information for your customers in the encrypted TrustCommerce database, and recall it with a single six-character alphanumeric code known as a billing ID.  Besides offloading the liability of storing sensitive data such as credit card numbers from your business to TrustCommerce, it also can simplify database access on your servers.
+<p>
+       Billing IDs add two new actions, store and unstore.  These allow you to create, update, and deactivate billing IDs.  Once stored, the billing ID will be passed in place of the many billing information fields for preauth and sale transactions.
+<p>
+       The store transaction looks very similar to a preauth or sale.  You may pass credit card information, billing and shipping address, or even ACH information.  (Please see sections X and X for a detailed description of these parameters.)  It adds one additional parameter:
+
+
+       <center><h3>Store Parameters</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Parameter Name</th><th>Description</th></tr>
+       <tr><td>verify</td><td>When set to "y", a $1.00 preauth will be run on the card to ensure that it is valid.</td></tr>
+       <tr><td>billingid</td><td>Pass if you wish to update values of an existing billing ID.</td></tr>
+       </table>
+<p>
+
+
+       The verify parameter is useful for ensuring that the card number is valid if you are not planning to bill the customer right away.  It has no effect for ACH billing IDs, because there is no such thing as an ACH preauth.  By default, the verification uses AVS; if you don't wish to use AVS, pass an avs of "n".  Please note: normally, billing ID storage returns a status of accepted, because the card is unverified.  If you use the verify parameter, however, it will return approved upon success.
+<p>
+       The unstore action takes a single parameter:
+
+
+       <center><h3>Unstore Parameters</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Parameter Name</th><th>Description</th></tr>
+       <tr><td>billingid</td><td>The six-character alphanumeric billing ID returned by a previous store transaction.</td></tr>
+       </table>
+<p>
+
+
+       Unstore removes the billing ID from active use, and you won't be able to run further transactions on it.  For your convenience, however, it does remain visible in Vault (flagged as an inactive ID), so you can still look up old IDs if needed.
+<p>
+       Now, the moment of truth: to run a billing ID transaction, pass the billingid parameter to a preauth or a sale in place of all of the usual billing info fields (name, cc, exp, routing, account, etc).  That's all there is to it!  You'll find that your sale or preauth transactions are now only a few parameters: custid, password, billingid, and amount.
+
+<h3>Billing ID Example</h3>
+<pre>
+       # First, store a new ID.
+       params = {
+               'custid':    'mycustid',
+               'password':  'mypass',
+               'action':    'store',
+               'cc':        '4111111111111111',
+               'exp':       '0404',
+               'name':      'Jennifer Smith'
+       }
+
+       result = tclink.send(params)
+
+       if (result['status'] == 'accepted'):
+               # It was succesfully stored.  Now try running a transaction on the new ID.
+               billingid = result['billingid']
+               params2 = {
+                       'custid':    'mycustid',
+                       'password':  'mypass',
+                       'action':    'sale',
+                       'billingid': billingid,
+                       'amount':    '995'
+               }
+               tclink.send(params2);
+               # Unstore the ID now that we are done.
+               params3 = {
+                       'custid':    'mycustid',
+                       'password':  'mypass',
+                       'action':    'unstore',
+                       'billingid': billingid
+               }
+               tclink.send(params3)
+</pre>
+<p>
+
+
+<a name=recurring></a><h2>XII. Recurring Billing</h2>
+
+
+       Recurring billing (sometimes also called "subscription billing") is an extension of the billing ID system.  There are four parameters that are added to a store which turn the billing ID into a recurring billing ID.  They are described below.
+
+
+       <center><h3>Recurring Parameters</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Parameter Name</th><th>Required?</th><th>Description</th></tr>
+       <tr><td>cycle</td><td align=center>X</td><td>Repeat cycle in days, weeks, months, or years.</td></tr>
+       <tr><td>amount</td><td align=center>X</td><td>Amount to bill in cents.</td></tr>
+       <tr><td>start</td><td>&nbsp;</td><td>Date to start, or else offset from current date (defaults to now).</td></tr>
+       <tr><td>payments</td><td>&nbsp;</td><td>Number of payments to make (defaults to infinite).</td></tr>
+       </table>
+<p>
+
+
+Cycle is in the format of a number followed by a character representing the timeframe: 'd' for days, 'w' for weeks, 'm' for months or 'y' for years.  For example, a value of "3d" in this field would cause the charge to recur every three days, whereas a value of "2m" would cause it to recur every two months.
+<p>
+Amount is identical to the amount passed to a sale or a preauth, and indicates the amount of each charge made during the subscription.
+<p>
+Start is an optional field which allows the delay of the cycle's start.  By default, the cycle starts the day the billing ID is stored.  If it is specified in the format YYYY-MM-DD, it indicates a date when the first payment should be made.  (For example, "2005-02-01" would be February 1, 2005.)  If it is in the same format as the cycle (a number followed by a character), it indicates an offset from the current date.  (For example, "1d" would start the billing tomorrow.)  Note: recurring transactions will appear at the end of the business day they are billed on, so the first transaction for new subscriptions will not appear in the Vault until that time.
+<p>
+Payments is also optional; left blank or set to zero it will continue the billing cycle until it is manually interrupted by an unstore, or by updating the billing ID with cycle set to "null".  Once the final payment is made, the billing ID will be unstored.
+<p>
+
+
+<h3>Recurring Billing Example</h3>
+<pre>
+       params = {
+               'custid':    'mycustid',
+               'password':  'mypass',
+               'action':    'store',
+               'cc':        '4111111111111111',
+               'exp':       '0404',
+               'name':      'Jennifer Smith',
+               'amount':    '1200'
+       }
+
+       mode = chooseSubscriptionMode()
+
+       if (mode == 1):
+               # Make a payment every day, infinitely (or until someone manually disables it)
+               params['cycle'] = '1d';
+       elif (mode == 2):
+               # Make a payment once a month for one year
+               params['cycle'] = '1m';
+               params['payments'] = '12';
+       elif (mode == 3):
+               # Make a payment every six weeks, starting one week from now
+               params['cycle'] = '62';
+               params['start'] = '1w';
+       elif (mode == 4):
+               # Make anual payments, and don't start until September 1, 2002
+               params['cycle'] = '1y';
+               params['start'] = '2003-09-02';
+
+       tclink.send(params)
+</pre>
+
+<p>
+
+
+<a name=wallet></a><h2>XIII. TCS Wallet</h2>
+
+
+       The TCS Wallet is an additional service offered by the TrustCommerce gateway that allows you to run many small micropayments which are later lumped together and submitted as a single, large payment.  This can offer a substantial savings for the merchant in transaction fees, as merchant account providers tend to penalize merchants that run small payments.
+<p>
+       The Wallet is an extension of the billing ID system.  It adds three new parameters to the store action, described below.
+
+
+       <center><h3>Wallet Parameters</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Parameter Name</th><th>Description</th></tr>
+       <tr><td>wallet</td><td>"y" to enable the wallet.</td></tr>
+       <tr><td>walletsize</td><td>Accumulated amount, in cents, before the wallet is submitted for capture.</td></tr>
+       <tr><td>walletexposure</td><td>Length of time to wait before capturing the wallet.</td></tr>
+       </table>
+<p>
+
+
+       In order to enable wallets for the billing ID that you are storing, set the "wallet" parameter to "y".  The other two parameters are optional, as there are default values attached to your TC account.  If you wish to change these values (which are normally $10.00 and 72 hours) please contact TrustCommerce.  If you wish to change the values for an individual billing ID without changing your defaults, include these parameters.
+<p>
+       Once the billing ID is stored, it is possible to use a new action type on the ID called walletsale.  It is identical to a sale in all ways, except that it can only be used on wallet-enabled billing IDs, and it can accept amounts anywhere from $0.01 up to the size of the wallet.  Walletsale will usually return "approved", but it may return "decline" if the stored credit card fails to re-authorize when the current wallet is exceeded.
+       Except for these two modifications (the wallet parameters on the store, and changing sales to walletsales), there is no extra development to be done client-side to make wallets work.  Captures happen automatically after walletexposure has expired or the walletamount has been used up; reauthorizations also happen automatically.
+<p>
+
+
+<h3>Wallet Example</h3>
+<pre>
+       # First, store a new ID with the wallet enabled.
+       params = {
+               'custid':    'mycustid',
+               'password':  'mypass',
+               'action':    'store',
+               'cc':        '4111111111111111',
+               'exp':       '0404',
+               'name':      'Jennifer Smith',
+               'wallet':    'y'
+       }
+
+       result = tclink.send(params)
+
+       if (result['status'] == 'approved'):
+               # We have a new wallet at our disposal.  Run a micropayment on it.
+               billingid = result['billingid']
+               params2 = {
+                       'custid':    'mycustid',
+                       'password':  'mypass',
+                       'action':    'walletsale',
+                       'billingid': billingid,
+                       'amount':    '995'
+               }
+               tclink.send(params)
+</pre>
+<p>
+
+
+<a name=fulfillment></a><h2>XIV. Automated Fulfillment</h2>
+
+
+       TrustCommerce offers the unique feature of automated fulfillment, by which orders submitted through the TCLink API can contain parameters describing product information.  This information is then passed on to your fulfillment house, which ships the products automatically.
+<p>
+       First, it is necessary to specify the shipping address for the customer.  If it is the same as the billing address, you need not duplicate it, but rather just send the shiptosame parameter set to y.  The table below enumerates the shipping parameters.
+
+
+       <center><h3>ShipTo Parameters</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Parameter Name</th><th>Description</th></tr>
+       <tr><td>shiptosame</td><td>y or n (defaults to n).  If "y", then no other shipto_ parameters should be passed.</td></tr>
+       <tr><td>shipto_name</td><td>Name of the product recipient.</td></tr>
+       <tr><td>shipto_address1</td><td>First line of shipping address.</td></tr>
+       <tr><td>shipto_address2</td><td>Second line (if any) of shipping address.</td></tr>
+       <tr><td>shipto_city</td><td>City.</td></tr>
+       <tr><td>shipto_state</td><td>State.</td></tr>
+       <tr><td>shipto_zip</td><td>Zipcode, five or nine digits (no spaces or dashes).</td></tr>
+       <tr><td>shipto_country</td><td>Country, leave blank for US.</td></tr>
+       </table>
+<p>
+
+
+       Second, some additional data about the order as a whole should be passed in the form of the following parameters.
+
+
+       <center><h3>Order Header Parameters</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Parameter Name</th><th>Description</th></tr>
+       <tr><td>shippingcode</td><td>Three character code indicating shipping method to use.</td></tr>
+       <tr><td>shippinghandling</td><td>The total cost of shipping and handling, in cents.</td></tr>
+       <tr><td>numitems</td><td>Total number of distinct items (product codes) in the order.</td></tr>
+       </table>
+<p>
+
+
+       Finally, a number of parameters which describe the details of each type of item must be passed.  In the table below, the 'X' character in the parameter name should be replaced with a digit indicating which item it applies to.  For example, if numitems is set to three, then you should pass three product codes, in the form of productcode1, productcode2, and productcode3.
+
+
+       <center><h3>Order Detail Parameters</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Parameter Name</th><th>Description</th></tr>
+       <tr><td>productcodeX</td><td>The alphanumeric product code defined by the fulfillment house.</td></tr>
+       <tr><td>quantityX</td><td>The number of items of this type to be shipped.</td></tr>
+       <tr><td>priceX</td><td>The price of all items of this type not including sales tax or shipping, in cents.</td></tr>
+       <tr><td>taxX</td><td>Total tax charged for all items of this product code.</td></tr>
+       <tr><td>shippinghandlingX</td><td>Total shipping and handling charged for all items of this product code.</td></tr>
+       </table>
+<p>
+
+
+       Please note: the shippinghandling field and the shippinghandlingX fields are mutually exclusive.  Use one or the other, but not both.  If you're not sure which to use, please contact your fulfillment house.
+<p>
+
+
+<h3>Fulfillment Example</h3>
+<pre>
+       params = {
+               'custid':           'mycustid',
+               'password':         'mypass',
+               'action':           'preauth',
+               'cc':               '4111111111111111',
+               'exp':              '0404',
+               'amount':           '1979',  # Total of items, tax, and shipping
+               'name':             'Jennifer Smith',
+               'address1':         '123 Test St.',
+               'city':             'Somewhere',
+               'state':            'CA',
+               'zip':              '90001',
+               'shiptosame':       'y',     # Shipping address is same as billing address
+
+               'numitems':         '2',     # Two total product codes will be described
+               'shippingcode':     'OVRNGT',
+               'shippinghandling': '695',
+
+               'productcode1':     'PCODE1',
+               'quantity1':        '3',
+               'price1':           '600',   # Item 1 costs $2.00, and there are 3 of them
+               'tax1':             '144',   # Tax of 8%
+
+               'productcode2':     'PCODE2',
+               'quantity2':        '1',
+               'price2':           '500',   # Item 1 costs $5.00, there's only one
+               'tax2':             '40'     # Tax of 8%
+       }
+
+       tclink.send(params)
+</pre>
+<p>
+
+
+<a name=query></a><h2>XV. Vault Query API</h2>
+
+
+       The Vault website serves as a web-based interface for merchant reconciliation.  On the backend, it is a complex database that tracks all transactional data for your TrustCommerce account.  The information contained in the Vault can be accessed at the API level using a standard CGI query over HTTPS.
+<p>
+       The query API returns data in CSV (comma separated value) format, which is just a flat text file with fields separated by commas, and records separated by newlines.  (You can also request the data returned in an HTML table, which is useful for debugging.)  The first line of the file contains the name of each field that will be returned in subsequent records.
+<p>
+       The parameters that the query interface accepts are described in the table below.
+
+
+       <center><h3>Required Parameters</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Parameter Name</th><th>Requred?</th><th>Description</th></tr>
+       <tr><td>custid</td><td align=center>X</td><td>TrustCommerce customer ID number.</td></tr>
+       <tr><td>password</td><td align=center>X</td><td>The password for your custID.</td></tr>
+       <tr><td>format</td><td>&nbsp;</td><td>Set to "html" for human-readable HTML output, or "text" (default) for CSV text output.</td></tr>
+       <tr><td>querytype</td><td align=center>X</td><td>Possible values are: chain, transaction, summary, or billingid, corresponding to the equivalent reports on the Vault website.  Read the User's Guide for further description of each report type.</td></tr>
+       <tr><td>media</td><td>&nbsp;</td><td>Set to "cc" (default) or "ach" for media type.</td></tr>
+       <tr><td>begindate</td><td>&nbsp;</td><td>Begin date for query, format: MM-DD-YYYY HH:MM:SS</td></tr>
+       <tr><td>enddate</td><td>&nbsp;</td><td>End date for query, format: MM-DD-YYYY HH:MM:SS</td></tr>
+       <tr><td>chain</td><td>&nbsp;</td><td>Narrow search to a single chain of transactions.</td></tr>
+       <tr><td>transid</td><td>&nbsp;</td><td>Narrow search to a single transaction ID.</td></tr>
+       <tr><td>billingid</td><td>&nbsp;</td><td>Narrow search to a single billing ID.</td></tr>
+       <tr><td>action</td><td>&nbsp;</td><td>Narrow search by action (preauth, sale, credit, etc).</td></tr>
+       <tr><td>status</td><td>&nbsp;</td><td>Narrow search by status (approved, accepted, decline, etc).</td></tr>
+       <tr><td>name</td><td>&nbsp;</td><td>Narrow search by cardholder name, partial or complete.</td></tr>
+       <tr><td>cc</td><td>&nbsp;</td><td>Narrow search by credit card number.</td></tr>
+       <tr><td>limit</td><td>&nbsp;</td><td>Do not allow size of result set to exceed this number of records.</td></tr>
+       <tr><td>offset</td><td>&nbsp;</td><td>Report result set starting from this offset.  Use this parameter in conjunction with limit in order to page through a large result set.</td></tr>
+       <tr><td>showcount</td><td>&nbsp;</td><td>Show the number of records returned on the last line of the result set.</td></tr>
+       </table>
+<p>
+
+
+       The sample HTML code shown below illustrates the functionality of the query API.  It can be pasted into a file and loaded on your web browser in order to try out some queries before you even begin to write your code.
+<p>
+
+
+<h3>Query Example HTML</h3>
+<pre>
+&lt;html&gt;
+&lt;head&gt; &lt;title&gt; TrustCommerce Query Interface &lt;/title&gt; &lt;/head&gt;
+&lt;body&gt;
+&lt;h2&gt; TrustCommerce Query Interface &lt;/h2&gt;
+&lt;form action=https://vault.trustcommerce.com/query/&gt;
+       &lt;table align=center border=1&gt;
+       &lt;tr&gt;
+               &lt;td&gt; custid &lt;/td&gt;
+               &lt;td&gt; &lt;input type=text name=custid&gt; &lt;/td&gt;
+               &lt;td&gt; This is your TrustCommerce custid (required) &lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;tr&gt;
+               &lt;td&gt; password &lt;/td&gt;
+               &lt;td&gt; &lt;input type=password name=password&gt; &lt;/td&gt;
+               &lt;td&gt; This is your TrustCommerce password (required) &lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;tr&gt;
+               &lt;td&gt; format &lt;/td&gt;
+               &lt;td&gt; &lt;select name=output&gt; &lt;option value=text&gt;text&lt;/option&gt;
+                               &lt;option value=html&gt;html&lt;/option&gt;&lt;/select&gt;&lt;/td&gt;
+               &lt;td&gt; Human readable (html) or computer readable (text) results&lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;tr&gt;
+               &lt;td&gt; Query type &lt;/td&gt;
+               &lt;td&gt; &lt;select name=querytype&gt; 
+               &lt;option value=chain&gt;chain&lt;/option&gt;
+               &lt;option value=transaction&gt;transaction&lt;/option&gt;
+               &lt;option value=summary&gt;summary&lt;/option&gt;
+               &lt;option value=billingid&gt;billingid&lt;/option&gt;
+               &lt;/select&gt;&lt;/td&gt;
+               &lt;td&gt; Type of query &lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;tr&gt;
+               &lt;td&gt; media &lt;/td&gt;
+               &lt;td&gt; &lt;input type=text name=media value=cc&gt; &lt;/td&gt;
+               &lt;td&gt; For now this must be cc &lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;tr&gt;
+               &lt;td&gt; begindate MM-DD-YYYY HH:MM:SS &lt;/td&gt;
+               &lt;td&gt; &lt;input type=text name=begindate&gt; &lt;/td&gt;
+               &lt;td&gt; Query begins at this date&lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;tr&gt;
+               &lt;td&gt; enddate MM-DD-YYYY HH:MM:SS &lt;/td&gt;
+               &lt;td&gt; &lt;input type=text name=enddate&gt; &lt;/td&gt;
+               &lt;td&gt; Query ends at this date&lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;tr&gt;
+               &lt;td&gt; chain &lt;/td&gt;
+               &lt;td&gt; &lt;input type=text name=chain&gt; &lt;/td&gt;
+               &lt;td&gt; Narrow search to a single chain of transactions &lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;tr&gt;
+               &lt;td&gt; transid &lt;/td&gt;
+               &lt;td&gt; &lt;input type=text name=transid&gt; &lt;/td&gt;
+               &lt;td&gt; Narrow search to a single transactions &lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;tr&gt;
+               &lt;td&gt; billingid &lt;/td&gt;
+               &lt;td&gt; &lt;input type=text name=transid&gt; &lt;/td&gt;
+               &lt;td&gt; Narrow search to a single billingid &lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;tr&gt;
+               &lt;td&gt; action &lt;/td&gt;
+               &lt;td&gt; &lt;input type=text name=action&gt; &lt;/td&gt;
+               &lt;td&gt; Narrow search by action. (example: preauth,postauth) &lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;tr&gt;
+               &lt;td&gt; status &lt;/td&gt;
+               &lt;td&gt; &lt;input type=text name=status&gt; &lt;/td&gt;
+               &lt;td&gt; Narrow search by status. (example: approved,accepted) &lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;tr&gt;
+               &lt;td&gt; name &lt;/td&gt;
+               &lt;td&gt; &lt;input type=text name=name&gt; &lt;/td&gt;
+               &lt;td&gt; Narrow search by name. &lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;tr&gt;
+               &lt;td&gt; cc &lt;/td&gt;
+               &lt;td&gt; &lt;input type=text name=cc&gt; &lt;/td&gt;
+               &lt;td&gt; Narrow search by credit card field. &lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;tr&gt;
+               &lt;td&gt; limit &lt;/td&gt;
+               &lt;td&gt; &lt;input type=text name=limit value=20&gt; &lt;/td&gt;
+               &lt;td&gt; Limit results to this number of fields (not used for summary)&lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;tr&gt;
+               &lt;td&gt; offset &lt;/td&gt;
+               &lt;td&gt; &lt;input type=text name=offset value=0&gt; &lt;/td&gt;
+               &lt;td&gt; Report results at this offset (used with limit to page through results)&lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;tr&gt;
+               &lt;td&gt; showcount &lt;/td&gt;
+               &lt;td&gt; &lt;select name=showcount&gt; 
+               &lt;option value=y&gt;yes&lt;/option&gt;
+               &lt;option value=n&gt;no&lt;/option&gt;
+               &lt;/select&gt;&lt;/td&gt;
+               &lt;td&gt; Show the number of not-limited rows on the last line of the result&lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;tr&gt;
+               &lt;td colspan=3&gt; &lt;input type=submit&gt; &lt;/td&gt;
+       &lt;/tr&gt;
+       &lt;/table&gt;
+&lt;/form&gt;
+&lt;/body&gt;
+&lt;/html&gt;
+</pre>
+<p>
+
+
+<a name=testdata></a><h2>Appendix A - Test Data</h2>
+
+
+       While testing, you may wish to experiment with the different responses that the gateway can generate.  The following test card numbers will produce an approval, and have address data as listed, for testing AVS.  If you wish to test CVV, the code listed int he right-hand column is the correct CVV code, Other valid credit cards will work, but will produce a 'U' AVS code.  All of these cards accept "0404" as the expiration date.
+
+
+       <center><h3>TCLink Function Names</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Card Number</th><th>Exp</th><th>Address</th><th>City</th><th>State</th><th>Zip</th><th>CVV</th></tr>
+       <tr><td>4111111111111111</td><td>04/04</td><td>123 Test St.</td><td>Somewhere</td><td>CA</td><td>90001</td><td>123</td></tr>
+       <tr><td>5411111111111115</td><td>04/04</td><td>4000 Main St.</td><td>Anytown</td><td>AZ</td><td>85001</td><td>777</td></tr>
+       <tr><td>6011111111111117</td><td>04/04</td><td>6789 Green Ave.</td><td>Nowhere</td><td>MA</td><td>12345</td><td>606</td></tr>
+       <tr><td>341111111111111</td><td>04/04</td><td>12 Colorado Blvd.</td><td>Elsewhere</td><td>IL</td><td>54321</td><td>4000</td></tr>
+       </table>
+<p>
+       The following card numbers will generate a decline, with the declinetype listed as follows.  You may use this to test code which takes different paths dependant upon the type of decline.
+
+
+       <center><h3>TCLink Function Names</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Card Number</th><th>Exp</th><th>DeclineType</th></tr>
+       <tr><td>4012345678909</td><td>04/04</td><td>decline</td>
+       <tr><td>5555444433332226</td><td>04/04</td><td>call</td>
+       <tr><td>4444111144441111</td><td>04/04</td><td>carderror</td>
+       </table>
+<p>
+
+
+       You should also test your code to make sure it properly handles all baddata and error cases as listed in section X.  Simply pass bad values in order to generate these situations.
+<p>
+
+<a name=troubleshooting></a><h2>Appendix B - Troubleshooting</h2>
+
+
+       Details about installing and troubleshooting TCLink specific to your development platform can be found in the documentation included with the TCLink archive.
+<p>
+       Once you are able to connect to the TC gateway, you should be able to diagnose parameter-related issues using the status, error, declinetype, and errortype parameters returned by the gateway.  There is one response which indicates a more generic error, and that's an error of <b>cantconnect</b>.  First, check the computer's network connection; can you ping machines on the Internet, by IP or by name?
+<p>
+       The most common network connectivity error is that your target computer may be behind a firewall.  TCLink uses the HTTPS port (443/tcp) for network communications; you can check whether this port is open from the target machine by typing "telnet vault.trustcommerce.com 443" at a UNIX command prompt, or else by loading a web browser on the target machine and attempting to visit https://vault.trustcommerce.com directly.  If you timeout attempting to make the connection, but your Internet connection is working otherwise, then you may be firewalled.  Speak to your network administrator about allowing outbound TCP traffic on port 443.
+<p>
+       Another common problem is the lack of domain name (DNS) resolution.  In some cases this will result in an errortype <b>dnsfailure</b>.  (Not always; the TCLink software will sometimes fall back to hardcoded IP addresses for established accounts.  But this method is insecure and error-prone, and is used only as a last resort to keep a system with temporary DNS issues up and running during the outage.)  The target machine must be able to resolve the trustcommerce.com domain; try typing "host trustcommerce.com" from a UNIX command prompt.  If you don't get a response, or get an error, then the machine cannot resolve DNS information and TCLink will not be able to connect to the TC gateway.  Speak to your sysadmin about making domain name resolution available to your target host.
+<p>
+
+
+<a name=httpspost></a><h2>Appendix C - Connecting via HTTPS POST</h2>
+
+
+       This method should only be used if a TCLink client install is not an option.  It does not have the failover capability (and thus the processing uptime is not guaranteed to be 100%), or some of the enhanced security features of TCLink.  In addition, transactions may be slightly slower, by an extra half second or so.  It does, however support all other features available through TCLink, including all parameters and transaction types.
+<p>
+       This is the URL:
+<p>
+<a href=https://vault.trustcommerce.com/trans/>https://vault.trustcommerce.com/trans/</a>
+<p>
+       The transaction should be sent as a standard POST, with CGI parameters, URL encoded.  The parameters are otherwise identical to those used through TCLink.
+<p>
+       Response parameters are returned as name-value pairs separated by newlines.
+<p>
+
+
+<a name=currency></a><h2>Appendix D - Currency Table</h2>
+
+
+       <center><h3>Currency Codes</h3></center>
+       <table align=center border=1 cellpadding=5 bgcolor=#e0e0e0>
+       <tr><th>Code</th><th>Currency Type</th><th>Code</th><th>Currency Type</th></tr>
+       <tr><td>usd</td><td>US Dollars</td><td>jpy</td><td>Japan Yen</td></tr>
+       <tr><td>eur</td><td>Euro</td><td>jod</td><td>Jordan Dinar</td></tr>
+       <tr><td>cad</td><td>Canadian Dollars</td><td>krw</td><td>Korea (South) Won</td></tr>
+       <tr><td>gbp</td><td>UK Pounds</td><td>lbp</td><td>Lebanon Pounds</td></tr>
+       <tr><td>dem</td><td>German Deutschemarks</td><td>luf</td><td>Luxembourg Francs</td></tr>
+       <tr><td>frf</td><td>French Francs</td><td>myr</td><td>Malaysia Ringgit</td></tr>
+       <tr><td>jpy</td><td>Japanese Yen</td><td>mxp</td><td>Mexico Pesos</td></tr>
+       <tr><td>nlg</td><td>Dutch Guilders</td><td>nlg</td><td>Netherlands Guilders</td></tr>
+       <tr><td>itl</td><td>Italian Lira</td><td>nzd</td><td>New Zealand Dollars</td></tr>
+       <tr><td>chf</td><td>Switzerland Francs</td><td>nok</td><td>Norway Kroner</td></tr>
+       <tr><td>dzd</td><td>Algeria Dinars</td><td>pkr</td><td>Pakistan Rupees</td></tr>
+       <tr><td>arp</td><td>Argentina Pesos</td><td>xpd</td><td>Palladium Ounces</td></tr>
+       <tr><td>aud</td><td>Australia Dollars</td><td>php</td><td>Philippines Pesos</td></tr>
+       <tr><td>ats</td><td>Austria Schillings</td><td>xpt</td><td>Platinum Ounces</td></tr>
+       <tr><td>bsd</td><td>Bahamas Dollars</td><td>plz</td><td>Poland Zloty</td></tr>
+       <tr><td>bbd</td><td>Barbados Dollars</td><td>pte</td><td>Portugal Escudo</td></tr>
+       <tr><td>bef</td><td>Belgium Francs</td><td>rol</td><td>Romania Leu</td></tr>
+       <tr><td>bmd</td><td>Bermuda Dollars</td><td>rur</td><td>Russia Rubles</td></tr>
+       <tr><td>brr</td><td>Brazil Real</td><td>sar</td><td>Saudi Arabia Riyal</td></tr>
+       <tr><td>bgl</td><td>Bulgaria Lev</td><td>xag</td><td>Silver Ounces</td></tr>
+       <tr><td>cad</td><td>Canada Dollars</td><td>sgd</td><td>Singapore Dollars</td></tr>
+       <tr><td>clp</td><td>Chile Pesos</td><td>skk</td><td>Slovakia Koruna</td></tr>
+       <tr><td>cny</td><td>China Yuan Renmimbi</td><td>zar</td><td>South Africa Rand</td></tr>
+       <tr><td>cyp</td><td>Cyprus Pounds</td><td>krw</td><td>South Korea Won</td></tr>
+       <tr><td>csk</td><td>Czech Republic Koruna</td><td>esp</td><td>Spain Pesetas</td></tr>
+       <tr><td>dkk</td><td>Denmark Kroner</td><td>xdr</td><td>Special Drawing Right (IMF)</td></tr>
+       <tr><td>nlg</td><td>Dutch Guilders</td><td>sdd</td><td>Sudan Dinar</td></tr>
+       <tr><td>xcd</td><td>Eastern Caribbean Dollars</td><td>sek</td><td>Sweden Krona</td></tr>
+       <tr><td>egp</td><td>Egypt Pounds</td><td>chf</td><td>Switzerland Francs</td></tr>
+       <tr><td>eur</td><td>Euro</td><td>twd</td><td>Taiwan Dollars</td></tr>
+       <tr><td>fjd</td><td>Fiji Dollars</td><td>thb</td><td>Thailand Baht</td></tr>
+       <tr><td>fim</td><td>Finland Markka</td><td>ttd</td><td>Trinidad and Tobago Dollars</td></tr>
+       <tr><td>frf</td><td>France Francs</td><td>trl</td><td>Turkey Lira</td></tr>
+       <tr><td>dem</td><td>Germany Deutsche Marks</td><td>gbp</td><td>United Kingdom Pounds</td></tr>
+       <tr><td>xau</td><td>Gold Ounces</td><td>usd</td><td>United States Dollars</td></tr>
+       <tr><td>grd</td><td>Greece Drachmas</td><td>veb</td><td>Venezuela Bolivar</td></tr>
+       <tr><td>hkd</td><td>Hong Kong Dollars</td><td>zmk</td><td>Zambia Kwacha</td></tr>
+       <tr><td>huf</td><td>Hungary Forint</td><td>eur</td><td>Euro</td></tr>
+       <tr><td>isk</td><td>Iceland Krona</td><td>xcd</td><td>Eastern Caribbean Dollars</td></tr>
+       <tr><td>inr</td><td>India Rupees</td><td>xdr</td><td>Special Drawing Right (IMF)</td></tr>
+       <tr><td>idr</td><td>Indonesia Rupiah</td><td>xag</td><td>Silver Ounces</td></tr>
+       <tr><td>iep</td><td>Ireland Punt</td><td>xau</td><td>Gold Ounces</td></tr>
+       <tr><td>ils</td><td>Israel New Shekels</td><td>xpd</td><td>Palladium Ounces</td></tr>
+       <tr><td>itl</td><td>Italy Lira</td><td>xpt</td><td>Platinum Ounces</td></tr>
+       <tr><td>jmd</td><td>Jamaica Dollars</td><td>&nbsp;</td><td>&nbsp;</td></tr>
+       </table>
+<p>
+
+<hr>
+<center><font size=-1><i>Copyright &copy; 2002 TrustCommerce</i></font></center>
+
+</body>
+</html>
+
diff --git a/ext/tclink/doc/TCDevGuide.txt b/ext/tclink/doc/TCDevGuide.txt
new file mode 100644 (file)
index 0000000..d017ec4
--- /dev/null
@@ -0,0 +1,1459 @@
+     ----------------------------------------------------------------------
+
+                      TrustCommerce Developer's Guide 2.2
+
+   http://www.trustcommerce.com
+   developer@trustcommerce.com
+
+   January 25, 2002
+
+     ----------------------------------------------------------------------
+
+Table of Contents
+
+   I. Introduction                        
+   II. Connecting via TCLink              
+   III. Transaction Types                 
+   IV. Input Parameters                   
+   V. Return Parameters                   
+   VI. Credit Card Preauths and Sales     
+   VII. Card Verification Value (CVV)     
+   VII. Card-Present Transactions         
+   IX. ACH                                
+   X. Postauths, Credits, and Chargebacks 
+   XI. Billing IDs                        
+   XII. Recurring Billing                 
+   XIII. TCS Wallet                       
+   XIV. Automated Fulfillment             
+   XV. Vault Query API                    
+   Appendix A - Test Data                 
+   Appendix B - Troubleshooting           
+   Appendix C - Connecting via HTTPS POST 
+   Appendix D - Currency Table            
+
+     ----------------------------------------------------------------------
+
+I. Introduction
+
+   This guide covers the TrustCommerce transactional processing API. It is
+   platform- and language-neutral. If you are a developer programming
+   processing functionality to a software package or website, then this guide
+   is for you. If you are connecting via a pre-integrated commerce package,
+   including shopping carts such as StoreForge, Mal's e-Commerce, PDG Cart,
+   or AllCommerce, then you do not need this document.
+
+   Definitions of credit card processing terms and information about the
+   Vault website are contained in the TrustCommerce User's Guide, and will
+   not be covered here. If you are not familiar with the basics of credit
+   card processing (such as the difference between an auth and capture), then
+   you should probably read the User's Guide first. The User's Guide also
+   describes use of the Vault website's reporting capabilities, which you may
+   find useful to confirm that your test transactions are working as
+   expected.
+
+   There are two methods of connecting to the TrustCommerce gateway at the
+   programming level: the TCLink client software, and an HTTPS POST to the
+   Vault server. TCLink is HIGHLY recommend, as it offers support for
+   TrustCommerce's unique features such as automated failover and enhanced
+   security through server certificate verification. It's available for many
+   platforms and languages, and installation is straightforward, so you
+   should try to use it if possible. If you are unable to use TCLink for
+   whatever reason, the HTTPS POST method will still allow you to access most
+   features of the TrustCommerce processing engine, but be aware that it
+   cannot match the speed and especially the reliability of TCLink.
+
+II. Connecting via TCLink
+
+   The TCLink API is available for download from the Vault website, in the
+   "Downloads" section. Be sure to chose the version that matches the
+   platform and language that you are using. In particular, Win32 developers
+   will probably always want the COM object, which contains support for a
+   number of different languages on the Win32 platform, including ASP,
+   ColdFusion, Perl, PHP, and Python.
+
+   Installation instructions specific to the TCLink version you've downloaded
+   can be found in the readme file contained with the archive. It will also
+   contain a version of the TCTest program specific to the language you're
+   using. It's highly recommended that you look over this example, and even
+   use it as the basis for your own code. In fact, you should look over the
+   code sample first to get a feel for the API, then return to reading this
+   document.
+
+   Versions of TCLink for high-level languages (including PHP, Perl, Python,
+   and Java) with built in support for hashes only have one method: Send().
+   This method accepts a single parameter, a hash of input values, and
+   returns a single parameters, a hash of output values. The only other
+   method avaliable is GetVersion(), which returns the version string for
+   TCLink.
+
+   TCLink for other languages (including C/C++, Win32 COM, and CFX) contains
+   four basic methods: Create(), PushParam(), Send(), and GetResponse().
+   C-style TCLink functions are described in the table below.
+
+  TCLink Function Names
+
+   +------------------------------------------------------------------------+
+   |    Function Name    |                   Description                    |
+   |---------------------+--------------------------------------------------|
+   | CreateLink()        | Create a new transaction handle.                 |
+   |---------------------+--------------------------------------------------|
+   | PushParam()         | Push a parameter into the transaction.           |
+   |---------------------+--------------------------------------------------|
+   | Send()              | Submit a transaction to the gateway.             |
+   |---------------------+--------------------------------------------------|
+   | GetResponse()       | Retrieve a response parameter from the           |
+   |                     | transaction.                                     |
+   |---------------------+--------------------------------------------------|
+   | GetEntireResponse() | Get the entire response for the transaction,     |
+   |                     | primarily use for debugging or logging.          |
+   |---------------------+--------------------------------------------------|
+   | GetVersion()        | Get the version string for the TCLink API in     |
+   |                     | use.                                             |
+   +------------------------------------------------------------------------+
+
+   These four methods map to the four stages of running a transaction:
+   initialize, push a number of parameters describing the transaction, send
+   the transaction to the TrustCommerce gateway for processing, and finally
+   get details about the transaction results.
+
+   The only method which contacts the TC servers is Send(). This function
+   will block for one or two seconds while the transaction is processed.
+   Afterward, you can retrieve response parameters at your leisure; they are
+   stored internally in TCLink.
+
+III. Transaction Types
+
+   You may wish to read the section of the TCS User's Guide which describes
+   the transaction types and the authorization/capture process, especially if
+   you are not already familiar with credit card processing.
+
+   In terms of parameters passed, preauths and sales are almost identical.
+   They take account data and personal information about the customer, along
+   with a transaction amount. The transaction is authorized and the response
+   values returned. In the case of a sale, the item is also immediately
+   submitted for capture. Preauths are not captured until they are
+   postauthed.
+
+   Postauths and credits are also very similar to one another. They indicate
+   a capture or a return of funds for a previous transaction, and no personal
+   data about the customer or their payment method is passed.
+
+   There are three other types of transaction. Store and unstore are covered
+   in the Billing ID section of this document. Walletsale is covered under
+   the TCS Wallet section.
+
+IV. Input Parameters
+
+   There are a large number of parameters available for describing
+   transactions. Not all parameters are accepted for all transaction types,
+   and most parameters are optional. Most transactions can be sent with only
+   a few parameters. The only parameters always required are custid,
+   password, and action.
+
+   Parameters are carefully checked for format and size before the
+   transaction is sent. If there are any errors in the parameters you've
+   entered, the transaction will be aborted and detailed information about
+   the errors will be returned. These return values are described in more
+   detail in the next section.
+
+   The parameters presented in the following tables are used by all
+   transaction types.
+
+  Required Parameters
+
+   +------------------------------------------------------------------------+
+   | Parameter Name |                      Description                      |
+   |----------------+-------------------------------------------------------|
+   | amount         | Amount of the transaction, in cents. (example: "500"  |
+   |                | is $5.00)                                             |
+   |----------------+-------------------------------------------------------|
+   | custid         | Your customer ID number assigned to you by            |
+   |                | TrustCommerce.                                        |
+   |----------------+-------------------------------------------------------|
+   | password       | The password for your custid as assigned by           |
+   |                | TrustCommerce.                                        |
+   |----------------+-------------------------------------------------------|
+   |                | The transaction type; can be one of preauth, sale,    |
+   | action         | postauth, credit, store, unstore, walletsale, or      |
+   |                | chargeback                                            |
+   +------------------------------------------------------------------------+
+
+  Optional Parameters
+
+   +------------------------------------------------------------------------+
+   | Parameter Name |                      Description                      |
+   |----------------+-------------------------------------------------------|
+   | amount         | Amount of the transaction, in cents. (example: "500"  |
+   |                | is $5.00)                                             |
+   |----------------+-------------------------------------------------------|
+   | demo           | When set to "y", the transaction will be a test       |
+   |                | transaction only.                                     |
+   |----------------+-------------------------------------------------------|
+   |                | Free-form text field intended for storing ticket      |
+   | ticket         | number or order number associated with the            |
+   |                | transaction, to aid merchants in order tracking and   |
+   |                | reporting.                                            |
+   |----------------+-------------------------------------------------------|
+   |                | Free-form text field intended for recording the       |
+   | operator       | operator that entered the transaction, to aid         |
+   |                | merchants in order track and reporting.               |
+   +------------------------------------------------------------------------+
+
+   The demo parameter is of particular note for testing. Demo transactions
+   allow you to test your processing system without charging real money to a
+   card, and you will not be charged and transaction fees. They are also
+   flagged separately in the Vault database and will not appear in the
+   regular accounting reports.
+
+   On card-not-present transactions, the ticket parameter is passed to the
+   acquiring bank in the settlement process as the "purchase identifier."
+   This may aid in reconciling the TrustCommerce transactions with the
+   deposits made into the merchant bank account. If no ticket is passed, then
+   the TrustCommerce transID will be sent to the bank instead.
+
+V. Return Parameters
+
+   Any transaction sent will return several parameters describing the success
+   or failure of the transaction. Properly formatted transactions will always
+   return a transaction ID (or "transID') this is the unique identifier for
+   this transaction, and can be used to retrieve the transaction from the
+   Vault website, or otherwise access the transaction in the future. (For
+   example, in order to credit a previous transaction, you will need to send
+   the transID of said transaction.)
+
+   Transactions also always return a status parameter which describes the
+   success or failure of the transaction. Status can be set to one of the
+   following:
+
+  Status
+
+   +------------------------------------------------------------------------+
+   | Status Value |                       Description                       |
+   |--------------+---------------------------------------------------------|
+   | approved     | The transaction was successfully authorized.            |
+   |--------------+---------------------------------------------------------|
+   | accepted     | The transaction has been successfully accepted into the |
+   |              | system.                                                 |
+   |--------------+---------------------------------------------------------|
+   | decline      | The transaction was declined, see declinetype for       |
+   |              | further details.                                        |
+   |--------------+---------------------------------------------------------|
+   | baddata      | Invalid parameters passed, see error for further        |
+   |              | details.                                                |
+   |--------------+---------------------------------------------------------|
+   | error        | System error when processing the transaction, see       |
+   |              | errortype for details.                                  |
+   +------------------------------------------------------------------------+
+
+   The difference between approved and accepted is subtle, but important.
+   Approved means that the transaction was an authorization of some sort, and
+   has been successfully cleared with the bank. Accepted only means that the
+   transaction was queued into the system without errors, but may be rejected
+   at some later time. An example of the difference is a sale versus a
+   credit. A sale is a realtime authorization, so it returns approved on
+   success. A credit is not realtime; there is no such thing as a "credit
+   authorization." Instead it is queued up for processing by the bank and
+   there is the small but non-zero posibility that it will be rejected at a
+   later time. In practice, however, this rarely happens, so the developer
+   need not worry unduly.
+
+   When status is set to decline, the parameter declinetype will contain one
+   of the following:
+
+  Decline Type
+
+   +------------------------------------------------------------------------+
+   | Declinetype Value |                    Description                     |
+   |-------------------+----------------------------------------------------|
+   | decline           | This is a "true" decline, it almost always is a    |
+   |                   | result of insufficient funds on the card.          |
+   |-------------------+----------------------------------------------------|
+   | avs               | AVS failed; the address entered does not match the |
+   |                   | billing address on file at the bank.               |
+   |-------------------+----------------------------------------------------|
+   |                   | CVV failed; the number provided is not the correct |
+   | cvv               | verification number for the card. (See section X   |
+   |                   | for details on CVV.)                               |
+   |-------------------+----------------------------------------------------|
+   |                   | The card must be authorized manually over the      |
+   |                   | phone. You may choose to call the customer service |
+   | call              | number listed on the card and ask for an offline   |
+   |                   | authcode, which can be passed in the               |
+   |                   | offlineauthcode field.                             |
+   |-------------------+----------------------------------------------------|
+   | carderror         | Card number is invalid, usually the result of a    |
+   |                   | typo in the card number.                           |
+   |-------------------+----------------------------------------------------|
+   | authexpired       | Attempt to postauth an expired (more than 7 days   |
+   |                   | old) preauth.                                      |
+   |-------------------+----------------------------------------------------|
+   | dailylimit        | Daily limit in transaction count or amount as been |
+   |                   | reached.                                           |
+   |-------------------+----------------------------------------------------|
+   | weeklylimit       | Weekly limit in transaction count or amount as     |
+   |                   | been reached.                                      |
+   |-------------------+----------------------------------------------------|
+   | monthlylimit      | Monthly limit in transaction count or amount as    |
+   |                   | been reached.                                      |
+   +------------------------------------------------------------------------+
+
+   A status of baddata indicates that no transaction was attempted because
+   one or more parameters was invalid. In this case, the parameter error will
+   indicate the problem, and the offenders parameter will list the offending
+   input fields. The error parameter may be set to one of the following:
+
+  Bad Data
+
+   +------------------------------------------------------------------------+
+   |    Error Value     |                    Description                    |
+   |--------------------+---------------------------------------------------|
+   | missingfields      | Some parameters required for this transaction     |
+   |                    | type were not sent.                               |
+   |--------------------+---------------------------------------------------|
+   | extrafields        | Parameters not allowed for this transaction type  |
+   |                    | were sent.                                        |
+   |--------------------+---------------------------------------------------|
+   | badformat          | A field was improperly formatted, such as         |
+   |                    | non-digit characters in a number field.           |
+   |--------------------+---------------------------------------------------|
+   | badlength          | A field was longer or shorter than the server     |
+   |                    | allows.                                           |
+   |--------------------+---------------------------------------------------|
+   |                    | The merchant can't accept data passed in this     |
+   |                    | field. If the offender is "cc", for example, it   |
+   |                    | usually means that you tried to run a card type   |
+   | merchantcantaccept | (such as American Express or Discover) that is    |
+   |                    | not supported by your account. If it was          |
+   |                    | "currency", you tried to run a currency type not  |
+   |                    | supported by your account.                        |
+   |--------------------+---------------------------------------------------|
+   | mismatch           | Data in one of the offending fields did not       |
+   |                    | cross-check with the other offending field.       |
+   +------------------------------------------------------------------------+
+
+   A status of error indicates the an error occurred while processing the
+   transaction. These are almost always networking errors; see the
+   Troubleshooting section for more. If the status is error, then the
+   errortype parameter will be set to one of the following:
+
+  Error
+
+   +------------------------------------------------------------------------+
+   | Errortype Value |                     Description                      |
+   |-----------------+------------------------------------------------------|
+   | cantconnect     | Couldn't connect to the TrustCommerce gateway. Check |
+   |                 | your Internet connection to make sure it is up.      |
+   |-----------------+------------------------------------------------------|
+   |                 | The TCLink software was unable to resolve DNS        |
+   | dnsfailure      | hostnames. Make sure you have name resolving ability |
+   |                 | on the machine.                                      |
+   |-----------------+------------------------------------------------------|
+   | linkfailure     | The connection was established, but was severed      |
+   |                 | before the transaction could complete.               |
+   |-----------------+------------------------------------------------------|
+   |                 | The bank servers are offline and unable to authorize |
+   | failtoprocess   | transactions. Try again in a few minutes, or try a   |
+   |                 | card from a different issuing bank.                  |
+   +------------------------------------------------------------------------+
+
+   Other parameters (such as avs or billingid) may be returned by the
+   transaction depending on the action; see sections covering the transaction
+   type you're running for detailed information on the specialized return
+   values.
+
+VI. Credit Card Preauths and Sales
+
+   The 'preauth' and 'sale' actions are identical in terms of parameters and
+   function. The only difference is that a sale submits the item for capture
+   as well, while preauths run the authorization only and can be postauthed
+   at another time.
+
+   The parameters that can be passed with these action types are described in
+   the following two tables. The first table list required fields that you
+   must pass in order to send the transaction. The second table lists
+   optional fields that you can pass if you wish, but are not required.
+
+  Required Parameters
+
+   +------------------------------------------------------------------------+
+   | Parameter Name |                      Description                      |
+   |----------------+-------------------------------------------------------|
+   | amount         | Amount of the transaction, in cents. (example: "500"  |
+   |                | is $5.00)                                             |
+   |----------------+-------------------------------------------------------|
+   | cc             | Credit card number, digits only (no spaces or dashes) |
+   |----------------+-------------------------------------------------------|
+   | exp            | Credit card expiration date, in MMYY format           |
+   +------------------------------------------------------------------------+
+
+  Optional Parameters
+
+   +------------------------------------------------------------------------+
+   | Parameter Name  | Default Value |             Description              |
+   |-----------------+---------------+--------------------------------------|
+   | media           | cc            | "cc" for credit card or "ach" for    |
+   |                 |               | ACH.                                 |
+   |-----------------+---------------+--------------------------------------|
+   | currency        | usd           | Currency code (see section X for the |
+   |                 |               | table of codes)                      |
+   |-----------------+---------------+--------------------------------------|
+   | avs             | y             | AVS requested, "y" or "n" (see notes |
+   |                 |               | below).                              |
+   |-----------------+---------------+--------------------------------------|
+   | name            |               | Cardholder's name.                   |
+   |-----------------+---------------+--------------------------------------|
+   | address1        |               | First line of cardholder's street    |
+   |                 |               | address.                             |
+   |-----------------+---------------+--------------------------------------|
+   | address2        |               | Second line of cardholder's street   |
+   |                 |               | address.                             |
+   |-----------------+---------------+--------------------------------------|
+   | city            |               | Cardholder's city.                   |
+   |-----------------+---------------+--------------------------------------|
+   | state           |               | Two-character code for the           |
+   |                 |               | cardholder's state.                  |
+   |-----------------+---------------+--------------------------------------|
+   | zip             |               | Cardholder's zipcode, five or nine   |
+   |                 |               | digits (no spaces or dashes).        |
+   |-----------------+---------------+--------------------------------------|
+   | country         |               | Cardholder's country, leave blank    |
+   |                 |               | for US.                              |
+   |-----------------+---------------+--------------------------------------|
+   | phone           |               | Cardholder's phone number.           |
+   |-----------------+---------------+--------------------------------------|
+   | email           |               | Cardholder's email address.          |
+   |-----------------+---------------+--------------------------------------|
+   |                 |               | Six-digit numeric code used to       |
+   | offlineauthcode |               | "force" the transaction (see notes   |
+   |                 |               | below).                              |
+   +------------------------------------------------------------------------+
+
+   A note about AVS: The AVS system is a useful way to help screen for fraud,
+   as it requires that whomever is sending the transaction know the billing
+   address for the card in question. As a merchant, you should know that AVS
+   is not uniformly supported by card issuers; approximately 30% of US-based
+   credit cards will not have AVS capability, and AVS is not available with
+   any non-US cards at all. If avs of "y" (the default) is used, it will
+   attempt to verify the address data with AVS, but if it is unavailable, it
+   will not cause the transaction to fail. Only if AVS is available and the
+   address data does not match will the transaction be declined due to AVS.
+   You may wish to screen AVS results more closely. For this reason, sales
+   and preauths will return the AVS code in a parameter named avs. It returns
+   a single character code, which are enumerated in the table below.
+
+  AVS Returns Codes
+
+         +------------------------------------------------------------+
+         | Code |                     Description                     |
+         |------+-----------------------------------------------------|
+         |  X   | Exact match, 9 digit zipcode.                       |
+         |------+-----------------------------------------------------|
+         |  Y   | Exact match, 5 digit zipcode.                       |
+         |------+-----------------------------------------------------|
+         |  A   | Street address match only.                          |
+         |------+-----------------------------------------------------|
+         |  W   | 9 digit zipcode match only.                         |
+         |------+-----------------------------------------------------|
+         |  Z   | 5 digit zipcode match only.                         |
+         |------+-----------------------------------------------------|
+         |  N   | No match on street address or zipcode.              |
+         |------+-----------------------------------------------------|
+         |  U   | AVS unavailable on this card.                       |
+         |------+-----------------------------------------------------|
+         |  G   | Non-US card issuer, AVS unavailable.                |
+         |------+-----------------------------------------------------|
+         |  R   | Card issuer system currently down, try again later. |
+         |------+-----------------------------------------------------|
+         |  E   | Error, ineligible - not a mail/phone order.         |
+         |------+-----------------------------------------------------|
+         |  S   | Service not supported.                              |
+         |------+-----------------------------------------------------|
+         |  0   | General decline or other error.                     |
+         +------------------------------------------------------------+
+
+   Only the numeric parts of the address (street address and zipcode) are
+   verified. It should also be noted that oftentimes AVS data is incorrect or
+   not entirely up-to-date, dependent upon the card issuing bank. For these
+   reasons, you should treat AVS as a helpful tool which should be used in
+   combination with other methods (dependent upon your business model) for
+   screening transactions. If you trust AVS too blindly, you may risk losing
+   legitimate sales. Some merchants (again, dependent upon business model)
+   choose to turn AVS off altogether. You should analyze your customer base
+   and make the decision that will work best for your business.
+
+   A note on offlineauthcode: Some cards returned a declinetype of call. This
+   indicates that the card cannot be automatically authorized, but if you
+   call the card issuers, they may be able to give you a manual
+   authorization, which will consist of a six-digit auth code. You may then
+   push the transaction through by entering that code into the
+   offlineauthcode field. Be warned: offlineauthcode is NOT a realtime
+   authorization, and is not guaranteed in the same way as a normal
+   authorization. Be careful with the use of this parameter.
+
+  Preauth/Sale Example
+
+         params = {
+                 'custid':    'mycustid',
+                 'password':  'mypasswd',
+                 'action':    'preauth',
+                 'amount':    '500',
+                 'cc':        '4111111111111111',
+                 'exp':       '0404',
+                 'name':      'Jennifer Smith',
+                 'address1':  '123 Test St.',
+                 'city':      'Somewhere',
+                 'state':     'CA',
+                 'zip':       '90001',
+                 'avs':       'y'
+         }
+
+         result = tclink.send(params)
+
+         if (result['status'] == 'approved'):
+                 print  'Transaction was successful'
+         elif (result['status'] == 'decline'):
+                 print 'Transaction declined.  Reason: ', result['declinetype']
+         elif (result['status'] == 'baddata'):
+                 print 'Improperly formatted data.  Offending fields: ', result['offenders']
+         else:
+                 print 'An error occured: ', result['errortype']
+
+         print 'Here are the full details:'
+         print result
+
+VII. Card Verification Value (CVV)
+
+   Another method for cardholder verification is the CVV system. Visa cards
+   use what is called a CVV2 code; Mastercards call it CVC2, and American
+   Express calls it CID. CVV2 and CVC2 (Visa/MC) are located on the back of
+   the credit card, printed in ink on the signature strip. The number is the
+   last three digits on the righthand side of the long string of numbers on
+   the strip. In the case of CID (AmEx), the number is a four-digit value
+   located on the front of the card, printed just above the card number on
+   the lefthand side. This value is passed to TCLink through the following
+   parameter.
+
+  CVV Parameters
+
+             +----------------------------------------------------+
+             | Parameter Name |            Description            |
+             |----------------+-----------------------------------|
+             | cvv            | A three or four digit CVV number. |
+             +----------------------------------------------------+
+
+   The CVV value will be checked if anything is passed in this parameter. (If
+   you don't include the parameter, no CVV test will be run.) If the CVV
+   matches, the transaction will run as normal. If it does not, you will
+   receive a status of decline, and a declinetype of cvv.
+
+  CVV Example
+
+         params = {
+                 'custid':    'mycustid',
+                 'password':  'mypasswd',
+                 'action':    'sale',
+                 'amount':    '500',
+                 'cc':        '4111111111111111',
+                 'exp':       '0404',
+                 'cvv':       '123'
+         }
+
+         result = tclink.send(params)
+
+         if (result['status'] == 'decline')
+                 if (result['declinetype'] == 'cvv')
+                         print 'The CVV number is not valid.'
+
+VII. Card-Present Transactions
+
+   In a retail environment with a card swiper, you may wish to pass magnetic
+   stripe data along with the other credit card information on a preauth or
+   sale. There are two parameters which you can use to send this data, named
+   track1 and track2. Each one is for a different type of track data, and
+   depends on the type of card reader being used.
+
+  Card-Present Parameters
+
+              +--------------------------------------------------+
+              | Parameter Name |           Description           |
+              |----------------+---------------------------------|
+              | track1         | Up to 79 bytes of Track 1 data. |
+              |----------------+---------------------------------|
+              | track2         | Up to 40 bytes of Track 2 data. |
+              +--------------------------------------------------+
+
+   You can include all data read from the track, but only data between the
+   start sentinel (a '%' character for track1 and a ';' for track2) and the
+   end sentinel ('?') will be used. Everything outside the start and end
+   sentinels (such as the trailing LRC character) will be discarded.
+
+   The cc and exp fields may be passed, but are not required, since they will
+   be extracted from the track data. If you do pass one or both of these
+   fields, however, and it does not match the data extracted from the track
+   data, a status of baddata and an error mismatch will be returned.
+
+   If both track1 and track2 data are passed, only the system will choose
+   track1 by default for the authorization, and track2 will be discarded.
+
+   Generally AVS and address data are not necessary for swiped transactions,
+   but you may pass them anyway if you choose.
+
+  Card Present Example
+
+         params = {
+                 'custid':    'mycustid',
+                 'password':  'mypasswd',
+                 'action':    'sale',
+                 'amount':    '500'
+         }
+
+         params['track1'] = CardReader.readMagStripe()
+
+         result = tclink.send(params)
+
+IX. ACH
+
+   ACH, also known as electronic checks, are very different from credit cards
+   in that they allow a direct debit or credit to a checking account. The
+   concept of "authorization" does not exist; it is purely a money transfer.
+   For this reason, the only transaction types available for ACH are sale and
+   credit. ACH credits are identical to all other types of credits in the
+   TrustCommerce system, so please refer to section X for details on issuing
+   credits.
+
+   ACH sales take the same parameters as credit card sales, with the
+   exception of the "cc" and "exp" fields. Instead, use the following
+   parameters.
+
+  ACH Parameters
+
+   +------------------------------------------------------------------------+
+   | Parameter Name |                      Description                      |
+   |----------------+-------------------------------------------------------|
+   | routing        | The routing number of the bank being debited.         |
+   |----------------+-------------------------------------------------------|
+   | account        | The account number of the person or business being    |
+   |                | debited.                                              |
+   +------------------------------------------------------------------------+
+
+   AVS is not available for ACH transactions, so the AVS setting is ignored.
+
+   There is only one declinetype returned from unsuccessful ACH sales, and
+   that is "decline."
+
+  ACH Example
+
+         params = {
+                 'custid':    'mycustid',
+                 'password':  'mypass',
+                 'action':    'sale',
+                 'media':     'ach',
+                 'amount':    '1000',
+                 'routing':   '123456789',
+                 'account':   '55544433322211'
+         }
+
+         tclink.send(params)
+
+X. Postauths, Credits, and Chargebacks
+
+   These three transaction types are similar in that they reference a
+   successful transaction previously executed through the TrustCommerce
+   system. No credit card information or other personal information fields
+   will be accepted by this transaction types; there is only one required
+   parameter.
+
+  Required Parameters
+
+   +------------------------------------------------------------------------+
+   | Parameter Name |                      Description                      |
+   |----------------+-------------------------------------------------------|
+   | transid        | The transaction ID (format: nnn-nnnnnnnnnn) of the    |
+   |                | referenced transaction.                               |
+   +------------------------------------------------------------------------+
+
+   In addition, postauths and credits can take an optional amount parameter.
+
+  Optional Parameters
+
+   +------------------------------------------------------------------------+
+   | Parameter Name |                      Description                      |
+   |----------------+-------------------------------------------------------|
+   | amount         | The amount, in cents, to credit or postauth if it is  |
+   |                | not the same as the original amount.                  |
+   +------------------------------------------------------------------------+
+
+   If no amount is passed, the default will be to take the amount from the
+   original transaction. If, however, you wish to credit or postauthorize
+   less than the original amount, you may pass this parameter.
+
+  Credit Example
+
+         params = {
+                 'custid':    'mycustid',
+                 'password':  'mypass',
+                 'action':    'credit',
+                 'transid':   '001-0000111101'
+         }
+
+         tclink.send(params)
+
+         if (result['status'] != 'accepted')
+                 print 'Credit unsuccesful.'
+
+XI. Billing IDs
+
+   The Billing ID system enables you to store the billing information for
+   your customers in the encrypted TrustCommerce database, and recall it with
+   a single six-character alphanumeric code known as a billing ID. Besides
+   offloading the liability of storing sensitive data such as credit card
+   numbers from your business to TrustCommerce, it also can simplify database
+   access on your servers.
+
+   Billing IDs add two new actions, store and unstore. These allow you to
+   create, update, and deactivate billing IDs. Once stored, the billing ID
+   will be passed in place of the many billing information fields for preauth
+   and sale transactions.
+
+   The store transaction looks very similar to a preauth or sale. You may
+   pass credit card information, billing and shipping address, or even ACH
+   information. (Please see sections X and X for a detailed description of
+   these parameters.) It adds one additional parameter:
+
+  Store Parameters
+
+   +------------------------------------------------------------------------+
+   | Parameter Name |                      Description                      |
+   |----------------+-------------------------------------------------------|
+   | verify         | When set to "y", a $1.00 preauth will be run on the   |
+   |                | card to ensure that it is valid.                      |
+   |----------------+-------------------------------------------------------|
+   | billingid      | Pass if you wish to update values of an existing      |
+   |                | billing ID.                                           |
+   +------------------------------------------------------------------------+
+
+   The verify parameter is useful for ensuring that the card number is valid
+   if you are not planning to bill the customer right away. It has no effect
+   for ACH billing IDs, because there is no such thing as an ACH preauth. By
+   default, the verification uses AVS; if you don't wish to use AVS, pass an
+   avs of "n". Please note: normally, billing ID storage returns a status of
+   accepted, because the card is unverified. If you use the verify parameter,
+   however, it will return approved upon success.
+
+   The unstore action takes a single parameter:
+
+  Unstore Parameters
+
+   +------------------------------------------------------------------------+
+   | Parameter Name |                      Description                      |
+   |----------------+-------------------------------------------------------|
+   | billingid      | The six-character alphanumeric billing ID returned by |
+   |                | a previous store transaction.                         |
+   +------------------------------------------------------------------------+
+
+   Unstore removes the billing ID from active use, and you won't be able to
+   run further transactions on it. For your convenience, however, it does
+   remain visible in Vault (flagged as an inactive ID), so you can still look
+   up old IDs if needed.
+
+   Now, the moment of truth: to run a billing ID transaction, pass the
+   billingid parameter to a preauth or a sale in place of all of the usual
+   billing info fields (name, cc, exp, routing, account, etc). That's all
+   there is to it! You'll find that your sale or preauth transactions are now
+   only a few parameters: custid, password, billingid, and amount.
+
+  Billing ID Example
+
+         # First, store a new ID.
+         params = {
+                 'custid':    'mycustid',
+                 'password':  'mypass',
+                 'action':    'store',
+                 'cc':        '4111111111111111',
+                 'exp':       '0404',
+                 'name':      'Jennifer Smith'
+         }
+
+         result = tclink.send(params)
+
+         if (result['status'] == 'accepted'):
+                 # It was succesfully stored.  Now try running a transaction on the new ID.
+                 billingid = result['billingid']
+                 params2 = {
+                         'custid':    'mycustid',
+                         'password':  'mypass',
+                         'action':    'sale',
+                         'billingid': billingid,
+                         'amount':    '995'
+                 }
+                 tclink.send(params2);
+                 # Unstore the ID now that we are done.
+                 params3 = {
+                         'custid':    'mycustid',
+                         'password':  'mypass',
+                         'action':    'unstore',
+                         'billingid': billingid
+                 }
+                 tclink.send(params3)
+
+XII. Recurring Billing
+
+   Recurring billing (sometimes also called "subscription billing") is an
+   extension of the billing ID system. There are four parameters that are
+   added to a store which turn the billing ID into a recurring billing ID.
+   They are described below.
+
+  Recurring Parameters
+
+   +------------------------------------------------------------------------+
+   | Parameter Name | Required? |                Description                |
+   |----------------+-----------+-------------------------------------------|
+   | cycle          |     X     | Repeat cycle in days, weeks, months, or   |
+   |                |           | years.                                    |
+   |----------------+-----------+-------------------------------------------|
+   | amount         |     X     | Amount to bill in cents.                  |
+   |----------------+-----------+-------------------------------------------|
+   | start          |           | Date to start, or else offset from        |
+   |                |           | current date (defaults to now).           |
+   |----------------+-----------+-------------------------------------------|
+   | payments       |           | Number of payments to make (defaults to   |
+   |                |           | infinite).                                |
+   +------------------------------------------------------------------------+
+
+   Cycle is in the format of a number followed by a character representing
+   the timeframe: 'd' for days, 'w' for weeks, 'm' for months or 'y' for
+   years. For example, a value of "3d" in this field would cause the charge
+   to recur every three days, whereas a value of "2m" would cause it to recur
+   every two months.
+
+   Amount is identical to the amount passed to a sale or a preauth, and
+   indicates the amount of each charge made during the subscription.
+
+   Start is an optional field which allows the delay of the cycle's start. By
+   default, the cycle starts the day the billing ID is stored. If it is
+   specified in the format YYYY-MM-DD, it indicates a date when the first
+   payment should be made. (For example, "2005-02-01" would be February 1,
+   2005.) If it is in the same format as the cycle (a number followed by a
+   character), it indicates an offset from the current date. (For example,
+   "1d" would start the billing tomorrow.) Note: recurring transactions will
+   appear at the end of the business day they are billed on, so the first
+   transaction for new subscriptions will not appear in the Vault until that
+   time.
+
+   Payments is also optional; left blank or set to zero it will continue the
+   billing cycle until it is manually interrupted by an unstore, or by
+   updating the billing ID with cycle set to "null". Once the final payment
+   is made, the billing ID will be unstored.
+
+  Recurring Billing Example
+
+         params = {
+                 'custid':    'mycustid',
+                 'password':  'mypass',
+                 'action':    'store',
+                 'cc':        '4111111111111111',
+                 'exp':       '0404',
+                 'name':      'Jennifer Smith',
+                 'amount':    '1200'
+         }
+
+         mode = chooseSubscriptionMode()
+
+         if (mode == 1):
+                 # Make a payment every day, infinitely (or until someone manually disables it)
+                 params['cycle'] = '1d';
+         elif (mode == 2):
+                 # Make a payment once a month for one year
+                 params['cycle'] = '1m';
+                 params['payments'] = '12';
+         elif (mode == 3):
+                 # Make a payment every six weeks, starting one week from now
+                 params['cycle'] = '62';
+                 params['start'] = '1w';
+         elif (mode == 4):
+                 # Make anual payments, and don't start until September 1, 2002
+                 params['cycle'] = '1y';
+                 params['start'] = '2003-09-02';
+
+         tclink.send(params)
+
+XIII. TCS Wallet
+
+   The TCS Wallet is an additional service offered by the TrustCommerce
+   gateway that allows you to run many small micropayments which are later
+   lumped together and submitted as a single, large payment. This can offer a
+   substantial savings for the merchant in transaction fees, as merchant
+   account providers tend to penalize merchants that run small payments.
+
+   The Wallet is an extension of the billing ID system. It adds three new
+   parameters to the store action, described below.
+
+  Wallet Parameters
+
+   +------------------------------------------------------------------------+
+   | Parameter Name |                      Description                      |
+   |----------------+-------------------------------------------------------|
+   | wallet         | "y" to enable the wallet.                             |
+   |----------------+-------------------------------------------------------|
+   | walletsize     | Accumulated amount, in cents, before the wallet is    |
+   |                | submitted for capture.                                |
+   |----------------+-------------------------------------------------------|
+   | walletexposure | Length of time to wait before capturing the wallet.   |
+   +------------------------------------------------------------------------+
+
+   In order to enable wallets for the billing ID that you are storing, set
+   the "wallet" parameter to "y". The other two parameters are optional, as
+   there are default values attached to your TC account. If you wish to
+   change these values (which are normally $10.00 and 72 hours) please
+   contact TrustCommerce. If you wish to change the values for an individual
+   billing ID without changing your defaults, include these parameters.
+
+   Once the billing ID is stored, it is possible to use a new action type on
+   the ID called walletsale. It is identical to a sale in all ways, except
+   that it can only be used on wallet-enabled billing IDs, and it can accept
+   amounts anywhere from $0.01 up to the size of the wallet. Walletsale will
+   usually return "approved", but it may return "decline" if the stored
+   credit card fails to re-authorize when the current wallet is exceeded.
+   Except for these two modifications (the wallet parameters on the store,
+   and changing sales to walletsales), there is no extra development to be
+   done client-side to make wallets work. Captures happen automatically after
+   walletexposure has expired or the walletamount has been used up;
+   reauthorizations also happen automatically.
+
+  Wallet Example
+
+         # First, store a new ID with the wallet enabled.
+         params = {
+                 'custid':    'mycustid',
+                 'password':  'mypass',
+                 'action':    'store',
+                 'cc':        '4111111111111111',
+                 'exp':       '0404',
+                 'name':      'Jennifer Smith',
+                 'wallet':    'y'
+         }
+
+         result = tclink.send(params)
+
+         if (result['status'] == 'approved'):
+                 # We have a new wallet at our disposal.  Run a micropayment on it.
+                 billingid = result['billingid']
+                 params2 = {
+                         'custid':    'mycustid',
+                         'password':  'mypass',
+                         'action':    'walletsale',
+                         'billingid': billingid,
+                         'amount':    '995'
+                 }
+                 tclink.send(params)
+
+XIV. Automated Fulfillment
+
+   TrustCommerce offers the unique feature of automated fulfillment, by which
+   orders submitted through the TCLink API can contain parameters describing
+   product information. This information is then passed on to your
+   fulfillment house, which ships the products automatically.
+
+   First, it is necessary to specify the shipping address for the customer.
+   If it is the same as the billing address, you need not duplicate it, but
+   rather just send the shiptosame parameter set to y. The table below
+   enumerates the shipping parameters.
+
+  ShipTo Parameters
+
+   +------------------------------------------------------------------------+
+   | Parameter Name  |                     Description                      |
+   |-----------------+------------------------------------------------------|
+   | shiptosame      | y or n (defaults to n). If "y", then no other        |
+   |                 | shipto_ parameters should be passed.                 |
+   |-----------------+------------------------------------------------------|
+   | shipto_name     | Name of the product recipient.                       |
+   |-----------------+------------------------------------------------------|
+   | shipto_address1 | First line of shipping address.                      |
+   |-----------------+------------------------------------------------------|
+   | shipto_address2 | Second line (if any) of shipping address.            |
+   |-----------------+------------------------------------------------------|
+   | shipto_city     | City.                                                |
+   |-----------------+------------------------------------------------------|
+   | shipto_state    | State.                                               |
+   |-----------------+------------------------------------------------------|
+   | shipto_zip      | Zipcode, five or nine digits (no spaces or dashes).  |
+   |-----------------+------------------------------------------------------|
+   | shipto_country  | Country, leave blank for US.                         |
+   +------------------------------------------------------------------------+
+
+   Second, some additional data about the order as a whole should be passed
+   in the form of the following parameters.
+
+  Order Header Parameters
+
+   +------------------------------------------------------------------------+
+   |  Parameter Name  |                     Description                     |
+   |------------------+-----------------------------------------------------|
+   | shippingcode     | Three character code indicating shipping method to  |
+   |                  | use.                                                |
+   |------------------+-----------------------------------------------------|
+   | shippinghandling | The total cost of shipping and handling, in cents.  |
+   |------------------+-----------------------------------------------------|
+   | numitems         | Total number of distinct items (product codes) in   |
+   |                  | the order.                                          |
+   +------------------------------------------------------------------------+
+
+   Finally, a number of parameters which describe the details of each type of
+   item must be passed. In the table below, the 'X' character in the
+   parameter name should be replaced with a digit indicating which item it
+   applies to. For example, if numitems is set to three, then you should pass
+   three product codes, in the form of productcode1, productcode2, and
+   productcode3.
+
+  Order Detail Parameters
+
+   +------------------------------------------------------------------------+
+   |  Parameter Name   |                    Description                     |
+   |-------------------+----------------------------------------------------|
+   | productcodeX      | The alphanumeric product code defined by the       |
+   |                   | fulfillment house.                                 |
+   |-------------------+----------------------------------------------------|
+   | quantityX         | The number of items of this type to be shipped.    |
+   |-------------------+----------------------------------------------------|
+   | priceX            | The price of all items of this type not including  |
+   |                   | sales tax or shipping, in cents.                   |
+   |-------------------+----------------------------------------------------|
+   | taxX              | Total tax charged for all items of this product    |
+   |                   | code.                                              |
+   |-------------------+----------------------------------------------------|
+   | shippinghandlingX | Total shipping and handling charged for all items  |
+   |                   | of this product code.                              |
+   +------------------------------------------------------------------------+
+
+   Please note: the shippinghandling field and the shippinghandlingX fields
+   are mutually exclusive. Use one or the other, but not both. If you're not
+   sure which to use, please contact your fulfillment house.
+
+  Fulfillment Example
+
+         params = {
+                 'custid':           'mycustid',
+                 'password':         'mypass',
+                 'action':           'preauth',
+                 'cc':               '4111111111111111',
+                 'exp':              '0404',
+                 'amount':           '1979',  # Total of items, tax, and shipping
+                 'name':             'Jennifer Smith',
+                 'address1':         '123 Test St.',
+                 'city':             'Somewhere',
+                 'state':            'CA',
+                 'zip':              '90001',
+                 'shiptosame':       'y',     # Shipping address is same as billing address
+
+                 'numitems':         '2',     # Two total product codes will be described
+                 'shippingcode':     'OVRNGT',
+                 'shippinghandling': '695',
+
+                 'productcode1':     'PCODE1',
+                 'quantity1':        '3',
+                 'price1':           '600',   # Item 1 costs $2.00, and there are 3 of them
+                 'tax1':             '144',   # Tax of 8%
+
+                 'productcode2':     'PCODE2',
+                 'quantity2':        '1',
+                 'price2':           '500',   # Item 1 costs $5.00, there's only one
+                 'tax2':             '40'     # Tax of 8%
+         }
+
+         tclink.send(params)
+
+XV. Vault Query API
+
+   The Vault website serves as a web-based interface for merchant
+   reconciliation. On the backend, it is a complex database that tracks all
+   transactional data for your TrustCommerce account. The information
+   contained in the Vault can be accessed at the API level using a standard
+   CGI query over HTTPS.
+
+   The query API returns data in CSV (comma separated value) format, which is
+   just a flat text file with fields separated by commas, and records
+   separated by newlines. (You can also request the data returned in an HTML
+   table, which is useful for debugging.) The first line of the file contains
+   the name of each field that will be returned in subsequent records.
+
+   The parameters that the query interface accepts are described in the table
+   below.
+
+  Required Parameters
+
+   +------------------------------------------------------------------------+
+   | Parameter Name | Requred? |                Description                 |
+   |----------------+----------+--------------------------------------------|
+   | custid         |    X     | TrustCommerce customer ID number.          |
+   |----------------+----------+--------------------------------------------|
+   | password       |    X     | The password for your custID.              |
+   |----------------+----------+--------------------------------------------|
+   |                |          | Set to "html" for human-readable HTML      |
+   | format         |          | output, or "text" (default) for CSV text   |
+   |                |          | output.                                    |
+   |----------------+----------+--------------------------------------------|
+   |                |          | Possible values are: chain, transaction,   |
+   |                |          | summary, or billingid, corresponding to    |
+   | querytype      |    X     | the equivalent reports on the Vault        |
+   |                |          | website. Read the User's Guide for further |
+   |                |          | description of each report type.           |
+   |----------------+----------+--------------------------------------------|
+   | media          |          | Set to "cc" (default) or "ach" for media   |
+   |                |          | type.                                      |
+   |----------------+----------+--------------------------------------------|
+   | begindate      |          | Begin date for query, format: MM-DD-YYYY   |
+   |                |          | HH:MM:SS                                   |
+   |----------------+----------+--------------------------------------------|
+   | enddate        |          | End date for query, format: MM-DD-YYYY     |
+   |                |          | HH:MM:SS                                   |
+   |----------------+----------+--------------------------------------------|
+   | chain          |          | Narrow search to a single chain of         |
+   |                |          | transactions.                              |
+   |----------------+----------+--------------------------------------------|
+   | transid        |          | Narrow search to a single transaction ID.  |
+   |----------------+----------+--------------------------------------------|
+   | billingid      |          | Narrow search to a single billing ID.      |
+   |----------------+----------+--------------------------------------------|
+   | action         |          | Narrow search by action (preauth, sale,    |
+   |                |          | credit, etc).                              |
+   |----------------+----------+--------------------------------------------|
+   | status         |          | Narrow search by status (approved,         |
+   |                |          | accepted, decline, etc).                   |
+   |----------------+----------+--------------------------------------------|
+   | name           |          | Narrow search by cardholder name, partial  |
+   |                |          | or complete.                               |
+   |----------------+----------+--------------------------------------------|
+   | cc             |          | Narrow search by credit card number.       |
+   |----------------+----------+--------------------------------------------|
+   | limit          |          | Do not allow size of result set to exceed  |
+   |                |          | this number of records.                    |
+   |----------------+----------+--------------------------------------------|
+   |                |          | Report result set starting from this       |
+   | offset         |          | offset. Use this parameter in conjunction  |
+   |                |          | with limit in order to page through a      |
+   |                |          | large result set.                          |
+   |----------------+----------+--------------------------------------------|
+   | showcount      |          | Show the number of records returned on the |
+   |                |          | last line of the result set.               |
+   +------------------------------------------------------------------------+
+
+   The sample HTML code shown below illustrates the functionality of the
+   query API. It can be pasted into a file and loaded on your web browser in
+   order to try out some queries before you even begin to write your code.
+
+  Query Example HTML
+
+ <html>
+ <head> <title> TrustCommerce Query Interface </title> </head>
+ <body>
+ <h2> TrustCommerce Query Interface </h2>
+ <form action=https://vault.trustcommerce.com/query/>
+         <table align=center border=1>
+         <tr>
+                 <td> custid </td>
+                 <td> <input type=text name=custid> </td>
+                 <td> This is your TrustCommerce custid (required) </td>
+         </tr>
+         <tr>
+                 <td> password </td>
+                 <td> <input type=password name=password> </td>
+                 <td> This is your TrustCommerce password (required) </td>
+         </tr>
+         <tr>
+                 <td> format </td>
+                 <td> <select name=output> <option value=text>text</option>
+                                 <option value=html>html</option></select></td>
+                 <td> Human readable (html) or computer readable (text) results</td>
+         </tr>
+         <tr>
+                 <td> Query type </td>
+                 <td> <select name=querytype>
+                 <option value=chain>chain</option>
+                 <option value=transaction>transaction</option>
+                 <option value=summary>summary</option>
+                 <option value=billingid>billingid</option>
+                 </select></td>
+                 <td> Type of query </td>
+         </tr>
+         <tr>
+                 <td> media </td>
+                 <td> <input type=text name=media value=cc> </td>
+                 <td> For now this must be cc </td>
+         </tr>
+         <tr>
+                 <td> begindate MM-DD-YYYY HH:MM:SS </td>
+                 <td> <input type=text name=begindate> </td>
+                 <td> Query begins at this date</td>
+         </tr>
+         <tr>
+                 <td> enddate MM-DD-YYYY HH:MM:SS </td>
+                 <td> <input type=text name=enddate> </td>
+                 <td> Query ends at this date</td>
+         </tr>
+         <tr>
+                 <td> chain </td>
+                 <td> <input type=text name=chain> </td>
+                 <td> Narrow search to a single chain of transactions </td>
+         </tr>
+         <tr>
+                 <td> transid </td>
+                 <td> <input type=text name=transid> </td>
+                 <td> Narrow search to a single transactions </td>
+         </tr>
+         <tr>
+                 <td> billingid </td>
+                 <td> <input type=text name=transid> </td>
+                 <td> Narrow search to a single billingid </td>
+         </tr>
+         <tr>
+                 <td> action </td>
+                 <td> <input type=text name=action> </td>
+                 <td> Narrow search by action. (example: preauth,postauth) </td>
+         </tr>
+         <tr>
+                 <td> status </td>
+                 <td> <input type=text name=status> </td>
+                 <td> Narrow search by status. (example: approved,accepted) </td>
+         </tr>
+         <tr>
+                 <td> name </td>
+                 <td> <input type=text name=name> </td>
+                 <td> Narrow search by name. </td>
+         </tr>
+         <tr>
+                 <td> cc </td>
+                 <td> <input type=text name=cc> </td>
+                 <td> Narrow search by credit card field. </td>
+         </tr>
+         <tr>
+                 <td> limit </td>
+                 <td> <input type=text name=limit value=20> </td>
+                 <td> Limit results to this number of fields (not used for summary)</td>
+         </tr>
+         <tr>
+                 <td> offset </td>
+                 <td> <input type=text name=offset value=0> </td>
+                 <td> Report results at this offset (used with limit to page through results)</td>
+         </tr>
+         <tr>
+                 <td> showcount </td>
+                 <td> <select name=showcount>
+                 <option value=y>yes</option>
+                 <option value=n>no</option>
+                 </select></td>
+                 <td> Show the number of not-limited rows on the last line of the result</td>
+         </tr>
+         <tr>
+                 <td colspan=3> <input type=submit> </td>
+         </tr>
+         </table>
+ </form>
+ </body>
+ </html>
+
+Appendix A - Test Data
+
+   While testing, you may wish to experiment with the different responses
+   that the gateway can generate. The following test card numbers will
+   produce an approval, and have address data as listed, for testing AVS. If
+   you wish to test CVV, the code listed int he right-hand column is the
+   correct CVV code, Other valid credit cards will work, but will produce a
+   'U' AVS code. All of these cards accept "0404" as the expiration date.
+
+  TCLink Function Names
+
+   +------------------------------------------------------------------------+
+   |   Card Number    |  Exp  | Address  |   City    | State |  Zip  | CVV  |
+   |------------------+-------+----------+-----------+-------+-------+------|
+   | 4111111111111111 | 04/04 | 123 Test | Somewhere | CA    | 90001 | 123  |
+   |                  |       | St.      |           |       |       |      |
+   |------------------+-------+----------+-----------+-------+-------+------|
+   | 5411111111111115 | 04/04 | 4000     | Anytown   | AZ    | 85001 | 777  |
+   |                  |       | Main St. |           |       |       |      |
+   |------------------+-------+----------+-----------+-------+-------+------|
+   |                  |       | 6789     |           |       |       |      |
+   | 6011111111111117 | 04/04 | Green    | Nowhere   | MA    | 12345 | 606  |
+   |                  |       | Ave.     |           |       |       |      |
+   |------------------+-------+----------+-----------+-------+-------+------|
+   |                  |       | 12       |           |       |       |      |
+   | 341111111111111  | 04/04 | Colorado | Elsewhere | IL    | 54321 | 4000 |
+   |                  |       | Blvd.    |           |       |       |      |
+   +------------------------------------------------------------------------+
+
+   The following card numbers will generate a decline, with the declinetype
+   listed as follows. You may use this to test code which takes different
+   paths dependant upon the type of decline.
+
+  TCLink Function Names
+
+                   +----------------------------------------+
+                   |   Card Number    |  Exp  | DeclineType |
+                   |------------------+-------+-------------|
+                   | 4012345678909    | 04/04 | decline     |
+                   |------------------+-------+-------------|
+                   | 5555444433332226 | 04/04 | call        |
+                   |------------------+-------+-------------|
+                   | 4444111144441111 | 04/04 | carderror   |
+                   +----------------------------------------+
+
+   You should also test your code to make sure it properly handles all
+   baddata and error cases as listed in section X. Simply pass bad values in
+   order to generate these situations.
+
+Appendix B - Troubleshooting
+
+   Details about installing and troubleshooting TCLink specific to your
+   development platform can be found in the documentation included with the
+   TCLink archive.
+
+   Once you are able to connect to the TC gateway, you should be able to
+   diagnose parameter-related issues using the status, error, declinetype,
+   and errortype parameters returned by the gateway. There is one response
+   which indicates a more generic error, and that's an error of cantconnect.
+   First, check the computer's network connection; can you ping machines on
+   the Internet, by IP or by name?
+
+   The most common network connectivity error is that your target computer
+   may be behind a firewall. TCLink uses the HTTPS port (443/tcp) for network
+   communications; you can check whether this port is open from the target
+   machine by typing "telnet vault.trustcommerce.com 443" at a UNIX command
+   prompt, or else by loading a web browser on the target machine and
+   attempting to visit https://vault.trustcommerce.com directly. If you
+   timeout attempting to make the connection, but your Internet connection is
+   working otherwise, then you may be firewalled. Speak to your network
+   administrator about allowing outbound TCP traffic on port 443.
+
+   Another common problem is the lack of domain name (DNS) resolution. In
+   some cases this will result in an errortype dnsfailure. (Not always; the
+   TCLink software will sometimes fall back to hardcoded IP addresses for
+   established accounts. But this method is insecure and error-prone, and is
+   used only as a last resort to keep a system with temporary DNS issues up
+   and running during the outage.) The target machine must be able to resolve
+   the trustcommerce.com domain; try typing "host trustcommerce.com" from a
+   UNIX command prompt. If you don't get a response, or get an error, then
+   the machine cannot resolve DNS information and TCLink will not be able to
+   connect to the TC gateway. Speak to your sysadmin about making domain name
+   resolution available to your target host.
+
+Appendix C - Connecting via HTTPS POST
+
+   This method should only be used if a TCLink client install is not an
+   option. It does not have the failover capability (and thus the processing
+   uptime is not guaranteed to be 100%), or some of the enhanced security
+   features of TCLink. In addition, transactions may be slightly slower, by
+   an extra half second or so. It does, however support all other features
+   available through TCLink, including all parameters and transaction types.
+
+   This is the URL:
+
+   https://vault.trustcommerce.com/trans/
+
+   The transaction should be sent as a standard POST, with CGI parameters,
+   URL encoded. The parameters are otherwise identical to those used through
+   TCLink.
+
+   Response parameters are returned as name-value pairs separated by
+   newlines.
+
+Appendix D - Currency Table
+
+  Currency Codes
+
+   +-----------------------------------------------------------------------+
+   | Code |       Currency Type       | Code |        Currency Type        |
+   |------+---------------------------+------+-----------------------------|
+   | usd  | US Dollars                | jpy  | Japan Yen                   |
+   |------+---------------------------+------+-----------------------------|
+   | eur  | Euro                      | jod  | Jordan Dinar                |
+   |------+---------------------------+------+-----------------------------|
+   | cad  | Canadian Dollars          | krw  | Korea (South) Won           |
+   |------+---------------------------+------+-----------------------------|
+   | gbp  | UK Pounds                 | lbp  | Lebanon Pounds              |
+   |------+---------------------------+------+-----------------------------|
+   | dem  | German Deutschemarks      | luf  | Luxembourg Francs           |
+   |------+---------------------------+------+-----------------------------|
+   | frf  | French Francs             | myr  | Malaysia Ringgit            |
+   |------+---------------------------+------+-----------------------------|
+   | jpy  | Japanese Yen              | mxp  | Mexico Pesos                |
+   |------+---------------------------+------+-----------------------------|
+   | nlg  | Dutch Guilders            | nlg  | Netherlands Guilders        |
+   |------+---------------------------+------+-----------------------------|
+   | itl  | Italian Lira              | nzd  | New Zealand Dollars         |
+   |------+---------------------------+------+-----------------------------|
+   | chf  | Switzerland Francs        | nok  | Norway Kroner               |
+   |------+---------------------------+------+-----------------------------|
+   | dzd  | Algeria Dinars            | pkr  | Pakistan Rupees             |
+   |------+---------------------------+------+-----------------------------|
+   | arp  | Argentina Pesos           | xpd  | Palladium Ounces            |
+   |------+---------------------------+------+-----------------------------|
+   | aud  | Australia Dollars         | php  | Philippines Pesos           |
+   |------+---------------------------+------+-----------------------------|
+   | ats  | Austria Schillings        | xpt  | Platinum Ounces             |
+   |------+---------------------------+------+-----------------------------|
+   | bsd  | Bahamas Dollars           | plz  | Poland Zloty                |
+   |------+---------------------------+------+-----------------------------|
+   | bbd  | Barbados Dollars          | pte  | Portugal Escudo             |
+   |------+---------------------------+------+-----------------------------|
+   | bef  | Belgium Francs            | rol  | Romania Leu                 |
+   |------+---------------------------+------+-----------------------------|
+   | bmd  | Bermuda Dollars           | rur  | Russia Rubles               |
+   |------+---------------------------+------+-----------------------------|
+   | brr  | Brazil Real               | sar  | Saudi Arabia Riyal          |
+   |------+---------------------------+------+-----------------------------|
+   | bgl  | Bulgaria Lev              | xag  | Silver Ounces               |
+   |------+---------------------------+------+-----------------------------|
+   | cad  | Canada Dollars            | sgd  | Singapore Dollars           |
+   |------+---------------------------+------+-----------------------------|
+   | clp  | Chile Pesos               | skk  | Slovakia Koruna             |
+   |------+---------------------------+------+-----------------------------|
+   | cny  | China Yuan Renmimbi       | zar  | South Africa Rand           |
+   |------+---------------------------+------+-----------------------------|
+   | cyp  | Cyprus Pounds             | krw  | South Korea Won             |
+   |------+---------------------------+------+-----------------------------|
+   | csk  | Czech Republic Koruna     | esp  | Spain Pesetas               |
+   |------+---------------------------+------+-----------------------------|
+   | dkk  | Denmark Kroner            | xdr  | Special Drawing Right (IMF) |
+   |------+---------------------------+------+-----------------------------|
+   | nlg  | Dutch Guilders            | sdd  | Sudan Dinar                 |
+   |------+---------------------------+------+-----------------------------|
+   | xcd  | Eastern Caribbean Dollars | sek  | Sweden Krona                |
+   |------+---------------------------+------+-----------------------------|
+   | egp  | Egypt Pounds              | chf  | Switzerland Francs          |
+   |------+---------------------------+------+-----------------------------|
+   | eur  | Euro                      | twd  | Taiwan Dollars              |
+   |------+---------------------------+------+-----------------------------|
+   | fjd  | Fiji Dollars              | thb  | Thailand Baht               |
+   |------+---------------------------+------+-----------------------------|
+   | fim  | Finland Markka            | ttd  | Trinidad and Tobago Dollars |
+   |------+---------------------------+------+-----------------------------|
+   | frf  | France Francs             | trl  | Turkey Lira                 |
+   |------+---------------------------+------+-----------------------------|
+   | dem  | Germany Deutsche Marks    | gbp  | United Kingdom Pounds       |
+   |------+---------------------------+------+-----------------------------|
+   | xau  | Gold Ounces               | usd  | United States Dollars       |
+   |------+---------------------------+------+-----------------------------|
+   | grd  | Greece Drachmas           | veb  | Venezuela Bolivar           |
+   |------+---------------------------+------+-----------------------------|
+   | hkd  | Hong Kong Dollars         | zmk  | Zambia Kwacha               |
+   |------+---------------------------+------+-----------------------------|
+   | huf  | Hungary Forint            | eur  | Euro                        |
+   |------+---------------------------+------+-----------------------------|
+   | isk  | Iceland Krona             | xcd  | Eastern Caribbean Dollars   |
+   |------+---------------------------+------+-----------------------------|
+   | inr  | India Rupees              | xdr  | Special Drawing Right (IMF) |
+   |------+---------------------------+------+-----------------------------|
+   | idr  | Indonesia Rupiah          | xag  | Silver Ounces               |
+   |------+---------------------------+------+-----------------------------|
+   | iep  | Ireland Punt              | xau  | Gold Ounces                 |
+   |------+---------------------------+------+-----------------------------|
+   | ils  | Israel New Shekels        | xpd  | Palladium Ounces            |
+   |------+---------------------------+------+-----------------------------|
+   | itl  | Italy Lira                | xpt  | Platinum Ounces             |
+   |------+---------------------------+------+-----------------------------|
+   | jmd  | Jamaica Dollars           |      |                             |
+   +-----------------------------------------------------------------------+
+
+     ----------------------------------------------------------------------
+
+                        Copyright (c) 2002 TrustCommerce
diff --git a/ext/tclink/php_tclink.c b/ext/tclink/php_tclink.c
new file mode 100644 (file)
index 0000000..12c001d
--- /dev/null
@@ -0,0 +1,123 @@
+/*
+ * TCLink PHP Module
+ *
+ * TCLink Copyright (c) 2002 TrustCommerce.
+ * http://www.trustcommerce.com
+ * developer@trustcommerce.com
+ * (626) 744-7700
+ */
+
+#include "php.h"
+#include "php_config.h"
+#include "php_tclink.h"
+
+function_entry php_tclink_functions[] = {
+       PHP_FE(tclink_send, NULL)
+       PHP_FE(tclink_getversion, NULL)
+       {NULL, NULL, NULL}
+};
+
+zend_module_entry php_tclink_module_entry = {
+#ifdef STANDARD_MODULE_HEADER
+       STANDARD_MODULE_HEADER,
+#endif
+       "tclink", php_tclink_functions, NULL, NULL, NULL, NULL, PHP_MINFO(tclink), STANDARD_MODULE_PROPERTIES
+};
+
+#define PHP_TCLINK_DEFAULT_BUFFER_SIZE 8196
+
+#ifdef COMPILE_DL_TCLINK
+ZEND_GET_MODULE(php_tclink)
+
+PHP_MINFO_FUNCTION(tclink)
+{
+       char *tmp = (char *)malloc(1024);
+       php_info_print_table_start();
+       if(tmp == NULL) {
+               php_info_print_table_row(2, "TCLink PHP Module", "enabled");
+       } else {
+               php_info_print_table_row(2, "TCLink PHP Module", TCLinkGetVersion(tmp));
+               free(tmp);
+       }
+       php_info_print_table_end();
+}
+
+/* {{{ proto void tclink_send(array params)
+   Send the transaction in for processing. */
+PHP_FUNCTION(tclink_send)
+{
+       pval **params, **zvalue;
+       HashTable *hash;
+       char *key, *value, *next_key;
+
+       TCLinkHandle h;
+       char buf[4096];
+
+       /* check parameters */
+       if((ZEND_NUM_ARGS() != 1) ||
+          (zend_get_parameters_ex(1, &params) == FAILURE)) {
+               WRONG_PARAM_COUNT;
+       }
+
+       convert_to_array_ex(params);
+
+       h = TCLinkCreate();
+
+       /* grab the hash and stuff each parameter set into TCLink */
+       hash = HASH_OF(*params);
+       zend_hash_internal_pointer_reset(hash);
+       while (zend_hash_get_current_data(hash, (void **)&zvalue) == SUCCESS)
+       {
+               /* The Zend API added an extra parameter between 4.04 (sometime in
+                * 1999) and 4.06 (in early 2001).  Assume that anything prior to
+                * 1/1/2001 is the older version. */
+#if PHP_API_VERSION < 20000101
+               zend_hash_get_current_key(hash, &key, NULL);
+#else
+               zend_hash_get_current_key(hash, &key, NULL, 0);
+#endif
+               convert_to_string_ex(zvalue);
+               value = Z_STRVAL_PP(zvalue);
+               TCLinkPushParam(h, key, value);
+               zend_hash_move_forward(hash);
+       }
+
+       /* send the transaction */
+       TCLinkSend(h);
+
+       /* pull out the parameters and put them in a hash */
+       TCLinkGetEntireResponse(h, buf, sizeof(buf));
+
+       array_init(return_value);
+
+       key = value = buf;
+       while (key && (value = strchr(key, '=')))
+       {
+               *value++ = 0;
+               next_key = strchr(value, '\n');
+               if (next_key) *next_key++ = 0;
+
+               add_assoc_string(return_value, key, value, 1);
+
+               key = next_key;
+       }
+
+       TCLinkDestroy(h);
+
+       /* return_value is returned automatically, we need not explictly call a
+          return macro */
+}
+/* }}} */
+
+/* {{{ proto string tclink_getversion()
+       returns the API version information */
+PHP_FUNCTION(tclink_getversion)
+{
+       char version[1024];
+
+       TCLinkGetVersion(version);
+       RETURN_STRING(version, 1);
+}
+/* }}} */
+
+#endif
diff --git a/ext/tclink/php_tclink.h b/ext/tclink/php_tclink.h
new file mode 100644 (file)
index 0000000..33bedaf
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ * TCLink PHP Module
+ *
+ * TCLink Copyright (c) 2002 TrustCommerce.
+ * http://www.trustcommerce.com
+ * developer@trustcommerce.com
+ * (626) 744-7700
+ */
+
+#ifndef PHP_TCLINK_H
+#define PHP_TCLINK_H
+
+/* Handle passed to all TCLink functions.  A unique handle must be created
+ * for each concurrent thread, but the same handle can be shared by transactions
+ * occurring one after another (such as a for loop).
+ */
+#define TCLinkHandle void *
+
+/* Parameter names and values cannot exceed this size.
+ */
+#define PARAM_MAX_LEN 256
+
+/* Create a new TCLinkHandle.
+ */
+TCLinkHandle TCLinkCreate();
+
+/* Add a parameter to be sent to the server.
+ */
+void TCLinkPushParam(TCLinkHandle handle, const char *name, const char *value);
+
+/* Flush the parameters to the server.
+ */
+void TCLinkSend(TCLinkHandle handle);
+
+/* Look up a response value from the server.
+ * Returns NULL if no such parameter, or stores the value in 'value' and
+ * returns a pointer to value.  value should be at least PARAM_MAX_LEN in size.
+ */
+char *TCLinkGetResponse(TCLinkHandle handle, const char *name, char *value);
+
+/* Get all response values from the server in one giant string.
+ * Stores the string into buf and returns a pointer to it.  Size should be
+ * sizeof(buf), which will limit the string so that no buffer overruns occur.
+ */
+char *TCLinkGetEntireResponse(TCLinkHandle handle, char *buf, int size);
+
+/* Destory a handle, ending that transaction and freeing the memory associated with it. */
+void TCLinkDestroy(TCLinkHandle handle);
+
+/* Store version string into buf.  Returns a pointer to buf. */
+char *TCLinkGetVersion(char *buf);
+
+#if HAVE_TCLINK
+extern zend_module_entry php_tclink_module_entry;
+#define tclink_module_ptr &php_tclink_module_entry
+
+PHP_MINFO_FUNCTION(tclink);
+
+PHP_FUNCTION(tclink_send);
+PHP_FUNCTION(tclink_getversion);
+
+#else
+#define tclink_module_ptr NULL
+#endif
+
+#define phpext_tclink_ptr tclink_module_ptr
+
+#endif /* PHP_TCLINK_H */
diff --git a/ext/tclink/tcexample.php b/ext/tclink/tcexample.php
new file mode 100644 (file)
index 0000000..7cac0a5
--- /dev/null
@@ -0,0 +1,101 @@
+<?
+       // This example assumes that tclink.so has already been loaded.
+       // Normally this is done by adding "extension=tclink.so" to your
+       // php.ini, but you may also make a manual call to dl("tclink")
+       // as well.  See tctest.php for example code.
+
+       if (!$custid) $custid = "TestMerchant";
+       if (!$password) $password = "password";
+?>
+<html>
+<head><title>TCLink PHP Example</title></head>
+<body bgcolor=white text=black>
+
+       <form method="post" action="<?= $PHP_SELF ?>">
+
+       <table cellspacing=1 cellpadding=3>
+       <tr bgcolor=blue><th colspan=2 align=center>
+               <font color=white>TrustCommerce PHP Example - TCLink ver. <?= tclink_getversion() ?>)</font>
+       </th></tr>
+
+       <tr><th align=right> CustID: </td><td> <input type="text" name="custid" value="<?= $custid ?>"> </td></tr>
+       <tr><th align=right> Password: </td><td> <input type="text" name="password" value="<?= $password ?>"> </td></tr>
+       <tr><th align=right> Action: </td><td> <select name="action">
+               <option value="sale">Sale</option>
+               <option value="preauth">Pre-Authorization</option>
+               <option value="postauth">Post-Authorization</option>
+               <option value="credit">Credit</option>
+       </select> </td></tr>
+       <tr><th align=right> Amount (in cents):</td><td> <input type="text" name="amount"> </td></tr>
+       <tr bgcolor=lightgray><td colspan=2 align=center> Sales and Pre-Authorizations Only: </td></tr>
+       <tr><th align=right> Card Number: </td><td> <input type="text" name="cc" size="16" maxlength="16"> </td></tr>
+       <tr><th align=right> Expiration: </td>
+           <td><select name="mm"><? for ($i = 1; $i <= 12; $i++) { ?><option value="<?=sprintf("%02d", $i);?>"><?=sprintf("%02d", $i);?></option><? } ?></select>
+               <select name="yy"><? for($i = (strftime("%Y")); $i <= (strftime("%Y") + 10); $i++) { ?><option value="<?=substr(sprintf("%04d", $i),2,2);?>"><?=$i;?></option><? } ?></select><br>
+           </td></tr>
+       <tr><th align=right> Cardholder Name: </td><td> <input type="text" name="name"> </td></tr>
+       <tr bgcolor=lightgray><td colspan=2 align=center> Credits and Post-Authorizations Only: </td></tr>
+       <tr><th align=right> Transaction ID: </td><td> <input type="text" name="transid" size="14" maxlength="14"> </td></tr>
+       <tr><td colspan=2 align=center> <input type="submit" name="Action" value="Process"> </td></tr>
+
+       <?
+               if ($Action == 'Process')
+               {
+                       $tclink['custid'] = $custid;
+                       $tclink['password'] = $password;
+                       $tclink['action'] = $action;
+                       if (is_numeric($amount))
+                               $tclink['amount'] = $amount;
+
+                       if ($action == 'sale' || $action == 'preauth')
+                       {
+                               $tclink['name'] = $name;
+                               $tclink['cc'] = $cc;
+                               $tclink['exp'] = $mm . $yy;
+                       }
+                       else if ($action == 'credit' || $action == 'postauth')
+                       {
+                               $tclink['transid'] = $transid;
+                       }
+
+                       $result = tclink_send($tclink);
+
+                       print "<tr><td colspan=2><hr></td></tr>";
+                       print "<tr bgcolor=blue><th colspan=2 align=center><font color=white>Transaction Results:</font></td></tr>";
+
+                       if ($result['transid'])
+                               printf("<tr><th>Transaction ID:</th><td>%s</td></tr>\n", $result['transid']);
+
+                       printf("<tr><th>Status:</td><td>%s</td></tr>\n", $tclink['status']);
+                       switch($tclink['status'])
+                       {
+                               case 'accepted':
+                               case 'approved':
+                                       break;
+
+                               case 'decline':
+                               case 'rejected':
+                                       printf("<tr><th>Decline Type:</th><td>%s</td></tr>\n", $tclink['declinetype']);
+                                       break;
+
+                               case 'error':
+                                       printf("<tr><th>Error Type</th><td>%s</td></tr>\n", $tclink['errortype']);
+                                       break;
+
+                               case 'baddata':
+                                       printf("<tr><th>Offenders:</th><td>%s</td></tr>\n", $tclink['$offenders']);
+                                       break;
+                       }
+
+                       print "<tr bgcolor=lightgray><td colspan=2 align=center>All Results:</td></tr>";
+
+                       while(list($key, $value) = each($result))
+                               printf("<tr><th>%s</th><td>%s</td></tr>\n", $key, $value);
+               }
+       ?>
+
+</table>
+</form>
+
+</body>
+</html>
diff --git a/ext/tclink/tclink.c b/ext/tclink/tclink.c
new file mode 100644 (file)
index 0000000..854e08d
--- /dev/null
@@ -0,0 +1,877 @@
+/* tclink.c - Library code for the TCLink client API.
+ *
+ * TCLink Copyright (c) 2002 TrustCommerce.
+ * http://www.trustcommerce.com
+ * developer@trustcommerce.com
+ * (626) 744-7700
+ */
+
+#include "php_tclink.h"
+
+#include <stdio.h>
+#include <memory.h>
+#include <errno.h>
+#include <string.h>
+#include <strings.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/poll.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <netdb.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <fcntl.h>
+#include <signal.h>
+
+#include <openssl/crypto.h>
+#include <openssl/x509.h>
+#include <openssl/pem.h>
+#include <openssl/ssl.h>
+#include <openssl/err.h>
+#include <openssl/rand.h>
+
+#define DEFAULT_HOST    "gateway.trustcommerce.com"
+#define TIMEOUT         40     /* seconds */
+
+#define TC_BUFF_MAX     16000
+#define TC_LINE_MAX     ((PARAM_MAX_LEN * 2) + 2)
+
+char *tclink_version    = "3.3-PHP";
+char *tclink_host       = DEFAULT_HOST;
+int tclink_port         = 443;
+
+/*************************************************/
+/* Data structures used only within this module. */
+/*************************************************/
+
+/* Variables used for transaction data. */
+
+typedef struct param_data
+{
+       char *name;
+       char *value;
+       struct param_data *next;
+} param;
+
+typedef struct _TCLinkCon
+{
+       /* Connection data */
+       int *ip;
+       int num_ips;
+       int sd;
+
+       /* SSL encryption */
+       X509 *tc_cert;
+       SSL_METHOD *meth;
+       SSL_CTX *ctx;
+       SSL *ssl;
+
+       /* Transaction parameters, sent and received */
+       param *send_param_list, *send_param_tail;
+       param *recv_param_list;
+
+       /* Connection status */
+       int is_error;
+       int pass;
+       time_t start_time;
+       int dns;
+
+} TCLinkCon;
+
+/* The TrustCommerce certificate. */
+unsigned char cert_data[540]={
+0x30,0x82,0x02,0x18,0x30,0x82,0x01,0x81,0x02,0x01,0x02,0x30,0x0D,0x06,0x09,0x2A,
+0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,0x30,0x55,0x31,0x0B,0x30,0x09,
+0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x14,0x30,0x12,0x06,0x03,0x55,
+0x04,0x08,0x13,0x0B,0x4C,0x6F,0x73,0x20,0x41,0x6E,0x67,0x65,0x6C,0x65,0x73,0x31,
+0x17,0x30,0x15,0x06,0x03,0x55,0x04,0x0A,0x13,0x0E,0x54,0x72,0x75,0x73,0x74,0x20,
+0x43,0x6F,0x6D,0x6D,0x65,0x72,0x63,0x65,0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,
+0x03,0x13,0x0E,0x50,0x43,0x41,0x20,0x28,0x31,0x30,0x32,0x34,0x20,0x62,0x69,0x74,
+0x29,0x30,0x1E,0x17,0x0D,0x30,0x30,0x30,0x34,0x32,0x39,0x30,0x35,0x30,0x39,0x30,
+0x34,0x5A,0x17,0x0D,0x30,0x34,0x30,0x34,0x32,0x39,0x30,0x35,0x30,0x39,0x30,0x34,
+0x5A,0x30,0x54,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,
+0x31,0x14,0x30,0x12,0x06,0x03,0x55,0x04,0x08,0x13,0x0B,0x4C,0x6F,0x73,0x20,0x41,
+0x6E,0x67,0x65,0x6C,0x65,0x73,0x31,0x17,0x30,0x15,0x06,0x03,0x55,0x04,0x0A,0x13,
+0x0E,0x54,0x72,0x75,0x73,0x74,0x20,0x43,0x6F,0x6D,0x6D,0x65,0x72,0x63,0x65,0x31,
+0x16,0x30,0x14,0x06,0x03,0x55,0x04,0x03,0x13,0x0D,0x43,0x41,0x20,0x28,0x31,0x30,
+0x32,0x34,0x20,0x62,0x69,0x74,0x29,0x30,0x81,0x9F,0x30,0x0D,0x06,0x09,0x2A,0x86,
+0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x81,0x8D,0x00,0x30,0x81,0x89,
+0x02,0x81,0x81,0x00,0xBD,0x7C,0x7B,0x6F,0x77,0x46,0xE3,0x0F,0xF8,0x50,0x89,0x06,
+0xFC,0x54,0x5A,0x59,0x30,0x55,0xC6,0x00,0x34,0x6F,0x6B,0x64,0x8E,0x11,0x3C,0xDD,
+0xA9,0x0D,0xC5,0xE1,0x1C,0x49,0xF7,0x0A,0x6B,0x3E,0xAA,0x98,0xA4,0xA2,0x8D,0xEF,
+0x9A,0xCB,0xA2,0x40,0x87,0x3B,0x4B,0x13,0x73,0xE6,0x6C,0x39,0x1C,0x48,0xBE,0x6C,
+0x1C,0x78,0x0F,0x8E,0x40,0x27,0xAD,0x61,0x0E,0x5E,0x1F,0x94,0xD7,0xAB,0x61,0x3C,
+0xB1,0xF4,0xC9,0xE2,0x0D,0x05,0x83,0xE8,0x75,0xAB,0x64,0x12,0x39,0xAB,0xEF,0x79,
+0x53,0x49,0x48,0xA0,0x9C,0x55,0xD2,0xE3,0xD0,0x25,0x94,0x78,0x69,0x03,0x95,0xBA,
+0x68,0xC6,0x35,0xFB,0x54,0x3D,0x05,0x6D,0xAD,0x50,0x5F,0xE7,0x63,0xB9,0x4A,0x28,
+0xB0,0xB3,0xE2,0x07,0x02,0x03,0x01,0x00,0x01,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,
+0x86,0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,0x03,0x81,0x81,0x00,0x34,0xED,0xF6,0x9D,
+0x32,0x51,0xCA,0x22,0xD6,0x8C,0x81,0x6F,0x64,0x41,0x7D,0xC0,0xD8,0x66,0xB7,0x2C,
+0x65,0x54,0x8A,0xE4,0x21,0x6A,0xF2,0x0F,0x3F,0xD0,0x85,0xDC,0x15,0xC1,0x5C,0x72,
+0x9A,0x0F,0x00,0x8D,0x38,0x59,0x70,0x7A,0x9C,0x40,0xA6,0x9A,0x2D,0x0E,0xA0,0x31,
+0x61,0x2E,0xA2,0x77,0x11,0xBB,0x20,0xF8,0xF9,0x28,0x10,0x1E,0x12,0xB1,0x9D,0x29,
+0xF7,0x86,0x12,0x05,0x83,0x83,0xE3,0xC3,0x82,0x65,0x97,0xE9,0xC2,0x5B,0x09,0x11,
+0x1D,0xF1,0x01,0x37,0x20,0x2E,0xC5,0x69,0x9C,0xED,0xE3,0xC1,0x29,0x1B,0x3D,0x47,
+0x72,0xED,0xA1,0x7B,0xE4,0x8B,0x2B,0x18,0x39,0xEA,0xDE,0x54,0x69,0xE7,0x35,0xDB,
+0x8F,0xFB,0x34,0xC7,0xF7,0xB3,0x6A,0x9A,0xE5,0x27,0xA4,0x0F};
+
+
+/*************************************
+ * Internal functions, not exported. *
+ *************************************/
+
+/* Random number from min to max. */
+static int number(int min, int max)
+{
+       return (rand() % (max - min + 1)) + min;
+}
+
+/* Safe string copy and append functions. */
+#define SAFE_COPY(d, s)    safe_copy((d), (s), sizeof(d));
+#define SAFE_APPEND(d, s)  safe_append((d), (s), sizeof(d));
+
+void safe_copy(char *dst, const char *src, int size)
+{
+  int len = strlen(src);
+  if (len < size)
+    strcpy(dst, src);
+  else {
+    strncpy(dst, src, size - 1);
+    dst[size-1] = 0;
+  }
+}
+
+void safe_append(char *dst, const char *src, int size)
+{
+  int dlen = strlen(dst);
+  int slen = strlen(src);
+       int avail = size - dlen;
+       if (avail < 1)
+               return;
+
+  if (slen < avail)
+    strcpy(dst+dlen, src);
+  else {
+    strncpy(dst+dlen, src, avail - 1);
+    dst[size-1] = 0;
+  }
+}
+
+/* Add a parameter-value pair to the recieved list. */
+static void AddRecvParam(TCLinkCon *c, const char *name, const char *value)
+{
+       param *p;
+
+       if (name[0] == 0 || value[0] == 0)
+               return;
+
+       p = (param *)malloc(sizeof(param));
+       p->name = strdup(name);
+       p->value = strdup(value);
+       p->next = c->recv_param_list;
+       c->recv_param_list = p;
+}
+
+/* Add a string to the received list. */
+static int AddRecvString(TCLinkCon *c, char *string)
+{
+       char *ptr = strchr(string, '=');
+       if (ptr == NULL)
+               return 0;
+
+       *ptr = 0;
+       AddRecvParam(c, string, ptr+1);
+
+       return 1;
+}
+
+/* Deallocate the send list. */
+static void ClearSendList(TCLinkCon *c)
+{
+       param *p, *next;
+       for (p = c->send_param_list; p; p = next)
+       {
+               next = p->next;
+               free(p->name);
+               free(p->value);
+               free(p);
+       }
+
+       c->send_param_list = c->send_param_tail = NULL;
+}
+
+/* Deallocate the recv list. */
+static void ClearRecvList(TCLinkCon *c)
+{
+       param *p, *next;
+       for (p = c->recv_param_list; p; p = next)
+       {
+               next = p->next;
+               free(p->name);
+               free(p->value);
+               free(p);
+       }
+
+       c->recv_param_list = NULL;
+}
+
+/* Open a socket to the host_ip specified.  Returns the socket's file
+ * descriptor on success (the open attempt is underway) or -1 for failure
+ * (should never happen in practice).  Note that this function DOES NOT block
+ * and wait for the connection; you'll need to select() on the socket later to see
+ * if it opened successfully.
+ */
+static int BeginConnection(TCLinkCon *c, int host_ip)
+{
+       struct sockaddr_in sa;
+       int sd;
+
+       sd = socket(AF_INET, SOCK_STREAM, 0);
+       if (sd < 0)
+               return -1;
+
+       fcntl(sd, F_SETFL, O_NONBLOCK);
+
+       memset(&sa, 0, sizeof(sa));
+       sa.sin_family = AF_INET;
+       sa.sin_addr.s_addr = host_ip;
+       sa.sin_port = htons(tclink_port);
+
+       connect(sd, (struct sockaddr *) &sa, sizeof(sa));
+
+       return sd;
+}
+
+/* This function is called on a socket file descriptor once the connection has been
+ * established and we're ready to negotiate SSL.  If the SSL handshake fails for some
+ * reason (such as the host on the other end not using SSL), it will return 0 for
+ * failure.  Success returns 1.
+ */
+static int FinishConnection(TCLinkCon *c, int sd)
+{
+       int ssl_connected, is_error, errcode, res, n;
+       struct pollfd pfd;
+       X509 *server_cert;
+       time_t start, remaining;
+
+       /* check if socket has connected successfully */
+       int val;
+       int /*socklen_t*/ size = 4;
+       getsockopt(sd, SOL_SOCKET, SO_ERROR, &val, &size);
+       if (val != 0)
+               return 0;
+
+       c->ssl = SSL_new(c->ctx);
+       if (!c->ssl)
+               return 0;
+
+       SSL_set_fd(c->ssl, sd);
+
+       ssl_connected = 0;
+       is_error = 0;
+       start = time(0);
+
+       while (!ssl_connected && !is_error)
+       {
+               remaining = 5 - (time(0) - start);
+               if (remaining <= 0) {
+                       is_error = 1;
+                       break;
+               }
+
+               res = SSL_connect(c->ssl);
+
+               ssl_connected = ((res == 1) && SSL_is_init_finished(c->ssl));
+
+               if (!ssl_connected)
+               {
+                       errcode = SSL_get_error(c->ssl, res);
+                       switch (errcode)
+                       {
+                               case SSL_ERROR_NONE:
+                                       /* no error, we should have a connection, check again */
+                                       break;
+
+                               case SSL_ERROR_WANT_READ:
+                               case SSL_ERROR_WANT_WRITE:
+                                       /* no error, just wait for more data */
+                                       pfd.fd = sd; pfd.events = POLLOUT|POLLIN; pfd.revents = 0;
+                                       while ((n = poll(&pfd, 1, remaining * 1000)) < 0)
+                                               if (errno != EINTR) {
+                                                       is_error = 1;
+                                                       break;
+                                               }
+
+                                       if (!n || !(pfd.revents & (POLLOUT|POLLIN)))
+                                               is_error = 1;
+
+                                       break;
+
+                               case SSL_ERROR_ZERO_RETURN: /* peer closed the connection */
+                               case SSL_ERROR_SSL:         /* error in SSL handshake */
+                               default:
+                                       is_error = 1;
+                       }
+               }
+       }
+
+       if (is_error) {
+               SSL_free(c->ssl);
+               return 0;
+       }
+   
+       fcntl(sd, F_SETFL, 0);           /* make the socket blocking again */
+
+       /* verify that server certificate is authentic */
+       server_cert = SSL_get_peer_certificate(c->ssl);
+       if (!server_cert || (X509_cmp(server_cert, c->tc_cert) != 0)) {
+               SSL_free(c->ssl);
+               return 0;
+       }
+
+       X509_free(server_cert);
+
+       return 1;
+}
+
+/* This function should be called on list of socket file descriptors (sd) to determine
+ * if any have opened successfully.  If so, it will return which one (index into
+ * the array).  Otherwise it returns -1 if none have successfully opened.
+ * This function will block for a maximum of 3 seconds.
+ * As this function calls FinishConnection(), you shouldn't need to do anything special
+ * after it returns success - the socket is set up and ready for use.
+ */
+static int CheckConnection(TCLinkCon *c, int *sd, int num_sd)
+{
+       fd_set wr_set, err_set;
+       struct timeval tv;
+       int max_sd = -1, i;
+
+       tv.tv_sec = 3;        /* wait 3 seconds for soc->mething to happen */
+       tv.tv_usec = 0;
+
+       /* build the fd_sets used for select() */
+       FD_ZERO(&wr_set);
+       FD_ZERO(&err_set);
+       for (i = 0; i < num_sd; i++)
+       {
+               if (sd[i] < 0) continue;
+               FD_SET(sd[i], &wr_set);
+               FD_SET(sd[i], &err_set);
+               if (sd[i] > max_sd)
+                       max_sd = sd[i];
+       }
+
+       /* run the select and see what we have waiting for us */
+       if (select(max_sd + 1, NULL, &wr_set, &err_set, &tv) < 1)
+               return -1;     /* I hope this never happens */
+
+       for (i = 0; i < num_sd; i++)
+               if (sd[i] >= 0)
+               {
+                       if (FD_ISSET(sd[i], &err_set))
+                       {
+                               /* error - close the socket and mark it defunct */
+                               close(sd[i]);
+                               sd[i] = -1;
+                       }
+                       else if (FD_ISSET(sd[i], &wr_set))
+                       {
+                               /* socket has opened! try to negotiate SSL */
+                               if (FinishConnection(c, sd[i])) {
+                                       /* socket is ready to go, so return success */
+                                       c->sd = sd[i];
+                                       return i;
+                               }
+                               else {
+                                       /* SSL handshake had errors, close the socket and mark it defunct */
+                                       close(sd[i]);
+                                       sd[i] = -1;
+                               }
+                       }
+               }
+
+       /* if we get here, nothing much interesting happened during those 3 seconds */
+       return -1;
+}
+
+void do_SSL_randomize()
+{
+       enum { RAND_VALS = 32 };
+       int randbuf[RAND_VALS];
+       char fname[512];
+       int use_rand_file;
+       time_t t;
+       int i, c;
+
+       /* if they have a /dev/urandom we can skip this function */
+       if (RAND_status() != 0)
+               return;
+
+       t = time(0);
+       RAND_seed((char *)&t, sizeof(time_t));
+
+       /* have they specified a random file with RANDFILE environment variable? */
+       use_rand_file = RAND_file_name(fname, sizeof(fname)) ? 1 : 0;
+       if (use_rand_file)
+               RAND_load_file(fname, 4096);
+
+       /* stuff it with packets of random numbers until it is satisfied */
+       for (i = 0; i < 256 && RAND_status() == 0; i++)
+       {
+               for (c = 0; c < RAND_VALS; c++)
+                       randbuf[c] = rand();
+               RAND_seed((char *)randbuf, sizeof(int) * RAND_VALS);
+       }
+}
+
+/* Open a connection to one of the TrustCommerce gateway servers. */
+static int Connect(TCLinkCon *c, int host_hash)
+{
+       struct hostent default_he;
+       char *addr_list[3]; int addr[2];
+       struct hostent *he;
+       unsigned int **gw;
+
+       enum { MAX_HOSTS = 32 };
+       time_t last_connect[MAX_HOSTS];
+       int sd[MAX_HOSTS];
+       int num_sd = 0;
+       int host;
+
+       int i, j, sort, sort_val;
+
+       unsigned char *cert_data_ptr = cert_data;
+
+       c->sd = -1;
+       c->is_error = 0;
+
+       srand(time(0));
+
+       /* These are used as BACKUP ONLY if the DNS if offline. */
+       addr[0] = inet_addr("204.212.133.5");
+       addr[1] = inet_addr("216.34.194.254");
+       addr_list[0] = (char *)&addr[0];
+       addr_list[1] = (char *)&addr[1];
+       addr_list[2] = 0;
+       default_he.h_addr_list = addr_list;
+
+       /* determine IP addresses of gateway */
+       if (!c->ip) 
+       {
+               he = gethostbyname(tclink_host);
+               if (he)
+                       c->dns = 1;
+               else {
+                       /* fall back to hardcoded IPs in an emergency */
+                       c->dns = 0;
+                       he = &default_he;
+               }
+
+               for (c->num_ips = 0; he->h_addr_list[c->num_ips]; c->num_ips++)
+                       ;
+
+               c->ip = (int *)malloc(c->num_ips * sizeof(int));
+               gw = (int unsigned **)he->h_addr_list;
+
+               /* sort the IP address list before storing it */
+               for (i = 0; i < c->num_ips; i++)
+               {
+                       sort = 0; sort_val = *gw[0];
+                       for (j = 1; j < c->num_ips; j++)
+                               if (*gw[j] > sort_val)
+                               {
+                                       sort = j;
+                                       sort_val = *gw[j];
+                               }
+
+                       c->ip[i] = sort_val;
+                       *gw[sort] = 0;
+               }
+       }
+
+       /* do some SSL setup */
+       if (!c->meth)
+       {
+               do_SSL_randomize();        /* handle systems without /dev/urandom */
+               SSLeay_add_ssl_algorithms();
+               c->meth = SSLv3_client_method();
+       }
+
+       if (!c->ctx)
+       {
+               c->ctx = SSL_CTX_new(c->meth);
+               if (!c->ctx) return 0;
+       }
+
+       /* create the valid certificate */
+       if (c->tc_cert == NULL) {
+               c->tc_cert = d2i_X509(NULL, &cert_data_ptr, 540);
+               if (!c->tc_cert) return 0;
+       }
+
+       /* This loop works as follows:
+        * Grab the first host.  Try to open a connection to it.  If there was an
+        * error (host down or unreachable) go to the next one.  If nothing has happened
+        * after 3 seconds, open a second socket (the first one is still open!) and try
+        * with the next fail-over host.  Continue to do this for a maximum of MAX_HOSTS
+        * sockets, or until our TIMEOUT value runs out.  We also keep track of how recently
+        * we tried to connect to a given host, so that we avoid saturating the machines
+        * in a heavy-load situation (which could be caused by anything from heavy internet
+        * lag between the local host and the TrustCommerce servers, to heavy load on the
+        * servers themselves due to half a million people trying to run credit card
+        * transactions in the same half second - unlikely, but certainly possible.)
+        */
+       c->start_time = time(0);
+       c->pass = 1;
+       memset(last_connect, 0, MAX_HOSTS * sizeof(time_t));
+       host = host_hash % c->num_ips;
+
+       for ( ; time(0) < (c->start_time + TIMEOUT); c->pass++)
+       {
+               /* retry the first host at least once */
+               if (c->pass > 2) host += 1;
+               if (host >= c->num_ips) host = 0;
+
+               /* only connect if we haven't tried this host before, or it's been a little
+                * while (note random modifier to help stagger network traffic) */
+               if (last_connect[host] == 0 ||
+                   (time(0) - last_connect[host]) >= number(TIMEOUT / 4, TIMEOUT))
+               {
+                       if (num_sd < MAX_HOSTS)
+                       {
+                               /* fire up a new connection to this host */
+                               if (c->pass != 1)
+                                       last_connect[host] = time(0);
+
+                               sd[num_sd] = BeginConnection(c, c->ip[host]);
+                               if (sd[num_sd] >= 0)
+                                       num_sd++;
+                       }
+
+                       /* scan all current sockets and see if we've made a successful connection
+                        * somewhere.  note that this also includes SSL and all that sort of fun,
+                        * so once it returns success, we're all done. */
+                       if (num_sd > 0)
+                               if (CheckConnection(c, sd, num_sd) >= 0)
+                               {
+                                       /* Success: close all other file handles and return */
+                                       for (i = 0; i < num_sd; i++)
+                                               if (sd[i] >= 0 && sd[i] != c->sd)
+                                                       close(sd[i]);
+
+                                       return 1;
+                               }
+               }
+       }
+
+       return 0;
+}
+
+/* Send a chunk of data through a connection previously opened with Connect(). */
+static int Send(TCLinkCon *c, const char *string)
+{
+       if (SSL_write(c->ssl, string, strlen(string)) < 0)
+               return 0;
+
+       return 1;
+}
+
+/* Peel a line off the current input.  Note that this DOESN'T necessarily wait for all
+ * input to come in, only up to a "\n".  -1 is returned for a network error, otherwise
+ * it returns the length of the line read.  If there is not a complete line pending
+ * for read this will block until there is, or an error occurs.
+ */
+static int ReadLine(TCLinkCon *c, char *buffer, char *destbuf)
+{
+       struct timeval tv;
+       fd_set read;
+       fd_set error;
+
+       while (1)      /* we wait for a line to come in or an error to occur */
+       {
+               char *eol = strchr(buffer, '\n');
+               if (eol != NULL)
+               {
+                       /* peel off the line and return it */
+                       *eol++ = 0;
+                       safe_copy(destbuf, buffer, TC_LINE_MAX);
+                       memmove(buffer, eol, strlen(eol)+1);
+                       return strlen(destbuf);
+               }
+               else
+               {
+                       if (c->is_error == 1)
+                               return -1;
+
+                       /* do socket work to grab the most recent chunk of incoming data */
+                       FD_ZERO(&read);   FD_SET(c->sd, &read);
+                       FD_ZERO(&error);  FD_SET(c->sd, &error);
+                       tv.tv_sec = TIMEOUT;
+                       tv.tv_usec = 0;
+
+                       if (select(c->sd + 1, &read, NULL, &error, &tv) < 1)
+                               c->is_error = 1;
+                       else if (FD_ISSET(c->sd, &error))
+                               c->is_error = 1;
+                       else if (FD_ISSET(c->sd, &read))
+                       {
+                               int buffer_end = strlen(buffer);
+                               int size = SSL_read(c->ssl, buffer + buffer_end, TC_BUFF_MAX-1 - buffer_end);
+                               if (size < 0)
+                                       c->is_error = 1;
+                               else
+                                       buffer[buffer_end + size] = 0;
+                       }
+               }
+       }
+}
+
+/* Closes a connection opened with Connect() and frees memory associated with it.
+ * You ONLY need to Close() connections which opened successfully; those that don't
+ * clean up after themselves before Connect() returns.
+ */
+static int Close(TCLinkCon *c)
+{
+       if (c->ssl) SSL_shutdown(c->ssl);
+
+       if (c->sd >= 0) {
+               close(c->sd);
+               c->sd = -1;
+       }
+
+       if (c->ssl) {
+               SSL_free(c->ssl);
+               c->ssl = NULL;
+       }
+
+       if (c->ctx) {
+               SSL_CTX_free(c->ctx);
+               c->ctx = NULL;
+       }
+
+       /* We DON'T free c->meth or c->tc_cert here, because they can be *
+        * reused by other transactions run on this same TCLinkHandle.   */
+
+       return 1;
+}
+
+/**********************************************
+ * API functions exported to the user client. *
+ **********************************************/
+
+TCLinkHandle TCLinkCreate()
+{
+       TCLinkCon *c = (TCLinkCon *)malloc(sizeof(TCLinkCon));
+
+       c->ip = NULL;
+       c->num_ips = 0;
+       c->sd = -1;
+
+       c->tc_cert = NULL;
+       c->meth = NULL;
+       c->ctx = NULL;
+       c->ssl = NULL;
+
+       c->send_param_list = NULL;
+       c->send_param_tail = NULL;
+       c->recv_param_list = NULL;
+
+       c->is_error = 0;
+       c->pass = 0;
+       c->start_time = 0;
+       c->dns = -1;
+
+       return (TCLinkHandle)c;
+}
+
+void TCLinkPushParam(TCLinkHandle handle, const char *name, const char *value)
+{
+       param *p;
+       char *ch;
+
+       TCLinkCon *c = (TCLinkCon *)handle;
+
+       if (name && value)
+       {
+               p = (param *)malloc(sizeof(param));
+               p->name = strdup(name);
+               p->value = strdup(value);
+               p->next = NULL;
+               if (c->send_param_tail)
+                       c->send_param_tail->next = p;
+               else
+                       c->send_param_list = p;
+               c->send_param_tail = p;
+
+               /* remove newlines and equals signs from the parameter name */
+               for (ch = p->name; *ch; ch++)
+                       if (*ch == '=' || *ch == '\n') *ch = ' ';
+
+               /* remove newlines from the value */
+               for (ch = p->value; *ch; ch++)
+                       if (*ch == '\n') *ch = ' ';
+       }
+}
+
+void TCLinkSend(TCLinkHandle handle)
+{
+       param *p, *next;
+       char buf[TC_BUFF_MAX], destbuf[TC_LINE_MAX];
+       char buf2[1024];
+       int host_hash = 1;
+       int retval = 0;
+
+       TCLinkCon *c = (TCLinkCon *)handle;
+
+       ClearRecvList(c);
+
+       /* build most of the string we will send to the processor */
+       sprintf(buf, "BEGIN\nversion=%s\n", tclink_version);
+
+       for (p = c->send_param_list; p; p = next)
+       {
+               next = p->next;
+               SAFE_COPY(buf2, p->name);
+               SAFE_APPEND(buf2, "=");
+               SAFE_APPEND(buf2, p->value);
+               SAFE_APPEND(buf2, "\n");
+               SAFE_APPEND(buf, buf2);
+               if (!strcasecmp(p->name, "custid")) {
+                       host_hash = atoi(p->value);
+                       host_hash = (host_hash / 100) + (host_hash % 100);
+               }
+               free(p->name);
+               free(p->value);
+               free(p);
+       }
+
+       c->send_param_list = c->send_param_tail = NULL;
+
+       /* try to make the connection */
+       if (!Connect(c, host_hash))
+       {
+               Close(c);  // clean up any memory Connect() may have left lying around
+               AddRecvParam(c, "status", "error");
+               AddRecvParam(c, "errortype", "cantconnect");
+               return;
+       }
+
+       /* append some data about the connection */
+       sprintf(buf+strlen(buf), "pass=%d\ntime=%ld\n", c->pass, time(0) - c->start_time);
+       if (c->dns != 1) SAFE_APPEND(buf, "dns=n\n");
+       SAFE_APPEND(buf, "END\n");
+
+       /* send the data */
+       if (Send(c, buf))
+       {
+               int state = 0;
+               buf[0] = destbuf[0] = 0;          /* recycle buf */
+               c->is_error = 0;
+               while (1)
+               {
+                       int len = ReadLine(c, buf, destbuf);
+                       if (len == 0) continue;
+                       if (len < 0) break;
+                       if (strcasecmp(destbuf, "BEGIN") == 0)
+                       {
+                               if (state != 0)
+                                       { state = -1; break; }
+                               state = 1;
+                       }
+                       else if (strcasecmp(destbuf, "END") == 0)
+                       {
+                               if (state != 1)
+                                       state = -1;
+                               else
+                                       state = 2;
+                               break;
+                       }
+                       else
+                       {
+                               if (state != 1 || !AddRecvString(c, destbuf))
+                                       { state = -1; break; }
+                       }
+               }
+               if (state == 2)
+                       retval = 1;
+       }
+
+       Close(c);
+
+       if (!retval)
+       {
+               ClearRecvList(c);
+               AddRecvParam(c, "status", "error");
+               AddRecvParam(c, "errortype", "linkfailure");
+       }
+}
+char *TCLinkGetResponse(TCLinkHandle handle, const char *name, char *value)
+{
+       param *p;
+       TCLinkCon *c = (TCLinkCon *)handle;
+
+       for (p = c->recv_param_list; p; p = p->next)
+               if (strcasecmp(name, p->name) == 0)
+               {
+                       safe_copy(value, p->value, PARAM_MAX_LEN);
+                       return value;
+               }
+
+       return NULL;
+}
+
+static void stuff_string(char *buf, int *len, int size, const char *add)
+{
+       int newlen = strlen(add);
+       if ((*len + newlen) >= size)
+               newlen = size - *len - 1;
+       if (newlen < 1) return;
+       strncpy(buf + *len, add, newlen);
+       *len += newlen;
+       buf[*len] = 0;
+}
+
+char *TCLinkGetEntireResponse(TCLinkHandle handle, char *buf, int size)
+{
+       param *p;
+       int len = 0;
+       TCLinkCon *c = (TCLinkCon *)handle;
+
+       for (p = c->recv_param_list; p; p = p->next) {
+               stuff_string(buf, &len, size, p->name);
+               stuff_string(buf, &len, size, "=");
+               stuff_string(buf, &len, size, p->value);
+               stuff_string(buf, &len, size, "\n");
+       }
+
+       return buf;
+}
+
+void TCLinkDestroy(TCLinkHandle handle)
+{
+       TCLinkCon *c = (TCLinkCon *)handle;
+       if (!c) return;
+
+       ClearSendList(c);
+       ClearRecvList(c);
+       Close(c);
+
+       if (c->ip)
+               free(c->ip);
+
+       if (c->tc_cert)
+               X509_free(c->tc_cert);
+
+       free(c);
+}
+
+char *TCLinkGetVersion(char *buf)
+{
+       strcpy(buf, tclink_version);
+       return buf;
+}
+
diff --git a/ext/tclink/tctest.php b/ext/tclink/tctest.php
new file mode 100644 (file)
index 0000000..fa947e3
--- /dev/null
@@ -0,0 +1,45 @@
+<?
+       // The ugly bit of code below loads the TCLink extension if it is not
+       // already.  You can skip all of this if "extension=tclink.so" is in
+       // your php.ini, or you can make a single call to dl("tclink") if
+       // tclink.so is in your PHP extensions path ("extension_dir").
+       if (!extension_loaded("tclink"))
+       {
+               $extfname = getcwd() . "/modules/tclink.so";
+               echo "TCLink extension not loaded, attempting to load manually from $extfname...";
+
+               // The excessive "../" bit allows us to back up out of the extension dir
+               // so that we can access the current working directory.  It is only done
+               // this way so that tctest.php may work out of the box on any system, you
+               // can get rid of this if you do a global install of TCLink.
+               $extfname = "../../../../../../../../../../../.." . $extfname;
+               if (!dl($extfname)) {
+                       echo "FAILED!\nAborting this test script, please check to make sure the module is properly built.\n";
+                       exit(1);
+               }
+               echo "success.\n";
+       }
+
+       print "\nTCLink version " . tclink_getversion() . "\n";
+       print "Sending transaction...";
+
+       // Build a hash containing our parameters
+       $params{'custid'} = 'TestMerchant';
+       $params{'password'} = 'password';
+       $params{'action'} = 'sale';
+       $params{'media'} = 'cc';
+       $params{'cc'} = '4111111111111111';
+       $params{'exp'} = '0110';
+       $params{'amount'} = '100';
+       $params{'name'} = 'Joe PHP';
+
+       // Send the hash to TrustCommerce for processing
+       $result = tclink_send($params);
+
+       print "done!\n\nTransaction results:\n";
+
+       // Print out all parameters returned
+       while (list($key, $val) = each($result))
+               print "\t$key=$val\n";
+?>
+