
<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)>
<cftry>
	<!--- 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.Amount" default="">
	<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="">

	<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="1234ORDER">

				<!--- setup the money object with the amount --->
				<cfset money.init(form.amount * 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()>
					<cfoutput>The credit card payment was successfully processed. </cfoutput>
					<!--- 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,
																Address,
																DeliveryCharge,
																TaxChargeAmount,
																AddedOn
																	)
							values									(
																#session.UserID#,
																#form.bizid#,
																0,
																#cart_total#,
																'',
																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
							FROM dbo.Business_OrderMaster O, dbo.BusinessMaster M
							WHERE	O.BusinessID = M.BusinessID
							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 cart_total < 10>
						<cfset admin_fees_calculated = cart_total * .022>
					<cfelse>
						<cfset admin_fees_calculated = cart_total * .005 +.22>
					</cfif>

					<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#,
														'',
														'',
														#createODBCDateTime(now())#,
														#get_queued_food.CartID#
													)											
					</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>

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

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

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

					<!--- 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>
