libnet-tclink-perl-3.4.0/0040755000175000017500000000000007726211153014633 5ustar wittenwittenlibnet-tclink-perl-3.4.0/doc/0040755000175000017500000000000007726211153015400 5ustar wittenwittenlibnet-tclink-perl-3.4.0/doc/TCDevGuide.txt0100640000175000017500000027030607726211153020065 0ustar wittenwitten ---------------------------------------------------------------------- TrustCommerce Developer's Guide 2.3 http://www.trustcommerce.com developer@trustcommerce.com March 18, 2003 ---------------------------------------------------------------------- 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. TCS Citadel (Billing IDs) XII. Recurring Billing XIII. TCS Wallet XIV. Purchase Level II (Commercial Cards) XIV. Order Detail XVI. Vault Query API Appendix A - Test Data Appendix B - Troubleshooting Appendix C - Connecting via HTTPS POST Appendix D - Currency Table Appendix E - Input Field List ---------------------------------------------------------------------- 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. | |---------------------+--------------------------------------------------| | Destroy() | Deallocate any memory associated with the | | | transaction handle. | |---------------------+--------------------------------------------------| | 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 | n | 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. | |-----------------+---------------+--------------------------------------| | | | Two-character code for the | | state | | cardholder's state, or the full | | | | region/province for international | | | | addresses. | |-----------------+---------------+--------------------------------------| | | | Cardholder's zipcode, five or nine | | zip | | digits with no spaces or dashes, or | | | | the full postal code for | | | | international addresses. | |-----------------+---------------+--------------------------------------| | 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=y 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. (This parameter is returned even when avs=n, which is the default.) 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. offlineauthcode can only be used with sale transactions. Be warned: offlineauthcode skips the authorization phase altogether, and thus 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. TCS Citadel (Billing IDs) The TCS Citadel 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. The Citadel 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. | +------------------------------------------------------------------------+ You can update information on existing billing IDs by passing the billingid field along with the store transaction. If you wish to erase the data contained in a field, pass the exact string "null" (four characters, all lower case) as the parameter value. 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 between 1 and 99 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.) If there is no start parameter, the first transaction is run immediately (and can cause the store action to return a "decline" or other result you would expect from a sale). Other return parameters associated with auths, such as avs code, will be returned as well. 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. There is only one instance in which the cycle parameter is not required, and that is a one-time future payment. By setting payments to "1" and passing a start date, the payment will be made on that date and then the billing ID unstored. The cycle parameter may be included with a one-time future payment, but it will have no effect. 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 annual payments, and don't start until September 1, 2004 params['cycle'] = '1y'; params['start'] = '2004-09-01'; elif (mode == 5): # Make a one time payment in 45 days params['start'] = '45d'; params['payments'] = '1'; 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. Purchase Level II Purchase Level II is required by some merchant banks to achieve a qualifed discount rate. It is only used for B2B or B2G transactions. If you are selling products directly to consumers, you do not need to use PL2. Additionally, PL2 can only be used if the cardholder is using one of the three types of commercial cards: a corporate card, a business card, or a purchasing card. PL2 has three new parmaeters: PL2 Input Parameters +------------------------------------------------------------------------+ | Parameter Name | Description | |------------------+-----------------------------------------------------| | purchaselevel | Specify as "2". | |------------------+-----------------------------------------------------| | | The purchasing order number from their Visa | | purchaseordernum | purchasing card. This is either a 16 or a 17 digit | | | number. If they are not using a Visa purchasing | | | card, do not pass this field. | |------------------+-----------------------------------------------------| | | The amount of tax, in cents, charged for the order. | | tax | If the order is tax exempt omit this field or set | | | it to 0. | +------------------------------------------------------------------------+ A successful PL2 transaction will return one extra response parameter PL2 Output Parameter +------------------------------------------------------------------------+ | Parameter Name | Description | |----------------+-------------------------------------------------------| | commercialcard | Set to "S" for if it is a purchasing card, "R" if it | | | is corporate card, and "B" if it is a business card. | +------------------------------------------------------------------------+ If you don't care what kind of card they used (which you probably don't), there is no reason to store or otherwise do anything with the commercialcard return value. TrustCommerce internally handles all the details for you. However, if you want this information for some reason, you can access it from the result parameters. Purchase Level II Example params = { 'custid': 'mycustid', 'password': 'mypass', 'action': 'sale', 'cc': '4111111111111111', 'exp': '0404', 'amount': '1000' 'name': 'Jennifer Smith', 'purchaselevel': '2' 'purchaseordernum': '12345678901234567' 'tax': '83' # $10.00 x 8.25% sales tax = $0.83 } result = tclink.send(params) if (result['status'] == 'approved'): print 'Approved' XIV. Order Detail 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. Even if you aren't using automated fulfillment, you can use the order line item specification parameters to store information in the TrustCommerce transaction database about the type of products ordered. First, you may wish 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) XVI. 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. | |----------------+----------+--------------------------------------------| | | | Use 'y' or 'n'. For billing ID search. | | pastdue | | Show only recurring billing IDs that have | | | | been unable to capture the requested | | | | funds. | |----------------+----------+--------------------------------------------| | 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 TrustCommerce Query Interface

TrustCommerce Query Interface

