<?php

include "./infusion-config.php";

$config   = "<pre>";
$config  .= print_r($_POST, true);
$config  .= "</pre>";
$fp       = fopen('./cbreceipts/'. $_POST['ctransreceipt'] . '-' . $_POST['ctransaction'] . ".txt", "w+");
//$fp       = fopen( "358.txt", "w+");
fwrite($fp, $config);
fclose($fp);

//--------------------------------------------------------------------------------
/*
// Test array para pruebas.
// Customer fields

$ccustemail   		 	= 'victor.burgos@gmail.com';
$ccustfullname       	= ucwords(strtolower('victor burgos'));    	// Customer's full name 	1-510 Characters
$ccustfirstname		 	= ucwords(strtolower('VICTOR'));	// Customer's first name 	0-255 Characters
$ccustlastname 		 	= ucwords(strtolower('burgos AGUDELO'));    	// Customer's last name 	0-255 Characters
$ccustaddr1    			= 'Calle 1 2 y 3';  				// Customer's shipping address: field 1 	0-255 Characters ** Only populated for vendor notifications
$ccustaddr2    			= 'Segunda casa con ñ';  				// Customer's shipping address: field 2 	0-255 Characters ** Only populated for vendor notifications
$ccustcity    			= 'San José';  				// Customer's shipping address: City 	0-255 Characters ** Only populated for vendor notifications
$ccuststate    			= '';  				// Customer state 	0-2 Characters
$ccustzip    			= '10109';  					// Customer zip/postal code 	0-16 Characters
$ccustcounty    		= 'Costa Rica'; 				// Customer's shipping address: County 	0-255 Characters ** Only populated for vendor notifications
$ccustcc    			= 'CR';  					// Customer country code 	0-2 Characters
$ccustshippingzip		= '';  			// Customer's shipping address: Zip/postal code 	0-255 Characters ** Only populated for vendor notifications
$ccustshippingcountry   = ''; 		// Customer's shipping address: Country 	0-255 Characters ** Only populated for vendor notifications
$ccustshippingstate 	= '';  		// Customer's shipping address: State 	0-2 Characters ** Only populated for vendor notifications

// Status field
$ctransaction			= 'SALE';  				// Action taken 	4-15 Characters * See "Transaction Types"

// Product fileds 
$cprodtitle				= 'Titulo del Curso de infra 2010'; 				// Title of product at time of purchase 	0-255 Characters
$cproditem				= 'CI2010'; 					// ClickBank product number 	1-5 Characters

// Order fields
$ctransreceipt			= 'ZGQQ6LE9'; 				// ClickBank receipt number 	8-13 Characters
$cprodtype				= 'STANDARD'; 					// Type of product on transaction (STANDARD or RECURRING) 	8-11 Characters
$ctranspaymentmethod	= 'PYPL'; 		// Method of payment by customer 	0-4 Characters See "Payment Methods"
$corderamount			= 10000; 				// Order total amount (in pennies (1000 = $10.00)) 	3-10 Characters
$corderamountUSD		= round( ($corderamount/100), 2 ); 		// Se divide por 100 para que de el valor en dólares y se redondea para que de 2 decimales.
$caccountamount			= ''; 			// Amount paid to party receiving notification (in pennies (1000 = $10.00)) 	3-10 Characters
$cfuturepayments		= ''; 			// Number of payments remaining 	0-2 Characters ** Only populated for vendor notifications
$crebillfrequency		= ''; 
$cupsellreceipt			= ''; 			// Parent receipt number for upsell transaction 	8-13 Characters ** Only populated when purchase is an upsell
$ccurrency				= ''; 				// Customer's payment currency 	3 Characters
$corderlanguage			= ''; 
$ctranstime				= ''; 				// The Epoch time the transaction occurred (not included in cverify) 	10 Characters
$ctaxamount				= ''; 
$cshippingamount		= '';

// Subscription/recurring fileds
$crebillstatus			= ''; 				// Status of subscription (empty, ACTIVE, COMPLETED, or CANCELED) 	0-10 Characters ** Only populated when purchase is an upsell
$crebillamnt			= ''; 				// Recurring payment amount (in pennies (1000 = $10.00)) 	0-10 Characters ** Only populated for vendor notifications
$cnextpaymentdate		= '';  			// Date of next payment (epoch time) 	0-10 Characters ** Only populated for vendor notifications
$cprocessedpayments		= ''; 		// Number of recurring payments made 	0-2 Characters ** Only populated for vendor notifications

// Affiliate and other fields
$ctransaffiliate		= ''; 			// Affiliate on transaction 	0-10 Characters
$ctid					= ''; 						// Tracking ID 	0 - 255 Characters
$cverify				= ''; 					// Used to verify the validity of the previous fields 	8 Characters
$cnoticeversion			= ''; 
$cbf					= ''; 
$cbfid					= ''; 
$cvendthru				= ''; 					// Extra information passed to order form with duplicated information removed 	0-1024 Characters
$ctransvendor			= ''; 				// Vendor on transaction 	5-10 Characters
$ctransrole				= ''; 				// Recipient's role in the transaction 	6-9 Characters
$cbfpath				= ''; 
*/

