
<cftry>
	<!--- create a config that is not in svn --->
	<cfscript>
		cfg = { path = "cfpayment.api.gateway.stripe.stripe", TestSecretKey = "sk_test_LfbmDduJxTwbVZmvcByYmirw" };
		svc = createObject("component", "cfpayment.api.core").init(cfg);
	</cfscript>
<cfcatch>
	<!--- if gwParams doesn't exist (or otherwise bombs), create a generic structure with blank values --->
	<cfset gwParams = StructNew() />
	<cfset gwParams.Path = "bogus.gateway" />
	<!--- these following params aren't needed for the bogus gateway, but should normally be filled in --->
	<cfset gwParams.MerchantAccount = "" />
	<cfset gwParams.userName = "" />
	<cfset gwParams.password = "" />
</cfcatch>
</cftry>

<!--- create gw and get reference --->
<cfset gw = svc.getGateway() />
<cfset creditcard = svc.createCreditCard()>
<cfset money = svc.createMoney()>
<cfset errors=ArrayNew(1)>
<!--- Initialize Form Variables --->
<cfparam name="form.BillingFirstName" default="">
<cfparam name="form.BillingLastName" default="">
<cfparam name="form.BillingAddressOne" default="">
<cfparam name="form.BillingCity" default="">
<cfparam name="form.BillingState" default="">
<cfparam name="form.BillingZip" default="">
<cfparam name="form.BillingCountry" default="">
<cfparam name="form.BillingPhoneNumber" default="">
<cfparam name="form.BillingEmailAddress" default="">
<cfparam name="form.orderID" default="1">