custid This is your TrustCommerce custid (required)
password This is your TrustCommerce password (required)
format Human readable (html) or computer readable (text) results
Query type Type of query
media For now this must be cc
begindate MM-DD-YYYY HH:MM:SS Query begins at this date
enddate MM-DD-YYYY HH:MM:SS Query ends at this date
chain Narrow search to a single chain of transactions
transid Narrow search to a single transactions
billingid Narrow search to a single billingid
pastdue Use 'y' or 'n'. For billing ID search. Show only recurring billing IDs that have been unable to capture the requested funds.
action Narrow search by action. (example: preauth,postauth)
status Narrow search by status. (example: approved,accepted)
name Narrow search by name.
cc Narrow search by credit card field.
limit Limit results to this number of fields (not used for summary)
offset Report results at this offset (used with limit to page through results)
showcount Show the number of not-limited rows on the last line of the result
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. Please note: these cards ONLY work on transactions flagged as demo, or while your account is in "test" mode! For a live transaction, they will all return a decline with a declinetype of carderror. Test Cards - Approved +------------------------------------------------------------------------+ |Card Type | Card Number | Exp |Address | City |State| Zip |CVV | |----------+----------------+-----+--------+-----------+-----+------+----| |Visa |4111111111111111|04/04|123 Test|Somewhere |CA |90001 |123 | | | | |St. | | | | | |----------+----------------+-----+--------+-----------+-----+------+----| |Mastercard|5411111111111115|04/04|4000 |Anytown |AZ |85001 |777 | | | | |Main St.| | | | | |----------+----------------+-----+--------+-----------+-----+------+----| |American | | |12 | | | | | |Express |341111111111111 |04/04|Colorado|Elsewhere |IL |54321 |4000| | | | |Blvd. | | | | | |----------+----------------+-----+--------+-----------+-----+------+----| | | | |6789 | | | | | |Discover |6011111111111117|04/04|Green |Nowhere |MA |12345 |- | | | | |Ave. | | | | | |----------+----------------+-----+--------+-----------+-----+------+----| |Diner's | | |7390 Del| | | | | |Club |36484444444446 |04/04|Mar |Atown |NY |01101 |- | | | | |Blvd. | | | | | |----------+----------------+-----+--------+-----------+-----+------+----| | | | |350 | | | | | |JCB |213122222222221 |04/04|Madison |Springfield|OH |400000|- | | | | |Ave. | | | | | +------------------------------------------------------------------------+ 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. Test Cards - Declined +----------------------------------------+ | 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 | | | +-----------------------------------------------------------------------+ Appendix E - Input Field List Input Fields +--------------------------------------------------------------+ | Name | Type | Minimum Length | Maximum Length | |-------------------+--------+----------------+----------------| | custid | string | 1 | 20 | |-------------------+--------+----------------+----------------| | password | string | 1 | 20 | |-------------------+--------+----------------+----------------| | action | string | 1 | 10 | |-------------------+--------+----------------+----------------| | media | string | 1 | 10 | |-------------------+--------+----------------+----------------| | currency | string | 3 | 3 | |-------------------+--------+----------------+----------------| | amount | number | 3 | 8 | |-------------------+--------+----------------+----------------| | cc | number | 13 | 16 | |-------------------+--------+----------------+----------------| | exp | number | 4 | 4 | |-------------------+--------+----------------+----------------| | cvv | number | 3 | 4 | |-------------------+--------+----------------+----------------| | routing | number | 9 | 9 | |-------------------+--------+----------------+----------------| | account | number | 3 | 17 | |-------------------+--------+----------------+----------------| | billingid | string | 6 | 6 | |-------------------+--------+----------------+----------------| | verify | string | 1 | 1 | |-------------------+--------+----------------+----------------| | transid | string | 14 | 14 | |-------------------+--------+----------------+----------------| | avs | string | 1 | 10 | |-------------------+--------+----------------+----------------| | name | string | 1 | 60 | |-------------------+--------+----------------+----------------| | address1 | string | 1 | 80 | |-------------------+--------+----------------+----------------| | address2 | string | 1 | 80 | |-------------------+--------+----------------+----------------| | zip | string | 1 | 20 | |-------------------+--------+----------------+----------------| | city | string | 1 | 40 | |-------------------+--------+----------------+----------------| | state | string | 1 | 20 | |-------------------+--------+----------------+----------------| | country | string | 1 | 20 | |-------------------+--------+----------------+----------------| | phone | string | 1 | 30 | |-------------------+--------+----------------+----------------| | email | string | 1 | 50 | |-------------------+--------+----------------+----------------| | track1 | string | 1 | 79 | |-------------------+--------+----------------+----------------| | track2 | string | 1 | 40 | |-------------------+--------+----------------+----------------| | ticket | string | 1 | 30 | |-------------------+--------+----------------+----------------| | operator | string | 1 | 20 | |-------------------+--------+----------------+----------------| | shiptosame | string | 1 | 1 | |-------------------+--------+----------------+----------------| | shipto_name | string | 1 | 60 | |-------------------+--------+----------------+----------------| | shipto_address1 | string | 1 | 40 | |-------------------+--------+----------------+----------------| | shipto_address2 | string | 1 | 20 | |-------------------+--------+----------------+----------------| | shipto_city | string | 1 | 20 | |-------------------+--------+----------------+----------------| | shipto_state | string | 2 | 2 | |-------------------+--------+----------------+----------------| | shipto_zip | string | 1 | 20 | |-------------------+--------+----------------+----------------| | shipto_country | string | 1 | 20 | |-------------------+--------+----------------+----------------| | numitems | number | 1 | 3 | |-------------------+--------+----------------+----------------| | price | string | 1 | 20 | |-------------------+--------+----------------+----------------| | shippingcode | string | 1 | 20 | |-------------------+--------+----------------+----------------| | shippinghandling | string | 1 | 20 | |-------------------+--------+----------------+----------------| | productcode# | string | 1 | 20 | |-------------------+--------+----------------+----------------| | quantity# | number | 1 | 3 | |-------------------+--------+----------------+----------------| | price# | number | 1 | 6 | |-------------------+--------+----------------+----------------| | tax# | number | 1 | 6 | |-------------------+--------+----------------+----------------| | shippinghandling# | number | 1 | 6 | |-------------------+--------+----------------+----------------| | wallet | string | 1 | 1 | |-------------------+--------+----------------+----------------| | walletsize | string | 3 | 8 | |-------------------+--------+----------------+----------------| | walletexposure | string | 1 | 3 | |-------------------+--------+----------------+----------------| | start | string | 2 | 10 | |-------------------+--------+----------------+----------------| | cycle | string | 2 | 4 | |-------------------+--------+----------------+----------------| | payments | number | 1 | 4 | |-------------------+--------+----------------+----------------| | demo | string | 1 | 1 | |-------------------+--------+----------------+----------------| | offlineauthcode | string | 6 | 6 | +--------------------------------------------------------------+ ---------------------------------------------------------------------- Copyright (c) 2003 TrustCommerce libnet-tclink-perl-3.4.0/doc/TCDevGuide.html0100644000175000017500000020353607726211153020217 0ustar wittenwitten TrustCommerce Developer's Guide 2.3