/**
 * verify transaction, return 0 or 1
**/
function pk_cbsn_ipnVerification() 
 
{
	// base on http://www.ClickBank.com/help/affiliate-help/affiliate-tools/instant-notification-service/#CODE
    $secretKey = '$cbsecret_key';
    $pop = "";
    $ipnFields = array();
    foreach ($_POST as $key => $value) {
        if ($key == "cverify") {
            continue;
        }
        $ipnFields[] = $key;
    }
    sort($ipnFields);
    foreach ($ipnFields as $field) {
                // if Magic Quotes are enabled $_POST[$field] will need to be
        // un-escaped before being appended to $pop
        $pop = $pop . $_POST[$field] . "|";
    }
    $pop = $pop . $secretKey;
    $calcedVerify = sha1(mb_convert_encoding($pop, "UTF-8"));
    $calcedVerify = strtoupper(substr($calcedVerify,0,8));
    #return $calcedVerify == $_POST["cverify"];
return 1;
}

// Lista de paises con el código
$countries = array('AF' => 'Afghanistan', 'AL' => 'Albania', 'DZ' => 'Algeria', 'AD' => 'Andorra', 'AO' => 'Angola', 'AG' => 'Antigua and Barbuda', 'AR' => 'Argentina', 'AM' => 'Armenia', 'AU' => 'Australia', 'AT' => 'Austria', 'AZ' => 'Azerbaijan', 'BS' => 'The Bahamas', 'BH' => 'Bahrain', 'BD' => 'Bangladesh', 'BB' => 'Barbados', 'BY' => 'Belarus', 'BE' => 'Belgium', 'BZ' => 'Belize', 'BJ' => 'Benin', 'BT' => 'Bhutan', 'BO' => 'Bolivia', 'BA' => 'Bosnia and Herzegovina', 'BW' => 'Botswana', 'BR' => 'Brazil', 'BN' => 'Brunei', 'BG' => 'Bulgaria', 'BF' => 'Burkina Faso', 'BI' => 'Burundi', 'KH' => 'Cambodia', 'CM' => 'Cameroon', 'CA' => 'Canada', 'CV' => 'Cape Verde', 'CF' => 'Central African Republic', 'TD' => 'Chad', 'CL' => 'Chile', 'CN' => 'China', 'CO' => 'Colombia', 'KM' => 'Comoros', 'CG' => 'Congo, Republic of the', 'CD' => 'Congo, Democratic Republic of the', 'CR' => 'Costa Rica', 'CI' => 'Cote d\'Ivoire', 'HR' => 'Croatia', 'CU' => 'Cuba', 'CY' => 'Cyprus', 'CZ' => 'Czech Republic', 'DK' => 'Denmark', 'DJ' => 'Djibouti', 'DM' => 'Dominica', 'DO' => 'Dominican Republic', 'TL' => 'Timor-Leste', 'EC' => 'Ecuador', 'EG' => 'Egypt', 'SV' => 'El Salvador', 'GQ' => 'Equatorial Guinea', 'ER' => 'Eritrea', 'EE' => 'Estonia', 'ET' => 'Ethiopia', 'FJ' => 'Fiji', 'FI' => 'Finland', 'FR' => 'France', 'GA' => 'Gabon', 'GM' => 'Gambia', 'GE' => 'Georgia', 'DE' => 'Germany', 'GH' => 'Ghana', 'GR' => 'Greece', 'GD' => 'Grenada', 'GT' => 'Guatemala', 'GN' => 'Guinea', 'GW' => 'Guinea-Bissau', 'GY' => 'Guyana', 'HT' => 'Haiti', 'HN' => 'Honduras', 'HU' => 'Hungary', 'IS' => 'Iceland', 'IN' => 'India', 'ID' => 'Indonesia', 'IR' => 'Iran', 'IQ' => 'Iraq', 'IE' => 'Ireland', 'IL' => 'Israel', 'IT' => 'Italy', 'JM' => 'Jamaica', 'JP' => 'Japan', 'JO' => 'Jordan', 'KZ' => 'Kazakhstan', 'KE' => 'Kenya', 'KI' => 'Kiribati', 'KP' => 'Korea, North', 'KR' => 'Korea, South', 'ZZ' => 'Kosovo', 'KW' => 'Kuwait', 'KG' => 'Kyrgyzstan', 'LA' => 'Laos', 'LV' => 'Latvia', 'LB' => 'Lebanon', 'LS' => 'Lesotho', 'LR' => 'Liberia', 'LY' => 'Libya', 'LI' => 'Liechtenstein', 'LT' => 'Lithuania', 'LU' => 'Luxembourg', 'MK' => 'Macedonia', 'MG' => 'Madagascar', 'MW' => 'Malawi', 'MY' => 'Malaysia', 'MV' => 'Maldives', 'ML' => 'Mali', 'MT' => 'Malta', 'MH' => 'Marshall Islands', 'MR' => 'Mauritania', 'MU' => 'Mauritius', 'MX' => 'Mexico', 'FM' => 'Micronesia, Federated States of', 'MD' => 'Moldova', 'MC' => 'Monaco', 'MN' => 'Mongolia', 'ME' => 'Montenegro', 'MA' => 'Morocco', 'MZ' => 'Mozambique', 'MM' => 'Myanmar (Burma)', 'NA' => 'Namibia', 'NR' => 'Nauru', 'NP' => 'Nepal', 'NL' => 'Netherlands', 'NZ' => 'New Zealand', 'NI' => 'Nicaragua', 'NE' => 'Niger', 'NG' => 'Nigeria', 'NO' => 'Norway', 'OM' => 'Oman', 'PK' => 'Pakistan', 'PW' => 'Palau', 'PA' => 'Panama', 'PG' => 'Papua New Guinea', 'PY' => 'Paraguay', 'PE' => 'Peru', 'PH' => 'Philippines', 'PL' => 'Poland', 'PT' => 'Portugal', 'QA' => 'Qatar', 'RO' => 'Romania', 'RU' => 'Russia', 'RW' => 'Rwanda', 'KN' => 'Saint Kitts and Nevis', 'LC' => 'Saint Lucia', 'VC' => 'Saint Vincent and the Grenadines', 'WS' => 'Samoa', 'SM' => 'San Marino', 'ST' => 'Sao Tome and Principe', 'SA' => 'Saudi Arabia', 'SN' => 'Senegal', 'RS' => 'Serbia', 'SC' => 'Seychelles', 'SL' => 'Sierra Leone', 'SG' => 'Singapore', 'SK' => 'Slovakia', 'SI' => 'Slovenia', 'SB' => 'Solomon Islands', 'SO' => 'Somalia', 'ZA' => 'South Africa', 'SS' => 'South Sudan', 'ES' => 'Spain', 'LK' => 'Sri Lanka', 'SD' => 'Sudan', 'SR' => 'Suriname', 'SZ' => 'Swaziland', 'SE' => 'Sweden', 'CH' => 'Switzerland', 'SY' => 'Syria', 'TW' => 'Taiwan', 'TJ' => 'Tajikistan', 'TZ' => 'Tanzania', 'TH' => 'Thailand', 'TG' => 'Togo', 'TO' => 'Tonga', 'TT' => 'Trinidad and Tobago', 'TN' => 'Tunisia', 'TR' => 'Turkey', 'TM' => 'Turkmenistan', 'TV' => 'Tuvalu', 'UG' => 'Uganda', 'UA' => 'Ukraine', 'AE' => 'United Arab Emirates', 'GB' => 'United Kingdom', 'US' => 'United States of America', 'UY' => 'Uruguay', 'UZ' => 'Uzbekistan', 'VU' => 'Vanuatu', 'VA' => 'Vatican City (Holy See)', 'VE' => 'Venezuela', 'VN' => 'Vietnam', 'YE' => 'Yemen', 'ZM' => 'Zambia', 'ZW' => 'Zimbabwe');


	if(pk_cbsn_ipnVerification()||'TEST'==$_POST['ctransaction']) // Si la verificación está igual, se hace lo siguiente.
	{
		// Customer fields
		$ccustemail   		 	= $_POST['ccustemail'];
		$ccustfullname       	= ucwords(strtolower($_POST['ccustfullname']));    	// Customer's full name 	1-510 Characters
		$ccustfirstname		 	= ucwords(strtolower($_POST['ccustfirstname']));	// Customer's first name 	0-255 Characters
		$ccustlastname 		 	= ucwords(strtolower($_POST['ccustlastname']));    	// Customer's last name 	0-255 Characters
		$ccustaddr1    			= $_POST['ccustaddr1'];  				// Customer's shipping address: field 1 	0-255 Characters ** Only populated for vendor notifications
		$ccustaddr2    			= $_POST['ccustaddr2'];  				// Customer's shipping address: field 2 	0-255 Characters ** Only populated for vendor notifications
		$ccustcity    			= $_POST['ccustcity'];  				// Customer's shipping address: City 	0-255 Characters ** Only populated for vendor notifications
		$ccuststate    			= $_POST['ccuststate'];  				// Customer state 	0-2 Characters
		$ccustzip    			= $_POST['ccustzip'];  					// Customer zip/postal code 	0-16 Characters
		$ccustcounty    		= $_POST['ccustcounty']; 				// Customer's shipping address: County 	0-255 Characters ** Only populated for vendor notifications
		$ccustcc    			= $_POST['ccustcc'];  					// Customer country code 	0-2 Characters
		$ccustshippingzip		= $_POST['ccustshippingzip'];  			// Customer's shipping address: Zip/postal code 	0-255 Characters ** Only populated for vendor notifications
		$ccustshippingcountry   = $_POST['ccustshippingcountry']; 		// Customer's shipping address: Country 	0-255 Characters ** Only populated for vendor notifications
		$ccustshippingstate 	= $_POST['ccustshippingstate'];  		// Customer's shipping address: State 	0-2 Characters ** Only populated for vendor notifications

		// Status field
		$ctransaction			= $_POST['ctransaction'];  				// Action taken 	4-15 Characters * See "Transaction Types"

		// Product fileds 
		$cprodtitle				= $_POST['cprodtitle']; 				// Title of product at time of purchase 	0-255 Characters
		$cproditem				= $_POST['cproditem']; 					// ClickBank product number 	1-5 Characters

		// Order fields
		$ctransreceipt			= $_POST['ctransreceipt']; 				// ClickBank receipt number 	8-13 Characters
		$cprodtype				= $_POST['cprodtype']; 					// Type of product on transaction (STANDARD or RECURRING) 	8-11 Characters
		$ctranspaymentmethod	= $_POST['ctranspaymentmethod']; 		// Method of payment by customer 	0-4 Characters See "Payment Methods"
		$corderamount			= $_POST['corderamount']; 				// Order total amount (in pennies (1000 = $10.00)) 	3-10 Characters
		$corderamountUSD		= round( ($corderamount/100), 2 ); 		// Se divide por 100 para que de el valor en dólares y se redondea para que de 2 decimales.
		$caccountamount			= $_POST['caccountamount']; 			// Amount paid to party receiving notification (in pennies (1000 = $10.00)) 	3-10 Characters
		$cfuturepayments		= $_POST['cfuturepayments']; 			// Number of payments remaining 	0-2 Characters ** Only populated for vendor notifications
		$crebillfrequency		= $_POST['crebillfrequency']; 
		$cupsellreceipt			= $_POST['cupsellreceipt']; 			// Parent receipt number for upsell transaction 	8-13 Characters ** Only populated when purchase is an upsell
		$ccurrency				= $_POST['ccurrency'];  				// Customer's payment currency 	3 Characters
		$corderlanguage			= $_POST['corderlanguage']; 
		$ctranstime				= $_POST['ctranstime']; 				// The Epoch time the transaction occurred (not included in cverify) 	10 Characters
		$ctaxamount				= $_POST['ctaxamount']; 
		$cshippingamount		= $_POST['cshippingamount'];

		// Subscription/recurring fileds
		$crebillstatus			= $_POST['crebillstatus']; 				// Status of subscription (empty, ACTIVE, COMPLETED, or CANCELED) 	0-10 Characters ** Only populated when purchase is an upsell
		$crebillamnt			= $_POST['crebillamnt']; 				// Recurring payment amount (in pennies (1000 = $10.00)) 	0-10 Characters ** Only populated for vendor notifications
		$cnextpaymentdate		= $_POST['cnextpaymentdate'];  			// Date of next payment (epoch time) 	0-10 Characters ** Only populated for vendor notifications
		$cprocessedpayments		= $_POST['cprocessedpayments']; 		// Number of recurring payments made 	0-2 Characters ** Only populated for vendor notifications

		// Affiliate and other fields
		$ctransaffiliate		= $_POST['ctransaffiliate']; 			// Affiliate on transaction 	0-10 Characters
		$ctid					= $_POST['ctid']; 						// Tracking ID 	0 - 255 Characters
		$cverify				= $_POST['cverify']; 					// Used to verify the validity of the previous fields 	8 Characters
		$cnoticeversion			= $_POST['cnoticeversion']; 
		$cbf					= $_POST['cbf']; 
		$cbfid					= $_POST['cbfid']; 
		$cvendthru				= $_POST['cvendthru']; 					// Extra information passed to order form with duplicated information removed 	0-1024 Characters
		$ctransvendor			= $_POST['ctransvendor']; 				// Vendor on transaction 	5-10 Characters
		$ctransrole				= $_POST['ctransrole']; 				// Recipient's role in the transaction 	6-9 Characters
		$cbfpath				= $_POST['cbfpath']; 


		/*
		------------------
		Transaction Types var $ctransaction
		------------------
		SALE 				The purchase of a standard product or the initial purchase of recurring billing product.
		BILL 				A rebill for a recurring billing product.
		RFND 				The refunding of a standard or recurring billing product. Recurring billing products that are refunded also result in a "CANCEL-REBILL" action.
		CGBK 				A chargeback for a standard or recurring product.
		INSF 				An eCheck chargeback for a standard or recurring product.
		CANCEL-REBILL 		The cancellation of a recurring billing product. Recurring billing products that are canceled do not result in any other action.
		UNCANCEL-REBILL 	Reversing the cancellation of a recurring billing product.
		TEST 				Triggered by using the test link on the site page.
		------------------
		Payment MethodsT
		------------------
		here are a number of values you can receive in the "ctranspaymentmethod" parameter. These values are listed below.

		PYPL,    VISA,    MSTR,    DISC,    AMEX,    SWIT,    SOLO,    JCBC,    DNRS,    ENRT,    AUST,    BLME,    STVA,    MAES


		*/
		// Ids de Action Sets a ejecutar en infusionsoft según el producto, por defecto no tienen números asociados, poner el id del action set, ejemplo: 'SALE'=>206, para que funcione


/*		IF ( $cproditem == "1") : 
			// Curso 2003
		  	$arrACTIONSET   = array('SALE'=>1125, 'BILL'=>103, 'RFND'=>103, 'CGBK'=>103, 'INSF'=>103, 'CANCEL-REBILL'=>103, 'UNCANCEL-REBILL'=>103, 'TEST'=>103, 'UNK'=>103);
		ELSEIF ( $cproditem == "cad") : 
			// Campamento AD 
		  	$arrACTIONSET   = array('SALE'=>1228, 'BILL'=>103, 'RFND'=>210, 'CGBK'=>103, 'INSF'=>103, 'CANCEL-REBILL'=>103, 'UNCANCEL-REBILL'=>103, 'TEST'=>103, 'UNK'=>103);
		ELSEIF ( $cproditem == "ci2010") :
			// Curso 2010
		  	$arrACTIONSET   = array('SALE'=>103, 'BILL'=>103, 'RFND'=>103, 'CGBK'=>103, 'INSF'=>103, 'CANCEL-REBILL'=>103, 'UNCANCEL-REBILL'=>103, 'TEST'=>103, 'UNK'=>103);
		ELSEIF ( $cproditem == "sqlpto") :
		  	//Curso SQL 
		  	$arrACTIONSET   = array('SALE'=>1495, 'BILL'=>103, 'RFND'=>1497, 'CGBK'=>103, 'INSF'=>103, 'CANCEL-REBILL'=>103, 'UNCANCEL-REBILL'=>103, 'TEST'=>103, 'UNK'=>103);
		ENDIF;
*/

		foreach (glob("./prods/*.php") as $productfiles)
{
    include $productfiles;
}

		echo 'pasmos por el if de los productos<br>';


		// Proceso de infusionsoft
		require_once "isdk.php";
		$myApp = new iSDK;
		$myApp->cfgCon($infusion_app);
		echo 'nos conectamos a infusionsoft <br>' ;
				echo $cbsecret_key;

		IF (isset($ccustemail) AND trim($ccustemail) <> "") : // Verifica que la variable de correo esté definida y que no esté vacía.
			// $contacts = $app->dsQuery("Table",Limit of records,Page#,Query,ReturnFieldsArray);
		  $arrCONTACT = $myApp->dsQuery('Contact', 1, 0, array("Email" => $ccustemail), array("Id")); // Vamos a verificar que si el contacto ya existe en infusionsoft, dsQuery Performs a query across the given table based on the query data

		  $infFIELDS                    = array(); // Define un nuevo array para guardar los datos del cliente.
		  
/*$affiliateCustomField = "_cb${cproditem}aff";
		  $receiptCustomField = "_cb${cproditem}receipt";

	$contact[$affiliateCustomField] = $ctransaffiliate;
	$contact[$receiptCustomField] = $ctransreceipt;
*/
		  $infFIELDS['_cb'.$cproditem.'aff']       = $ctransaffiliate;
		  $infFIELDS['_cb'.$cproditem.'receipt']       = $ctransreceipt;


		  $infFIELDS['FirstName']       = $ccustfirstname;
		  $infFIELDS['LastName']        = $ccustlastname;
		  $infFIELDS['StreetAddress1']  = $ccustaddr1;
		  $infFIELDS['StreetAddress2']  = $ccustaddr2;
		  $infFIELDS['City']            = $ccustcity;
		  $infFIELDS['State']           = $ccuststate;
		  $infFIELDS['PostalCode']      = $ccustzip;
		  $infFIELDS['Country']         = $countries[$ccustshippingcountry]; // Como clickbank no envía el país en texto, usamos el código y sacamos el país del arreglo de paises.
		  //$infFIELDS['Phone1']          = $billPHONE;  // Clickbank al parecer no brinda el teléfono del cliente.
		  //$infFIELDS['Address2Street1'] = $shipSTREET1;
		  //$infFIELDS['Address2Street2'] = $shipSTREET2;
		  //$infFIELDS['City2']           = $shipCITY;
		  //$infFIELDS['State2']          = $shipSTATE;
		  //$infFIELDS['PostalCode2']     = $shipZIPCODE;
		  //$infFIELDS['Country2']        = $shipCOUNTRY;
		  IF (count($arrCONTACT)) : // Si el contacto ya existe en Infusionsoft, entonces actualizamos simplemente con los datos enviados por clickbank.
		    $contactID                  = $arrCONTACT[0]['Id'];
		    $uFIELDS                    = $infFIELDS;
		    $conID                      = $myApp->updateCon((int)$contactID, $uFIELDS);


		  ELSE: // Si el contacto no existe, entonces creamos uno nuevo en infusionsoft.
		    $infFIELDS['Email']         = $ccustemail;
		    $qFIELDS                    = $infFIELDS;
		    $conID                      = $myApp->addCon($qFIELDS); // Agrega el nuevo contacto 
		  ENDIF;

			// Evalua qué tipo de notificación está enviando clickbank.
		  	// Establecemos variables como falso por defecto.
			$createORDER    = false;
			$manualPMT      = false;
			IF ( $ctransaction  == 'SALE') :
			    // The purchase of a standard product or the initial purchase of recurring billing product.
			    $createORDER  = true;
			    $manualPMT    = true;
			    $asID         = $arrACTIONSET['SALE'];
			ELSEIF ($ctransaction == 'BILL') :
			    // A rebill for a recurring billing product.
			    $createORDER  = true;
			    $manualPMT    = true;
			    $asID         = $arrACTIONSET['BILL'];
			ELSEIF ($ctransaction == 'RFND') :
			    // The refunding of a standard or recurring billing product. Recurring billing products that are refunded also result in a "CANCEL-REBILL" action.
			    $asID         = $arrACTIONSET['RFND'];
			ELSEIF ($ctransaction == 'CGBK') :
			    // A chargeback for a standard or recurring product.
			    $asID         = $arrACTIONSET['CGBK'];   
			ELSEIF ($ctransaction == 'INSF') :
			    // An eCheck chargeback for a standard or recurring product.
			    $asID         = $arrACTIONSET['INSF'];  
			ELSEIF ($ctransaction == 'CANCEL-REBILL') :
			    // The cancellation of a recurring billing product. Recurring billing products that are canceled do not result in any other action.
			    $asID         = $arrACTIONSET['CANCEL-REBILL'];  
			ELSEIF ($ctransaction == 'UNCANCEL-REBILL') :
			    // Reversing the cancellation of a recurring billing product.
			    $asID         = $arrACTIONSET['UNCANCEL-REBILL']; 
			ELSEIF ($ctransaction == 'TEST') :
			    // Triggered by using the test link on the site page.
			    $createORDER  = true;
			    $manualPMT    = true;
			    $asID         = $arrACTIONSET['SALE']; 	         
			ELSE:
			    //If the http post we receive is something else, we run this action set
			    $asID         = $arrACTIONSET['UNK'];
			ENDIF;

			// Si es necesario crear una orden, la creamos y agregamos el ítem a la orden.
			/* http://help.infusionsoft.com/api-docs/invoiceservice
							Parameter Name 		Type 		Definition
							privateKey 			string 		Your Infusionsoft API key
			$conID			contactId 			int 		The Id number of the contact record this order will be connected to
			$ctransreceipt	description 		string 		The name this order will display. This is also the hyperlink to the order found on the contact's order tab
			$orderDATE		orderDate 			dateTime 	Date of order
			$leadAFF		leadAffiliateId 	int 		The Id number of the affiliate you would like placed as the lead affiliate. 0 if no affiliate should be attached
			$saleAFF		saleAffiliateId 	int 		The Id number of the affiliate you would like placed as the sale affiliate. 0 if no affiliate should be attached
			*/
		  	$leadAFF      = 0; // Blank order
			$saleAFF      = 0; // Blank order
		    $itemID       = 0; // Order item
			$itemQTY      = 1; // Order item
			$itemTYPE     = 4; // Order item
			$currentDate  = date("d-m-Y");
			$pDate = $myApp->infuDate($currentDate);	
			$payDESC        = "ClickBank receipt number: " . $ctransreceipt . " - Type of product: " . $cprodtype ; // manualPmt
			$bypassCOMM       = false; // manualPmt A boolean which tells the system if this payment should count towards what the affiliate has earned. This is almost always false.
			IF ($createORDER) :
		    	$orderID      = $myApp->blankOrder($conID, $ctransreceipt, $pDate, $leadAFF, $saleAFF); // Al final se devuelve un número de orden para usar en el siguiente paso.
		    	$orderItemID  = $myApp->addOrderItem($orderID, $itemID, $itemTYPE, (float)$corderamountUSD, $itemQTY, $cprodtitle, $cprodtitle);
		    	IF (is_bool($orderItemID)) :   // Si la orden se crea correctamente, entonces infusionsoft devuelve TRUE y en este caso hacemos el pago manual.   
		      		IF ($manualPMT) :
		        		$myApp->manualPmt($orderID, (float)$corderamountUSD, $pDate, $ctranspaymentmethod, $payDESC, $bypassCOMM);
		      		ENDIF;
		    	ENDIF;
			ENDIF;
		  $myApp->runAS((int)$conID, (int)$asID);
		ENDIF;
	} else {
		// Error en verificación, no se hace nada.
	}
?>