<cfparam name="form.Amount" default="1">
<cfparam name="form.CardNumber" default="">
<cfparam name="form.CardType" default="">
<cfparam name="form.ExpirationMonth" default="">
<cfparam name="form.ExpirationYear" default="">
<cfparam name="form.TransactionType" default="SALE">
<cfparam name="form.cvv2" default="">
<cftry>
	

	<cfif structKeyExists(form, "submitBtn")>
		<!--- PROCESS --->
		<cftry>
			<!--- populate credit card object with passed data --->
			<cfset ccObjList="Account,Month,Year,VerificationValue,FirstName,LastName,Address,PostalCode">
			<cfset formFieldList="CardNumber,ExpirationMonth,ExpirationYear,cvv2,BillingFirstName,BillingLastName,BillingAddressOne,BillingZip">
			<cfset numFields=ListLen(ccObjList)>
			<cfloop from="1" to="#numFields#" index="idx">
				<cfset currCCField=ListGetAt(ccObjList, idx)>
				<cfset currFormField=ListGetAt(formFieldList, idx)>
				<cfinvoke component="#creditcard#" method="set#currCCField#">
					<cfinvokeargument name="#currCCField#" value="#form[currFormField]#" />
				</cfinvoke>
			</cfloop>
			<!--- validate credit card --->
			<cfset errors=creditCard.validate()>
			<cfif not ArrayLen(errors)>
				<!--- gateway specific parameters --->
				<!--- for example, the skipjack gateway requires email, phonenumber and ordernumber; these are passed in the options struct --->
				<cfset options=StructNew()>
				<cfset options.address=StructNew()>
				<cfset options.email=form.BillingEmailAddress>
				<!--- send through generic address structure --->
				<cfset options.address.phone=form.BillingPhoneNumber>
				<cfset options.address.Address1=form.BillingAddressOne>
				<cfset options.address.City=form.BillingCity>
				<cfset options.address.State=form.BillingState>
				<cfset options.address.PostalCode=form.BillingZip>
				<cfset options.address.Country=form.BillingCountry>
				<cfset options.order_id=form.orderID>

				<!--- setup the money object with the amount --->
				<cfset money.init( 100)><!--- in cents --->
				
				<!--- send authorize command --->
				<!--- pass in the money object, the creditcard object, extra parameters required by the specific gateway --->
				<cfset authResponse=gw.purchase(money, creditCard)>
				
				<!--- process response --->
				
				<cfif authResponse.getSuccess()>
					<!---- TODO use stcResult to get the data post payment. ---->
					<cfset stcResult  = {
						id = authResponse.getParsedResult().id,
						amount = round(authResponse.getParsedResult().amount)/100,
						message = authResponse.getParsedResult().outcome.seller_message,
						receipt_url = authResponse.getParsedResult().receipt_url,
						status =  authResponse.getParsedResult().status
					}>

					<cfoutput>The credit card payment was successfully processed. <br><br>
					Your receipt can be found <a href="#stcResult.receipt_url#" target="new">here.</a><br><br></cfoutput>

					<!--- <cfdump var=#stcResult#>

					TODO: you should now do something (record, redirect, etc.) --->

					<!--- <cfdump var="#deserializeJSON(authResponse.getResult())#" label="getResult">
					<cfdump var="#authResponse.getParsedResult()#" label="getParsedResult">
					<cfif isdefined("arguments")><cfdump var="#arguments#" label="Arguments Scope"></cfif>
					<cfif isdefined("attributes")><cfdump var="#attributes#" label="Attributes Scope"></cfif>
					<cfif isdefined("CGI")><cfdump var="#CGI#" label="CGI Scope"></cfif>
					<cfif isdefined("Request")><cfdump var="#Request#" label="Request Scope"></cfif>
					<cfif isdefined("URL")><cfdump var="#URL#" label="URL Scope"></cfif>
					<cfif isdefined("Form")><cfdump var="#Form#" label="Form Scope"></cfif>
					<cfif isdefined("session")><cfdump var="#Session#" label="Session Scope"></cfif> --->

					<!--- do the rest of the stuff --->

					<cfset cart_total = 0>

					<CFQUERY name="get_queued_food" datasource="#application.datasource#" dbtype="ODBC">
						SELECT      A.CartID, A.AddedOn, A.Quantity, A.SpecialRemark, B.BusinessName, B.UserID, C.ItemName, A.Price, D.UserFirstName, D.LaerFirstName, D.Balance
						FROM        dbo.Business_CartMaster A, dbo.BusinessMaster B, dbo.Business_ItemMaster C, Users D
						WHERE		A.UserID = D.UserID
										AND
									A.ItemID = C.ItemID
										AND
									B.BusinessID = C.BusinessID
										AND
									C.BusinessID = #form.bizid#
										AND
									A.CartStatusID = 1
										AND
									A.UserID = #session.UserID#
						ORDER BY	A.AddedOn DESC
					</CFQUERY>

					<cfoutput query="get_queued_food">

						<cfif len(get_queued_food.Price) EQ 0><cfset get_queued_food.Price=0></cfif>

						<cfset cart_total = (cart_total + (get_queued_food.price*get_queued_food.quantity))>

						<CFQUERY name="update_cart_items" datasource="#application.datasource#" dbtype="ODBC">
							UPDATE		dbo.Business_CartMaster
							SET			CartStatusID=2
							WHERE		CartID=#get_queued_food.CartID#
						</CFQUERY>				

						<CFQUERY name="Insert_order" datasource="#application.datasource#" dbtype="ODBC">
							INSERT Into dbo.Business_OrderMaster	(
																UserID,
																BusinessID,
																IsDelivery,
																TotalAmount,
																Remark,
																Address,
																DeliveryCharge,
																TaxChargeAmount,
																AddedOn
																	)
							values									(
																#session.UserID#,
																#form.bizid#,
																0,
																#cart_total#,
																'#form.SpecialRemark#',
																'',
																0,
																0,
																#CreateODBCDateTime(now())#
																	);
						</CFQUERY>

						<CFQUERY name="get_last_inserted" datasource="#application.datasource#" dbtype="ODBC">
							SELECT TOP 1 O.OrderID, M.UserID as person_to_pay_for_orderID, U.Balance
							FROM dbo.Business_OrderMaster O, dbo.BusinessMaster M, Users U
							WHERE	O.BusinessID = M.BusinessID
										AND 
									M.UserID = U.UserID
							ORDER BY O.AddedOn DESC
						</CFQUERY>

						<CFQUERY name="link_order" datasource="#application.datasource#" dbtype="ODBC">
							INSERT INTO dbo.Business_OrderCartTransaction	(
																	OrderID,
																	CartID
																			)
							VALUES	
																			(
																	#get_last_inserted.OrderID#,
																	#get_queued_food.CartID#
																			)
						</CFQUERY>

					</cfoutput>

					<cfif payment_mode eq "account">

						<cfif cart_total < 10>
							<cfset admin_fees_calculated = cart_total * .022>
						<cfelse>
							<cfset admin_fees_calculated = cart_total * .005 +.215>
						</cfif>

					<cfelseif payment_mode eq "mixed">

						<cfif cart_total-get_queued_food.balance < 10>
							<cfset admin_fees_calculated = (cart_total-get_queued_food.balance) * .022>
						<cfelse>
							<cfset admin_fees_calculated = (cart_total-get_queued_food.balance) * .005 +.215>
						</cfif>

					<cfelseif payment_mode eq "creditcard">

						<cfset admin_fees_calculated = 0>

					<cfelse>

						problem! what is the payment_mode?<br><br>

					</cfif>

					<cfif payment_mode eq "account">

						<CFQUERY name="insert_payment" datasource="#application.datasource#" dbtype="ODBC">
							INSERT INTO dbo.PaymentMaster (
															ReceiverID,
															PayUserID,
															BusinessID,
															Amount,
															AdminFees,
															PayUserRemark,
															SystemRemark,
															AddedOn,
															CartID,
															PaymentReceiptURL
														)
										VALUES			(
															#get_last_inserted.person_to_pay_for_orderID#,
															#session.UserID#,
															#form.bizid#,
															#cart_total-admin_fees_calculated#,
															#admin_fees_calculated#,
															'',
															'from account balance',
															#createODBCDateTime(now())#,
															#get_queued_food.CartID#,
															'#stcResult.receipt_url#'
														)											
						</CFQUERY>

						<CFQUERY name="delete_item_cost" datasource="#application.datasource#" dbtype="ODBC">
							UPDATE Users
							SET balance = #check_user.balance-cart_total#
							WHERE UserID = #session.UserID#
						</CFQUERY>

						<cfif cart_total < 10>
							<cfset admin_fees_calculated = cart_total * .022>
						<cfelse>
							<cfset admin_fees_calculated = cart_total * .005 +.215>
						</cfif>

						<CFQUERY name="transfer_money_to_business_creators_UserID" datasource="#application.datasource#" dbtype="ODBC">
							UPDATE Users
							SET balance = #get_last_inserted.balance+(cart_total-admin_fees_calculated)#
							WHERE UserID = #get_last_inserted.person_to_pay_for_orderID#
						</CFQUERY>					

						<CFQUERY name="get_user_104_balance" datasource="#application.datasource#" dbtype="ODBC">
							SELECT			balance
							FROM			Users
							WHERE			UserID = 104
						</CFQUERY>

						<CFQUERY name="transfer_fees_to_UserID_104" datasource="#application.datasource#" dbtype="ODBC">
							UPDATE Users
							SET balance = #get_user_104_balance.balance+admin_fees_calculated#
							WHERE UserID = 104
						</CFQUERY>

					<cfelseif payment_mode eq "mixed">
						
						<cfset card_fee = (cart_total-get_queued_food.balance/.9725)*.0275+.30>

						<CFQUERY name="insert_account_payment" datasource="#application.datasource#" dbtype="ODBC">
							INSERT INTO dbo.PaymentMaster (
															ReceiverID,
															PayUserID,
															BusinessID,
															Amount,
															AdminFees,
															PayUserRemark,
															SystemRemark,
															AddedOn,
															CartID
														)
										VALUES			(
															#get_last_inserted.person_to_pay_for_orderID#,
															#session.UserID#,
															#form.bizid#,
															#get_queued_food.balance#,
															#admin_fees_calculated#,
															'',
															'mixed - from account balance #dollarformat(get_queued_food.balance)#',
															#createODBCDateTime(now())#,
															#get_queued_food.CartID#
														)											
						</CFQUERY>

						<CFQUERY name="insert_cc_payment" datasource="#application.datasource#" dbtype="ODBC">
							INSERT INTO dbo.PaymentMaster (
															ReceiverID,
															PayUserID,
															BusinessID,
															Amount,
															AdminFees,
															PayUserRemark,
															SystemRemark,
															AddedOn,
															CartID
														)
										VALUES			(
															#get_last_inserted.person_to_pay_for_orderID#,
															#session.UserID#,
															#form.bizid#,
															#cart_total-get_queued_food.balance#,
															0,
															'',
															'mixed - from credit card #dollarformat(amount)#',
															#createODBCDateTime(now())#,
															#get_queued_food.CartID#
														)											
						</CFQUERY>

						<CFQUERY name="delete_item_cost" datasource="#application.datasource#" dbtype="ODBC">
							UPDATE Users
							SET balance = 0
							WHERE UserID = #session.UserID#
						</CFQUERY>

						<CFQUERY name="transfer_money_to_business_creators_UserID" datasource="#application.datasource#" dbtype="ODBC">
							UPDATE Users
							SET balance = #get_last_inserted.balance+(cart_total-admin_fees_calculated)#
							WHERE UserID = #get_last_inserted.person_to_pay_for_orderID#
						</CFQUERY>			

						<CFQUERY name="get_user_104_balance" datasource="#application.datasource#" dbtype="ODBC">
							SELECT			balance
							FROM			Users
							WHERE			UserID = 104
						</CFQUERY>

						<CFQUERY name="transfer_fees_to_UserID_104" datasource="#application.datasource#" dbtype="ODBC">
							UPDATE Users
							SET balance = #get_user_104_balance.balance+admin_fees_calculated#
							WHERE UserID = 104
						</CFQUERY>

					<cfelseif payment_mode eq "creditcard"> <!--- credit card --->

						<CFQUERY name="insert_payment" datasource="#application.datasource#" dbtype="ODBC">
							INSERT INTO dbo.PaymentMaster (
															ReceiverID,
															PayUserID,
															BusinessID,
															Amount,
															AdminFees,
															PayUserRemark,
															SystemRemark,
															AddedOn,
															CartID
														)
										VALUES			(
															#get_last_inserted.person_to_pay_for_orderID#,
															#session.UserID#,
															#form.bizid#,
															#cart_total-admin_fees_calculated#,
															#admin_fees_calculated#,
															'',
															'from credit card',
															#createODBCDateTime(now())#,
															#get_queued_food.CartID#
														)											
						</CFQUERY>

						<CFQUERY name="transfer_money_to_business_creators_UserID" datasource="#application.datasource#" dbtype="ODBC">
							UPDATE Users
							SET balance = #get_last_inserted.balance+(cart_total-admin_fees_calculated)#
							WHERE UserID = #get_last_inserted.person_to_pay_for_orderID#
						</CFQUERY>

					<cfelse>

						problem! what is the payment_mode?<br><br><cfabort>

					</cfif>

					<div align="center">Order Complete!<br><br><a href="index.cfm">Reload</a> for new balance<br><br>

					<!--- end additional stuff --->

					<cfoutput>

						<script language="JavaScript">
							function submitformfunctionaddstuff()
							{
							document.myformcartadd.submit();
							}
						</script>
						
						<form action="#request.cgiPath#" method="post" name="myformcartadd" id="myformcartadd" style="display:inline;">
							
							<a href="javascript: submitformfunctionaddstuff()">Add Stuff</a>
							
							<input type="hidden" name="mode" value="start">
						
						</form><br><br>

					</cfoutput>

					<!--- end do the rest of the stuff --->
					
				<cfelse>
					<!--- add the gateway errors to any existing errors we are tracking (eg. creditcard object errors) --->
					<cfset ArrayAppend(errors, authResponse.getMessage())>
				</cfif>
			</cfif>
			<!--- if we get here, there were errors --->
			<!--- <cfdump var="#errors.getErrors()#"> --->
		<cfcatch type="cfpayment">

			<!--- <cfdump var="#cfcatch#"><cfabort> --->
			<cfset ArrayAppend(errors, cfcatch.message)>
		</cfcatch>
		<cfcatch>

			<!--- <cfdump var="#cfcatch#"><cfabort> --->
			<cfset ArrayAppend(errors, cfcatch.message)>
		</cfcatch>
		</cftry>
	</cfif>

<cfcatch>
	<cfoutput>Initialization Error - Credit Card Payment Form</cfoutput>
	<!--- TODO: this should be e-mailed or logged somewhere --->
	<cfdump var="#CFCatch#" label="CFCatch Scope">
	<cfif isdefined("arguments")><cfdump var="#arguments#" label="Arguments Scope"></cfif>
	<cfif isdefined("attributes")><cfdump var="#attributes#" label="Attributes Scope"></cfif>
	<cfif isdefined("CGI")><cfdump var="#CGI#" label="CGI Scope"></cfif>
	<cfif isdefined("Request")><cfdump var="#Request#" label="Request Scope"></cfif>
	<cfif isdefined("URL")><cfdump var="#URL#" label="URL Scope"></cfif>
	<cfif isdefined("Form")><cfdump var="#Form#" label="Form Scope"></cfif>
	<cfif isdefined("session")><cfdump var="#Session#" label="Session Scope"></cfif>
	<cfabort>
</cfcatch>
</cftry>