TrustCommerce Developer's Guide 2.3

http://www.trustcommerce.com
developer@trustcommerce.com

March 18, 2003


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. TCS Citadel (Billing IDs)
XII. Recurring Billing
XIII. TCS Wallet
XIV. Purchase Level II (Commercial Cards)
XV. Order Detail
XVI. Vault Query API
Appendix A - Test Data
Appendix B - Troubleshooting
Appendix C - Connecting via HTTPS POST
Appendix D - Currency Table
Appendix E - Input Field List

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.
Destroy() Deallocate any memory associated with the transaction handle.
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 NameDescription
amountAmount of the transaction, in cents. (example: "500" is $5.00)
custidYour customer ID number assigned to you by TrustCommerce.
passwordThe password for your custid as assigned by TrustCommerce.
actionThe transaction type; can be one of preauth, sale, postauth, credit, store, unstore, walletsale, or chargeback

Optional Parameters

Parameter NameDescription
amountAmount of the transaction, in cents. (example: "500" is $5.00)
demoWhen set to "y", the transaction will be a test transaction only.
ticketFree-form text field intended for storing ticket number or order number associated with the transaction, to aid merchants in order tracking and reporting.
operatorFree-form text field intended for recording the 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 ValueDescription
approvedThe transaction was successfully authorized.
acceptedThe transaction has been successfully accepted into the system.
declineThe transaction was declined, see declinetype for further details.
baddataInvalid parameters passed, see error for further details.
errorSystem 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 ValueDescription
declineThis is a "true" decline, it almost always is a result of insufficient funds on the card.
avsAVS failed; the address entered does not match the billing address on file at the bank.
cvvCVV failed; the number provided is not the correct verification number for the card. (See section X for details on CVV.)
callThe 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.
carderrorCard number is invalid, usually the result of a typo in the card number.
authexpiredAttempt to postauth an expired (more than 7 days old) preauth.
dailylimitDaily limit in transaction count or amount as been reached.
weeklylimitWeekly limit in transaction count or amount as been reached.
monthlylimitMonthly 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 ValueDescription
missingfieldsSome parameters required for this transaction type were not sent.
extrafieldsParameters not allowed for this transaction type were sent.
badformatA field was improperly formatted, such as non-digit characters in a number field.
badlengthA field was longer or shorter than the server allows.
merchantcantacceptThe 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.
mismatchData 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 ValueDescription
cantconnectCouldn't connect to the TrustCommerce gateway. Check your Internet connection to make sure it is up.
dnsfailureThe TCLink software was unable to resolve DNS hostnames. Make sure you have name resolving ability on the machine.
linkfailureThe connection was established, but was severed before the transaction could complete.
failtoprocessThe bank servers are offline and unable to authorize 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 NameDescription
amountAmount of the transaction, in cents. (example: "500" is $5.00)
ccCredit card number, digits only (no spaces or dashes)
expCredit card expiration date, in MMYY format

Optional Parameters

Parameter NameDefault ValueDescription
mediacc"cc" for credit card or "ach" for ACH.
currencyusdCurrency code (see section X for the table of codes)
avsnAVS 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, or the full region/province for international addresses.
zip Cardholder's zipcode, five or nine digits with no spaces or dashes, or the full postal code for international addresses.
country Cardholder's country, leave blank for US.
phone Cardholder's phone number.
email Cardholder's email address.
offlineauthcode Six-digit numeric code used to "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=y 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. (This parameter is returned even when avs=n, which is the default.) It returns a single character code, which are enumerated in the table below.

AVS Returns Codes

CodeDescription
XExact match, 9 digit zipcode.
YExact match, 5 digit zipcode.
AStreet address match only.
W9 digit zipcode match only.
Z5 digit zipcode match only.
NNo match on street address or zipcode.
UAVS unavailable on this card.
GNon-US card issuer, AVS unavailable.
RCard issuer system currently down, try again later.
EError, ineligible - not a mail/phone order.
SService not supported.
0General 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. offlineauthcode can only be used with sale transactions. Be warned: offlineauthcode skips the authorization phase altogether, and thus 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 NameDescription
cvvA 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 NameDescription
track1Up to 79 bytes of Track 1 data.
track2Up 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 NameDescription
routingThe routing number of the bank being debited.
accountThe 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 NameDescription
transidThe transaction ID (format: nnn-nnnnnnnnnn) of the referenced transaction.

In addition, postauths and credits can take an optional amount parameter.

Optional Parameters

Parameter NameDescription
amountThe 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. TCS Citadel (Billing IDs)

The TCS Citadel 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.

The Citadel 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 NameDescription
verifyWhen set to "y", a $1.00 preauth will be run on the card to ensure that it is valid.
billingidPass if you wish to update values of an existing billing ID.

You can update information on existing billing IDs by passing the billingid field along with the store transaction. If you wish to erase the data contained in a field, pass the exact string "null" (four characters, all lower case) as the parameter value.

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 NameDescription
billingidThe 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 NameRequired?Description
cycleXRepeat cycle in days, weeks, months, or years.
amountXAmount 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 between 1 and 99 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.)

If there is no start parameter, the first transaction is run immediately (and can cause the store action to return a "decline" or other result you would expect from a sale). Other return parameters associated with auths, such as avs code, will be returned as well.

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.

There is only one instance in which the cycle parameter is not required, and that is a one-time future payment. By setting payments to "1" and passing a start date, the payment will be made on that date and then the billing ID unstored. The cycle parameter may be included with a one-time future payment, but it will have no effect.

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 annual payments, and don't start until September 1, 2004
		params['cycle'] = '1y';
		params['start'] = '2004-09-01';
	elif (mode == 5):
		# Make a one time payment in 45 days
		params['start'] = '45d';
		params['payments'] = '1';

	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 NameDescription
wallet"y" to enable the wallet.
walletsizeAccumulated amount, in cents, before the wallet is submitted for capture.
walletexposureLength 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. Purchase Level II

Purchase Level II is required by some merchant banks to achieve a qualifed discount rate. It is only used for B2B or B2G transactions. If you are selling products directly to consumers, you do not need to use PL2. Additionally, PL2 can only be used if the cardholder is using one of the three types of commercial cards: a corporate card, a business card, or a purchasing card.

PL2 has three new parmaeters:

PL2 Input Parameters

Parameter NameDescription
purchaselevelSpecify as "2".
purchaseordernumThe purchasing order number from their Visa purchasing card. This is either a 16 or a 17 digit number. If they are not using a Visa purchasing card, do not pass this field.
taxThe amount of tax, in cents, charged for the order. If the order is tax exempt omit this field or set it to 0.

A successful PL2 transaction will return one extra response parameter

PL2 Output Parameter

Parameter NameDescription
commercialcardSet to "S" for if it is a purchasing card, "R" if it is corporate card, and "B" if it is a business card.

If you don't care what kind of card they used (which you probably don't), there is no reason to store or otherwise do anything with the commercialcard return value. TrustCommerce internally handles all the details for you. However, if you want this information for some reason, you can access it from the result parameters.

Purchase Level II Example

	params = {
		'custid':           'mycustid',
		'password':         'mypass',
		'action':           'sale',
		'cc':               '4111111111111111',
		'exp':              '0404',
		'amount':           '1000'
		'name':             'Jennifer Smith',
		'purchaselevel':    '2'
		'purchaseordernum': '12345678901234567'
		'tax':              '83'    # $10.00 x 8.25% sales tax = $0.83

	}

	result = tclink.send(params)

	if (result['status'] == 'approved'):
		print 'Approved'

XV. Order Detail

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. Even if you aren't using automated fulfillment, you can use the order line item specification parameters to store information in the TrustCommerce transaction database about the type of products ordered.

First, you may wish 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 NameDescription
shiptosamey or n (defaults to n). If "y", then no other shipto_ parameters should be passed.
shipto_nameName of the product recipient.
shipto_address1First line of shipping address.
shipto_address2Second line (if any) of shipping address.
shipto_cityCity.
shipto_stateState.
shipto_zipZipcode, five or nine digits (no spaces or dashes).
shipto_countryCountry, 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 NameDescription
shippingcodeThree character code indicating shipping method to use.
shippinghandlingThe total cost of shipping and handling, in cents.
numitemsTotal 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 NameDescription
productcodeXThe alphanumeric product code defined by the fulfillment house.
quantityXThe number of items of this type to be shipped.
priceXThe price of all items of this type not including sales tax or shipping, in cents.
taxXTotal tax charged for all items of this product code.
shippinghandlingXTotal 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)

XVI. 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 NameRequred?Description
custidXTrustCommerce customer ID number.
passwordXThe password for your custID.
format Set to "html" for human-readable HTML output, or "text" (default) for CSV text output.
querytypeXPossible 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.
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.
pastdue Use 'y' or 'n'. For billing ID search. Show only recurring billing IDs that have been unable to capture the requested funds.
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.
offset Report result set starting from this 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=format> <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> pastdue </td>
		<td> <select name=pastdue> 
		<option value=y>y</option>
		<option value=n>n</option>
		</select></td>
		<td> Use 'y' or 'n'. For billing ID search.  Show only recurring billing IDs
		     that have been unable to capture the requested funds. </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.

Please note: these cards ONLY work on transactions flagged as demo, or while your account is in "test" mode! For a live transaction, they will all return a decline with a declinetype of carderror.

Test Cards - Approved

Card TypeCard NumberExpAddressCityStateZipCVV
Visa411111111111111104/04123 Test St.SomewhereCA90001123
Mastercard541111111111111504/044000 Main St.AnytownAZ85001777
American Express34111111111111104/0412 Colorado Blvd.ElsewhereIL543214000
Discover601111111111111704/046789 Green Ave.NowhereMA12345 -
Diner's Club3648444444444604/047390 Del Mar Blvd.AtownNY01101 -
JCB21312222222222104/04350 Madison Ave.SpringfieldOH400000 -

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.

Test Cards - Declined

Card NumberExpDeclineType
401234567890904/04decline
555544443333222604/04call
444411114444111104/04carderror

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

CodeCurrency TypeCodeCurrency Type
usdUS DollarsjpyJapan Yen
eurEurojodJordan Dinar
cadCanadian DollarskrwKorea (South) Won
gbpUK PoundslbpLebanon Pounds
demGerman DeutschemarkslufLuxembourg Francs
frfFrench FrancsmyrMalaysia Ringgit
jpyJapanese YenmxpMexico Pesos
nlgDutch GuildersnlgNetherlands Guilders
itlItalian LiranzdNew Zealand Dollars
chfSwitzerland FrancsnokNorway Kroner
dzdAlgeria DinarspkrPakistan Rupees
arpArgentina PesosxpdPalladium Ounces
audAustralia DollarsphpPhilippines Pesos
atsAustria SchillingsxptPlatinum Ounces
bsdBahamas DollarsplzPoland Zloty
bbdBarbados DollarsptePortugal Escudo
befBelgium FrancsrolRomania Leu
bmdBermuda DollarsrurRussia Rubles
brrBrazil RealsarSaudi Arabia Riyal
bglBulgaria LevxagSilver Ounces
cadCanada DollarssgdSingapore Dollars
clpChile PesosskkSlovakia Koruna
cnyChina Yuan RenmimbizarSouth Africa Rand
cypCyprus PoundskrwSouth Korea Won
cskCzech Republic KorunaespSpain Pesetas
dkkDenmark KronerxdrSpecial Drawing Right (IMF)
nlgDutch GuilderssddSudan Dinar
xcdEastern Caribbean DollarssekSweden Krona
egpEgypt PoundschfSwitzerland Francs
eurEurotwdTaiwan Dollars
fjdFiji DollarsthbThailand Baht
fimFinland MarkkattdTrinidad and Tobago Dollars
frfFrance FrancstrlTurkey Lira
demGermany Deutsche MarksgbpUnited Kingdom Pounds
xauGold OuncesusdUnited States Dollars
grdGreece DrachmasvebVenezuela Bolivar
hkdHong Kong DollarszmkZambia Kwacha
hufHungary ForinteurEuro
iskIceland KronaxcdEastern Caribbean Dollars
inrIndia RupeesxdrSpecial Drawing Right (IMF)
idrIndonesia RupiahxagSilver Ounces
iepIreland PuntxauGold Ounces
ilsIsrael New ShekelsxpdPalladium Ounces
itlItaly LiraxptPlatinum Ounces
jmdJamaica Dollars  

Appendix E - Input Field List

Input Fields

NameTypeMinimum LengthMaximum Length
custidstring120
passwordstring120
actionstring110
mediastring110
currencystring33
amountnumber38
ccnumber1316
expnumber44
cvvnumber34
routingnumber99
accountnumber317
billingidstring66
verifystring11
transidstring1414
avsstring110
namestring160
address1string180
address2string180
zipstring120
citystring140
statestring120
countrystring120
phonestring130
emailstring150
track1string179
track2string140
ticketstring130
operatorstring120
shiptosamestring11
shipto_namestring160
shipto_address1string140
shipto_address2string120
shipto_citystring120
shipto_statestring22
shipto_zipstring120
shipto_countrystring120
numitemsnumber13
pricestring120
shippingcodestring120
shippinghandlingstring120
productcode#string120
quantity#number13
price#number16
tax#number16
shippinghandling#number16
walletstring11
walletsizestring38
walletexposurestring13
startstring210
cyclestring24
paymentsnumber14
demostring11
offlineauthcodestring66


Copyright © 2003 TrustCommerce
libnet-tclink-perl-3.4.0/Changes0100644000175000017500000000036107726211153016123 0ustar wittenwittenRevision history for Perl extension TCLink. 3.4 Fri Jul 18 14:20:00 2003 - Upgrade to 3.4 version of C backend 3.3 Mon Jan 7 20:40:54 2002 - Upgrade to 3.3 version of C backend 3.25 Mon Oct 22 16:32:16 2001 - Initial CPAN release libnet-tclink-perl-3.4.0/MANIFEST0100644000175000017500000000020107726211153015752 0ustar wittenwittenChanges MANIFEST README LICENSE Makefile.PL TCLink.pm TCLink.xs test.pl tclink.h tclink.c doc/TCDevGuide.txt doc/TCDevGuide.html libnet-tclink-perl-3.4.0/README0100644000175000017500000000475207726211153015520 0ustar wittenwitten Net::TCLink v3.4 Perl Implementation copyright (C) TrustCommerce 2003 http://www.trustcommerce.com developer@trustcommerce.com September 5, 2003 I. DESCRIPTION Net::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 Perl or ActivePerl on Win32, do not use this client. Please download the COM object from the Vault website instead. II. BUILD You will need the OpenSSL libraries and header files installed on your system to compile Net::TCLink. You can download them from http://www.openssl.org. Many modern UNIX systems (including Red Hat Linux 7.0 and above) come with the OpenSSL libraries pre-installed. To build, you need only execute the following two commands: $ perl Makefile.PL $ make Optionally, you may test the build by running the following: $ make test III. INSTALLATION If you wish to install globally (recommended), execute the following command as root: # make install If you do not have root priviledges on the machine, or do not wish to install Net::TCLink globally, you may still load the module manually from the blib directory where it is built. Assuming the name of your test script is RunTrans.pl, use the following command line: $ perl -Iblib/arch -Iblib/lib RunTrans.pl You may wish to change "blib/arch" and "blib/lib" to be the full path to those locations, so that you may execute the command anywhere. Or, you may insert the following code at the top of your script: use lib "blib/lib"; use lib "blib/arch"; Again, you may prefer to use the full path name here. IV. USAGE The included perl script 'test.pl' contains example code for the Net::TCLink Perl module. Net::TCLink is very easy to use. It consists of a single function call, send(), that takes a hash or a hash reference as its only parameter. The hash contains the name/value pairs describing the transaction. The return value is also a hash, containing the name/value pairs describing the transactions results. Please refer to the TCDevGuide.txt or TCDevGuide.html in the doc folder for more information. libnet-tclink-perl-3.4.0/LICENSE0100644000175000017500000006347607726211153015655 0ustar wittenwitten GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! libnet-tclink-perl-3.4.0/Makefile.PL0100755000175000017500000000216407726211153016610 0ustar wittenwitten#!/usr/bin/perl use ExtUtils::MakeMaker; $usage = < 'Net::TCLink', 'VERSION_FROM' => 'TCLink.pm', 'PREREQ_PM' => {}, 'DEFINE' => '-DPERL5 -DTCLINK_VERSION=\"3.4-Perl-' . $platform . '\"', 'LIBS' => ["-L$openssl_path -L$openssl_path/lib $libs"], 'INC' => "-I$openssl_path/include" ); libnet-tclink-perl-3.4.0/TCLink.pm0100644000175000017500000000425707726211153016322 0ustar wittenwittenpackage Net::TCLink; use strict; use Carp; use vars qw($VERSION @ISA @EXPORT @EXPORT_OK $AUTOLOAD); require Exporter; require DynaLoader; require AutoLoader; @ISA = qw(Exporter DynaLoader); @EXPORT = qw( PARAM_MAX_LEN TCLinkHandle ); $VERSION = '3.4'; sub AUTOLOAD { my $constname; ($constname = $AUTOLOAD) =~ s/.*:://; croak "& not defined" if $constname eq 'constant'; my $val = constant($constname, @_ ? $_[0] : 0); if ($! != 0) { if ($! =~ /Invalid/) { $AutoLoader::AUTOLOAD = $AUTOLOAD; goto &AutoLoader::AUTOLOAD; } else { croak "Your vendor has not defined Net::TCLink macro $constname"; } } no strict 'refs'; *$AUTOLOAD = sub () { $val }; goto &$AUTOLOAD; } bootstrap Net::TCLink $VERSION; sub send { my $params; if ($#_ == 0) { $params = $_[0]; } else { %$params = @_; } my $handle = TCLinkCreate(); foreach (keys %$params) { TCLinkPushParam($handle,$_,$params->{$_}); } TCLinkSend($handle); my %response; my $buf = " " x 2048; $buf = TCLinkGetEntireResponse($handle,$buf); my @parts = split/\n/,$buf; foreach (@parts) { my ($name,$val) = split/=/,$_; $response{$name} = $val; } TCLinkDestroy($handle); return %response; } 1; __END__ # Below is stub documentation for your module. You better edit it! =head1 NAME Net::TCLink - Perl interface to the TrustCommerce payment gateway =head1 SYNOPSIS use Net::TCLink; %results = Net::TCLink::send(%params); =head1 DESCRIPTION Net::TCLink is a module that allows for fast, secure, reliable credit card and check transactions via the TrustCommerce IP gateway. The module consists of a single functions call that accepts a hash that describes the requested transaction and returns a map that describes the result. What values can be passed and returned are beyond the scope of this document and can be found in the web developers guide. This guide is included the Net::TCLink distribution as TCDevGuide.{txt,html} or can be found at https://vault.trustcommerce.com/. =head2 EXPORT None by default. =head1 AUTHOR Orion Henry, orion@trustcommerce.com =head1 SEE ALSO perl(1). =cut libnet-tclink-perl-3.4.0/TCLink.xs0100644000175000017500000000074007726211153016331 0ustar wittenwitten#include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "tclink.c" MODULE = Net::TCLink PACKAGE = Net::TCLink void * TCLinkCreate() void TCLinkPushParam(handle, name, value) void * handle char * name char * value void TCLinkSend(handle) void * handle char * TCLinkGetEntireResponse(handle,buf) void * handle char * buf CODE: TCLinkGetEntireResponse(handle,buf,strlen(buf)); RETVAL = buf; OUTPUT: RETVAL void TCLinkDestroy(handle) void * handle libnet-tclink-perl-3.4.0/test.pl0100755000175000017500000000170507726211153016152 0ustar wittenwitten# Before `make install' is performed this script should be runnable with # `make test'. After `make install' it should work as `perl test.pl' ######################### We start with some black magic to print on failure. # Change 1..1 below to 1..last_test_to_print . # (It may become useful if the test is moved to ./t subdirectory.) BEGIN { $| = 1; print "1..2\n"; } END {print "not ok 1\n" unless $loaded;} use Net::TCLink; $loaded = 1; print "ok 1\n"; my %params = ( custid => 'TestMerchant', password => 'password', amount => '100', cc => '4111111111111111', exp => '1209', action => 'sale' ); my %results = Net::TCLink::send(\%params); if ($results{status} eq 'approved') { print "ok 2\n"; } else { print "not ok 2\n"; } ######################### End of black magic. # Insert your test code below (better if it prints "ok 13" # (correspondingly "not ok 13") depending on the success of chunk 13 # of the test code): libnet-tclink-perl-3.4.0/tclink.h0100644000175000017500000000453407726211153016273 0ustar wittenwitten/* tclink.h - Header file for TCLink library. * * TCLink Copyright (c) 2003 TrustCommerce. * http://www.trustcommerce.com * developer@trustcommerce.com * (626) 744-7700 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef _TCLINK_H #define _TCLINK_H #include "config.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); #endif libnet-tclink-perl-3.4.0/tclink.c0100644000175000017500000006114707726211153016271 0ustar wittenwitten/* tclink.c - Library code for the TCLink client API. * * TCLink Copyright (c) 2003 TrustCommerce. * http://www.trustcommerce.com * developer@trustcommerce.com * (626) 744-7700 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "tclink.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define OPENSSL_NO_KRB5 1 #include #include #include #include #include #include #define DEFAULT_HOST "gateway2048.trustcommerce.com" #define TIMEOUT 40 /* seconds */ #define TC_BUFF_MAX 16000 #define TC_LINE_MAX ((PARAM_MAX_LEN * 2) + 2) char *tclink_version = TCLINK_VERSION; /* TCLINK_VERSION is defined in Makefile */ 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. */ enum { TC_CERT_SIZE = 952 }; unsigned char cert_data[TC_CERT_SIZE]={ 0x30,0x82,0x03,0xb4,0x30,0x82,0x02,0x9c,0x02,0x01,0x00,0x30,0x0d,0x06,0x09,0x2a, 0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x04,0x05,0x00,0x30,0x81,0x9f,0x31,0x0b,0x30, 0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x13,0x30,0x11,0x06,0x03, 0x55,0x04,0x08,0x13,0x0a,0x43,0x61,0x6c,0x69,0x66,0x6f,0x72,0x6e,0x69,0x61,0x31, 0x14,0x30,0x12,0x06,0x03,0x55,0x04,0x07,0x13,0x0b,0x4c,0x6f,0x73,0x20,0x41,0x6e, 0x67,0x65,0x6c,0x65,0x73,0x31,0x16,0x30,0x14,0x06,0x03,0x55,0x04,0x0a,0x13,0x0d, 0x54,0x72,0x75,0x73,0x74,0x43,0x6f,0x6d,0x6d,0x65,0x72,0x63,0x65,0x31,0x26,0x30, 0x24,0x06,0x03,0x55,0x04,0x03,0x13,0x1d,0x67,0x61,0x74,0x65,0x77,0x61,0x79,0x32, 0x30,0x34,0x38,0x2e,0x74,0x72,0x75,0x73,0x74,0x63,0x6f,0x6d,0x6d,0x65,0x72,0x63, 0x65,0x2e,0x63,0x6f,0x6d,0x31,0x25,0x30,0x23,0x06,0x09,0x2a,0x86,0x48,0x86,0xf7, 0x0d,0x01,0x09,0x01,0x16,0x16,0x69,0x6e,0x66,0x6f,0x40,0x74,0x72,0x75,0x73,0x74, 0x63,0x6f,0x6d,0x6d,0x65,0x72,0x63,0x65,0x2e,0x63,0x6f,0x6d,0x30,0x1e,0x17,0x0d, 0x30,0x33,0x30,0x33,0x31,0x32,0x30,0x30,0x35,0x35,0x35,0x37,0x5a,0x17,0x0d,0x30, 0x33,0x30,0x34,0x31,0x31,0x30,0x30,0x35,0x35,0x35,0x37,0x5a,0x30,0x81,0x9f,0x31, 0x0b,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x13,0x30,0x11, 0x06,0x03,0x55,0x04,0x08,0x13,0x0a,0x43,0x61,0x6c,0x69,0x66,0x6f,0x72,0x6e,0x69, 0x61,0x31,0x14,0x30,0x12,0x06,0x03,0x55,0x04,0x07,0x13,0x0b,0x4c,0x6f,0x73,0x20, 0x41,0x6e,0x67,0x65,0x6c,0x65,0x73,0x31,0x16,0x30,0x14,0x06,0x03,0x55,0x04,0x0a, 0x13,0x0d,0x54,0x72,0x75,0x73,0x74,0x43,0x6f,0x6d,0x6d,0x65,0x72,0x63,0x65,0x31, 0x26,0x30,0x24,0x06,0x03,0x55,0x04,0x03,0x13,0x1d,0x67,0x61,0x74,0x65,0x77,0x61, 0x79,0x32,0x30,0x34,0x38,0x2e,0x74,0x72,0x75,0x73,0x74,0x63,0x6f,0x6d,0x6d,0x65, 0x72,0x63,0x65,0x2e,0x63,0x6f,0x6d,0x31,0x25,0x30,0x23,0x06,0x09,0x2a,0x86,0x48, 0x86,0xf7,0x0d,0x01,0x09,0x01,0x16,0x16,0x69,0x6e,0x66,0x6f,0x40,0x74,0x72,0x75, 0x73,0x74,0x63,0x6f,0x6d,0x6d,0x65,0x72,0x63,0x65,0x2e,0x63,0x6f,0x6d,0x30,0x82, 0x01,0x22,0x30,0x0d,0x06,0x09,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01,0x05, 0x00,0x03,0x82,0x01,0x0f,0x00,0x30,0x82,0x01,0x0a,0x02,0x82,0x01,0x01,0x00,0xb7, 0x9e,0x49,0xa6,0xf2,0x34,0xc2,0x1c,0xbc,0x23,0xee,0x66,0x52,0x10,0x8a,0xba,0xf6, 0x6c,0x31,0x78,0x58,0x4e,0x44,0xce,0x40,0x0f,0x90,0x52,0x66,0x3e,0xa7,0x34,0xef, 0x31,0x24,0x13,0x73,0x20,0x33,0x4b,0xe2,0x3a,0x4d,0x4c,0xdd,0x48,0x8b,0xf4,0xb9, 0xdd,0x4e,0x54,0xc8,0x79,0xd3,0x13,0xac,0x73,0x93,0x3d,0x47,0x99,0x1a,0x5c,0x4a, 0xdb,0x0f,0x2d,0xf9,0xb5,0x5d,0x3e,0x91,0x15,0x4e,0x7d,0x7e,0x21,0x47,0xf2,0xb3, 0xcc,0xd3,0x7c,0xc4,0x2f,0x9e,0xfe,0xec,0xd5,0x0f,0xe7,0xc8,0x7e,0x7f,0xf6,0x32, 0xb8,0xac,0xff,0xac,0x8e,0xbf,0xb2,0xc1,0xaa,0xf3,0x66,0x4d,0x86,0x9a,0xd9,0xd4, 0x04,0x97,0x5a,0xc3,0xa3,0x33,0xc8,0x2e,0x4f,0x07,0xca,0x6f,0x1c,0x58,0xbd,0x00, 0x9e,0xe9,0xd8,0x3c,0xe2,0x87,0x80,0xb5,0x99,0x40,0x37,0x2f,0x24,0x05,0x4b,0xc2, 0xf9,0xe7,0x25,0x8e,0xfc,0x76,0xb1,0x76,0xde,0xf2,0xe6,0x5f,0x06,0x44,0x31,0x59, 0x1c,0xed,0x8b,0x1c,0x1c,0xb1,0x2f,0x48,0xf7,0xeb,0x78,0x73,0xa5,0x57,0xac,0xf0, 0x30,0x7f,0xdd,0x09,0xa8,0x7b,0xb5,0xc5,0x30,0x2c,0xcc,0x6a,0xaf,0x6e,0x98,0x6d, 0xa3,0x08,0xf8,0x94,0x0e,0x7a,0xad,0xe6,0xe5,0x27,0x01,0xc8,0x2f,0x01,0x0f,0x59, 0x87,0x3f,0x5f,0x6f,0x5f,0x2c,0x27,0x3d,0xe8,0x33,0x2e,0xc1,0x69,0xbb,0xe9,0xa0, 0xea,0xea,0x19,0x8b,0x9d,0x0f,0xa0,0x88,0x51,0x53,0xc1,0xf9,0x3d,0x41,0x9f,0xe2, 0xa8,0x66,0x0c,0xb3,0x21,0x64,0xd3,0x4b,0x81,0x91,0xd7,0x7d,0xce,0xc7,0xb5,0x02, 0x03,0x01,0x00,0x01,0x30,0x0d,0x06,0x09,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01, 0x04,0x05,0x00,0x03,0x82,0x01,0x01,0x00,0x12,0x8d,0xa7,0x9b,0x9f,0x0b,0x8e,0x26, 0x8f,0xf2,0xf5,0x77,0xe2,0x71,0x85,0xd0,0x82,0x30,0x3f,0x44,0x68,0x6e,0xc6,0x4a, 0xe2,0x19,0x35,0x00,0x5e,0x6b,0xb1,0xd1,0xd4,0xd4,0x62,0x92,0xbe,0xc2,0x10,0x07, 0xbe,0x86,0x7b,0x8a,0xa5,0xe6,0xef,0x2b,0x6c,0x86,0x4d,0xc3,0x72,0x73,0xbf,0x68, 0x2a,0xaf,0xee,0x7d,0x97,0xad,0x20,0x3c,0xef,0x5c,0x83,0x78,0x01,0xf5,0xe5,0x08, 0x4f,0x33,0x52,0xaa,0xe6,0xb9,0x57,0xc9,0x26,0x48,0x59,0x20,0xe2,0x8b,0xdf,0xce, 0x49,0x6f,0x2f,0x7c,0x66,0x03,0x75,0x62,0x97,0x35,0xdf,0x23,0x8d,0x81,0xde,0x85, 0x9b,0x21,0x28,0x8b,0x74,0x35,0xa8,0x24,0x64,0x26,0x73,0xae,0xda,0xbd,0x81,0x2c, 0x87,0x97,0xd4,0xe6,0x0b,0x7e,0xcc,0x1b,0x1f,0xa9,0x6c,0x6a,0x70,0xbd,0x7f,0x1e, 0x9c,0x2d,0x7c,0xcc,0x62,0x7f,0x1a,0x93,0x12,0xaf,0xd9,0xd5,0xd8,0xe6,0x94,0xb7, 0x64,0x09,0x2c,0xc2,0xc5,0x5b,0x73,0x8f,0x4c,0x58,0x1b,0xbc,0x37,0x42,0x3c,0x4c, 0x37,0x7e,0x9e,0x79,0x1f,0xd1,0x0c,0xfe,0x54,0xc7,0x82,0x8f,0xde,0x87,0xf0,0xe2, 0x40,0x68,0x4f,0x47,0x03,0x0d,0x23,0x46,0xf2,0x67,0xb9,0x30,0x3b,0x42,0xe3,0x77, 0x40,0xa6,0xc2,0x9e,0x28,0xdf,0x28,0xda,0xfc,0xec,0xd0,0xc0,0x6a,0xd9,0x80,0x41, 0x60,0x5a,0xfb,0x24,0x23,0x2e,0x4d,0x50,0xb1,0xec,0xfb,0xb3,0x97,0xe2,0x4a,0x5a, 0xc7,0xda,0x12,0xbb,0x2a,0x6b,0x04,0xd6,0x90,0x91,0xe9,0xf7,0x5d,0x42,0x98,0xd7, 0x81,0x8a,0xd3,0x70,0x31,0xbd,0x11,0x4a}; /************************************* * 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; X509 *server_cert; time_t start, remaining; fd_set in, out, err; struct timeval tv; /* 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; FD_ZERO(&in); FD_SET((unsigned)sd, &in); FD_ZERO(&out); FD_SET((unsigned)sd, &out); FD_ZERO(&err); FD_SET((unsigned)sd, &err); 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 */ tv.tv_sec = remaining; tv.tv_usec = 0; if (select(sd+1, &in, &out, &err, &tv) < 0) 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[4]; int addr[3]; 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("216.34.199.222"); addr[1] = inet_addr("216.120.83.124"); addr[2] = inet_addr("64.14.242.58"); addr_list[0] = (char *)&addr[0]; addr_list[1] = (char *)&addr[1]; addr_list[2] = (char *)&addr[2]; addr_list[3] = 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, TC_CERT_SIZE); 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; }