Example #1
0
		public TransactionResult SubmitPaymentTransaction(CheckoutDetails details)
		{
			TransactionResult result = new TransactionResult();

            // 1. Process date and time variables
            string transactionNumber = DateTime.Now.ToString(TransactionNumberFormat);
            // 2. Process E-Commerce variables
            transactionNumber = transactionNumber.Replace("[INVOICE_ID]", details[CheckoutKeys.InvoiceNumber]);

			// transaction is ok
			result.Succeed = true;
			// set transation id
			result.TransactionId = transactionNumber;
			// status code is empty
			result.StatusCode = String.Empty;
			// no response available
			result.RawResponse = "No response available";

			// check payment approval setting
			if (AutoApprove)
				result.TransactionStatus = TransactionStatus.Approved;
			else
				result.TransactionStatus = TransactionStatus.Pending;

			// return result
			return result;
		}
        /// <summary>
        /// Performs checkout operation
        /// </summary>
        /// <param name="spaceId">Space.</param>
        /// <param name="gatewayId">Gateway.</param>
        /// <param name="invoiceId">Invoice.</param>
        /// <param name="details">Array of parameters.</param>
        /// <returns>Checkout result object.</returns>
        public static CheckoutResult CheckOut(string contractId, int invoiceId, string methodName,
                                              CheckoutDetails details)
        {
            CheckoutResult result = new CheckoutResult();

            try
            {
                Contract contractInfo = ContractSystem.ContractController.GetContract(contractId);
                // impersonate
                ContractSystem.ContractController.ImpersonateAsContractReseller(contractInfo);
                // TRACE
                ES.TaskManager.StartTask(TASK_SOURCE, CHECKOUT_TASK, methodName);
                ES.TaskManager.Write("Start accepting payment for invoice");
                ES.TaskManager.WriteParameter("ContractID", contractId);
                ES.TaskManager.WriteParameter("InvoiceID", invoiceId);

                // get user details
                ContractAccount account = ContractSystem.ContractController.GetContractAccountSettings(contractId);

                // try to load plugin type and throw an exception if type not found
                IPaymentGatewayProvider provider = (IPaymentGatewayProvider)SystemPluginController.GetContractPaymentMethod(
                    contractInfo, methodName);

                // add invoice details
                Invoice invoice = InvoiceController.GetCustomerInvoiceInternally(invoiceId);

                // append information for the provider
                details[CheckoutKeys.ContractNumber] = contractId;
                details[CheckoutKeys.Amount]         = invoice.Total.ToString("0.00");
                details[CheckoutKeys.InvoiceNumber]  = invoice.InvoiceNumber;
                details[CheckoutKeys.Currency]       = invoice.Currency;

                ES.TaskManager.Write("Submitting payment transaction");
                // call checkout routine
                TransactionResult pgResult = provider.SubmitPaymentTransaction(details);
                // log provider response
                SystemPluginController.LogContractPayment(contractInfo, methodName, pgResult.RawResponse);
                // ERROR
                if (!pgResult.Succeed)
                {
                    result.Succeed    = false;
                    result.StatusCode = pgResult.StatusCode;
                    //
                    ES.TaskManager.WriteError("Transaction failed");
                    ES.TaskManager.WriteParameter("StatusCode", result.StatusCode);
                    ES.TaskManager.WriteParameter("RawResponse", pgResult.RawResponse);
                    // EXIT
                    return(result);
                }
                // OK
                ES.TaskManager.Write("Transaction is OK");

                // check whether the transaction already exists
                CustomerPayment tran = StorehouseController.LookupForTransaction(pgResult.TransactionId);

                // lookup for pending transaction
                if (tran == null)
                {
                    // add payment record
                    result.PaymentId = StorehouseController.AddCustomerPayment(contractId, invoice.InvoiceId,
                                                                               pgResult.TransactionId, invoice.Total, invoice.Currency, methodName,
                                                                               pgResult.TransactionStatus);
                    // ERROR
                    if (result.PaymentId < 1)
                    {
                        result.Succeed    = false;
                        result.StatusCode = result.PaymentId.ToString();
                        //
                        ES.TaskManager.WriteError("Could not add customer payment record to the db");
                        ES.TaskManager.WriteParameter("ResultCode", result.StatusCode);
                        // EXIT
                        return(result);
                    }
                }
                // if transaction is already submitted just update it's status
                if (tran != null)
                {
                    StorehouseController.UpdateTransactionStatus(tran.PaymentId, pgResult.TransactionStatus);
                }
                // OK
                result.Succeed = true;
                // ensure user requests to persist his payment details for credit card
                if (details.Persistent && methodName == PaymentMethod.CREDIT_CARD)
                {
                    StorehouseController.SetPaymentProfile(contractId, details);
                }
            }
            catch (Exception ex)
            {
                result.Succeed    = false;
                result.StatusCode = GENERAL_FAILURE;
                //
                ES.TaskManager.WriteError(ex);
            }
            finally
            {
                ES.TaskManager.CompleteTask();
            }
            // EXIT
            return(result);
        }
Example #3
0
        public TransactionResult SubmitPaymentTransaction(CheckoutDetails details)
        {
            //init result structure
            TransactionResult ret = new TransactionResult();
            //create request content
            string data = GetRequestData(details);
            // create webrequest instance
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(ServiceUrl);

            webRequest.Method        = "POST";
            webRequest.ContentLength = data.Length;
            webRequest.ContentType   = "application/x-www-form-urlencoded";
            // send service request
            StreamWriter sw = null;

            try
            {
                sw = new StreamWriter(webRequest.GetRequestStream());
                sw.Write(data);
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
            }
            // read service response
            AIMResponse     aimResponse = null;
            HttpWebResponse webResponse = null;

            try
            {
                // get response
                webResponse = (HttpWebResponse)webRequest.GetResponse();
                // emit new response
                aimResponse = new AIMResponse(webResponse.GetResponseStream(), DELIMITER_CHAR);
            }
            finally
            {
                webResponse.Close();
                webRequest.Abort();
            }
            // copy raw service response
            ret.RawResponse = aimResponse.RawResponse;
            // read service response status
            switch (aimResponse[AIMField.ResponseCode])
            {
            case "1":                     //This transaction has been approved.
            case "4":                     //This transaction is being held for review.
                // check MD5 signature
                if (!CheckResponseSignature(Username, MD5_Hash, aimResponse[AIMField.TransactionId], details[CheckoutKeys.Amount],
                                            aimResponse[AIMField.ResponseSignature]))
                {
                    throw new Exception(MD5_INVALID_MSG);
                }
                //
                ret.Succeed = true;
                //
                ret.TransactionId = aimResponse[AIMField.TransactionId];
                // mark transaction as a completed
                ret.TransactionStatus = TransactionStatus.Approved;
                //
                break;

            case "2":                     // This transaction has been declined.
            case "3":                     // There has been an error processing this transaction.
                //
                ret.StatusCode = String.Concat(AuthorizeNetKeys.ErrorPrefix, aimResponse[AIMField.ResponseCode],
                                               aimResponse[AIMField.ResponseReasonCode]);
                //
                ret.Succeed = false;
                //
                ret.TransactionStatus = TransactionStatus.Declined;
                //
                break;
            }
            // return result
            return(ret);
        }
Example #4
0
        public TransactionResult SubmitPaymentTransaction(CheckoutDetails details)
        {
            //init result structure
            TransactionResult ret = new TransactionResult();

            //set up Request
            //instantiate DoDirectPaymentRequestType and RequestDetails objects
            DoDirectPaymentRequestType request = new DoDirectPaymentRequestType();

            request.Version = PROCESSOR_VERSION;
            DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType();

            request.DoDirectPaymentRequestDetails = requestDetails;

            //set payment action
            requestDetails.PaymentAction = PaymentActionCodeType.Sale;

            //set IP
            //requestDetails.IPAddress = Request.UserHostAddress;
            requestDetails.IPAddress = details[CheckoutKeys.IPAddress];

            //set CreditCard info
            CreditCardDetailsType creditCardDetails = new CreditCardDetailsType();

            requestDetails.CreditCard          = creditCardDetails;
            creditCardDetails.CreditCardNumber = details[CheckoutKeys.CardNumber];
            creditCardDetails.CreditCardType   = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), details[CheckoutKeys.CardType], true);
            creditCardDetails.CVV2             = details[CheckoutKeys.VerificationCode];
            creditCardDetails.ExpMonth         = Int32.Parse(details[CheckoutKeys.ExpireMonth]);
            creditCardDetails.ExpYear          = Int32.Parse(details[CheckoutKeys.ExpireYear]);
            // Switch/Solo
            if (creditCardDetails.CreditCardType == CreditCardTypeType.Solo ||
                creditCardDetails.CreditCardType == CreditCardTypeType.Switch)
            {
                creditCardDetails.StartMonth  = Int32.Parse(details[CheckoutKeys.StartMonth]);
                creditCardDetails.StartYear   = Int32.Parse(details[CheckoutKeys.StartYear]);
                creditCardDetails.IssueNumber = details[CheckoutKeys.IssueNumber];
            }

            //set billing address
            PayerInfoType cardOwner = new PayerInfoType();

            creditCardDetails.CardOwner   = cardOwner;
            cardOwner.PayerName           = new PersonNameType();
            cardOwner.PayerName.FirstName = details[CheckoutKeys.FirstName];
            cardOwner.PayerName.LastName  = details[CheckoutKeys.LastName];

            cardOwner.Address         = new AddressType();
            cardOwner.Address.Street1 = details[CheckoutKeys.Address];
            //??? cardOwner.Address.Street2 = "";
            cardOwner.Address.CityName         = details[CheckoutKeys.City];
            cardOwner.Address.StateOrProvince  = details[CheckoutKeys.State];
            cardOwner.Address.PostalCode       = details[CheckoutKeys.Zip];
            cardOwner.Address.CountrySpecified = true;
            cardOwner.Address.Country          = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), details[CheckoutKeys.Country], true);

            //set payment Details
            PaymentDetailsType paymentDetails = new PaymentDetailsType();

            requestDetails.PaymentDetails = paymentDetails;
            paymentDetails.OrderTotal     = new BasicAmountType();
            //TODO: Add currency support
            paymentDetails.OrderTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), details[CheckoutKeys.Currency]);
            //paymentDetails.OrderTotal.currencyID = CurrencyCodeType.USD;
            //No currency symbol. Decimal separator must be a period (.), and the thousands separator must be a comma (,)
            paymentDetails.OrderTotal.Value = details[CheckoutKeys.Amount];

            DoDirectPaymentReq paymentRequest = new DoDirectPaymentReq();

            paymentRequest.DoDirectPaymentRequest = request;

            //FINISH set up req
            //setup request Header, API credentials
            PayPalAPIAASoapBinding paypalInterface = new PayPalAPIAASoapBinding();
            UserIdPasswordType     user            = new UserIdPasswordType();

            //set api credentials - username, password, signature
            user.Username  = Username;
            user.Password  = Password;
            user.Signature = Signature;
            // setup service url
            paypalInterface.Url = ServiceUrl;
            paypalInterface.RequesterCredentials             = new CustomSecurityHeaderType();
            paypalInterface.RequesterCredentials.Credentials = user;

            //make call return response
            DoDirectPaymentResponseType paymentResponse = new DoDirectPaymentResponseType();

            paymentResponse = paypalInterface.DoDirectPayment(paymentRequest);
            //write response xml to the ret object
            ret.RawResponse = SerializeObject(paymentResponse);

            switch (paymentResponse.Ack)
            {
            case AckCodeType.Success:
            case AckCodeType.SuccessWithWarning:
                ret.Succeed           = true;
                ret.TransactionId     = paymentResponse.TransactionID;
                ret.TransactionStatus = TransactionStatus.Approved;
                break;

            default:                     // show errors if Ack is NOT Success
                ret.Succeed           = false;
                ret.TransactionStatus = TransactionStatus.Declined;
                if (paymentResponse.Errors != null &&
                    paymentResponse.Errors.Length > 0)
                {
                    ret.StatusCode = PayPalProKeys.ErrorPrefix + paymentResponse.Errors[0].ErrorCode;
                }
                break;
            }
            return(ret);
        }
Example #5
0
 private void Process_PDT_Request(TransactionResult result, CheckoutDetails details)
 {
 }
		private void Process_IPN_Request(TransactionResult result, CheckoutDetails details)
		{
			result.RawResponse = "";

			// build raw response
			foreach (string keyName in details.GetAllKeys())
			{
				if (String.IsNullOrEmpty(keyName))
					continue;

				// check for separator
				if (!String.IsNullOrEmpty(result.RawResponse) && 
					!result.RawResponse.EndsWith("&"))
					result.RawResponse += "&";

				result.RawResponse += keyName + "=" + details[keyName];
			}
			// compare business account against email addres in response
			if (!String.Equals(details["receiver_email"], Business, StringComparison.InvariantCultureIgnoreCase))
				throw new Exception(BUSINESS_NOT_MATCH_MSG);

			// validate whether response still genuine
			if(!IsResponseGenuine(result.RawResponse))
				throw new Exception(INVALID_RESPONSE_MSG);
			// build tran id
			string transactionId = details["txn_id"];
			// check payment status
			switch(details["payment_status"])
			{
				case "Completed":
				case "Processed":
					result.Succeed = true;
					// store order details
					result.TransactionId = transactionId;
					result.TransactionStatus = TransactionStatus.Approved;
					break;
				case "Pending":
					result.Succeed = true;
					// store order details
					result.TransactionId = transactionId;
					result.TransactionStatus = TransactionStatus.Pending;
					break;
				default:
					result.Succeed = false;
					result.TransactionStatus = TransactionStatus.Declined;
					break;
			}
		}
		private void Process_PDT_Request(TransactionResult result, CheckoutDetails details)
		{

		}
		public TransactionResult SubmitPaymentTransaction(CheckoutDetails details)
		{
			//init result structure
			TransactionResult result = new TransactionResult();
			// check is request genuine depending on the provider mode
			Process_IPN_Request(result, details);
			//
			return result;
		}
Example #9
0
		public TransactionResult SubmitPaymentTransaction(CheckoutDetails details)
		{
			TransactionResult result = new TransactionResult();
			// build raw response for 2CO
			string[] keys = details.GetAllKeys();
			List<string> bunch = new List<string>();
			// copy checkout details
			foreach (string key in keys)
			{
				bunch.Add(String.Concat(key, "=", details[key]));
			}
			// build raw 2CO response
			result.RawResponse = String.Join("|", bunch.ToArray());
			// recognize credit card status
            switch(details[CREDIT_CARD_PROCESSED])
            {
                case "Y":
                    result.TransactionStatus = TransactionStatus.Approved;
                    break;
                case "K":
                    result.TransactionStatus = TransactionStatus.Pending;
                    break;
                default:
                    throw new Exception(CC_PROCESSED_ERROR_MSG);
            }
			// read order number
			string order_number = details["order_number"];
			// check demo mode: set order number to 1
			// according to 2Checkout documentation for demo transactions
			
			bool valid = false;
			// validate TCO key
			if (LiveMode) // do live validation
				valid = ValidateKey(SecretWord, AccountSID, order_number, details[CheckoutKeys.Amount], details[KEY]);
			else // do demo validation
				valid = ValidateKey(SecretWord, AccountSID, "1", details[CheckoutKeys.Amount], details[KEY]);

			// key validation failed
			if (!valid)
				throw new ArgumentException(KEY_VALIDATION_FAILED_MSG);
			// we are succeed copy order number
			result.TransactionId = order_number;
			//
			result.Succeed = true;
			// return result
			return result;
		}
		public TransactionResult SubmitPaymentTransaction(CheckoutDetails details)
		{
			//init result structure
			TransactionResult ret = new TransactionResult();

			//set up Request
			//instantiate DoDirectPaymentRequestType and RequestDetails objects
			DoDirectPaymentRequestType request = new DoDirectPaymentRequestType();
			request.Version = PROCESSOR_VERSION;
			DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType();
			request.DoDirectPaymentRequestDetails = requestDetails;

			//set payment action
			requestDetails.PaymentAction = PaymentActionCodeType.Sale;

			//set IP
			//requestDetails.IPAddress = Request.UserHostAddress;
			requestDetails.IPAddress = details[CheckoutKeys.IPAddress];

			//set CreditCard info
			CreditCardDetailsType creditCardDetails = new CreditCardDetailsType();
			requestDetails.CreditCard = creditCardDetails;
			creditCardDetails.CreditCardNumber = details[CheckoutKeys.CardNumber];
			creditCardDetails.CreditCardType = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), details[CheckoutKeys.CardType], true);
			creditCardDetails.CVV2 = details[CheckoutKeys.VerificationCode];
			creditCardDetails.ExpMonth = Int32.Parse(details[CheckoutKeys.ExpireMonth]);
			creditCardDetails.ExpYear = Int32.Parse(details[CheckoutKeys.ExpireYear]);
			// Switch/Solo
			if (creditCardDetails.CreditCardType == CreditCardTypeType.Solo ||
				creditCardDetails.CreditCardType == CreditCardTypeType.Switch)
			{
				creditCardDetails.StartMonth = Int32.Parse(details[CheckoutKeys.StartMonth]);
				creditCardDetails.StartYear = Int32.Parse(details[CheckoutKeys.StartYear]);
				creditCardDetails.IssueNumber = details[CheckoutKeys.IssueNumber];
			}

			//set billing address
			PayerInfoType cardOwner = new PayerInfoType();
			creditCardDetails.CardOwner = cardOwner;
			cardOwner.PayerName = new PersonNameType();
			cardOwner.PayerName.FirstName = details[CheckoutKeys.FirstName];
			cardOwner.PayerName.LastName = details[CheckoutKeys.LastName];

			cardOwner.Address = new AddressType();
			cardOwner.Address.Street1 = details[CheckoutKeys.Address];
			//??? cardOwner.Address.Street2 = "";
			cardOwner.Address.CityName = details[CheckoutKeys.City];
			cardOwner.Address.StateOrProvince = details[CheckoutKeys.State];
			cardOwner.Address.PostalCode = details[CheckoutKeys.Zip];
			cardOwner.Address.CountrySpecified = true;
			cardOwner.Address.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), details[CheckoutKeys.Country], true);

			//set payment Details
			PaymentDetailsType paymentDetails = new PaymentDetailsType();
			requestDetails.PaymentDetails = paymentDetails;
			paymentDetails.OrderTotal = new BasicAmountType();
			//TODO: Add currency support
			paymentDetails.OrderTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), details[CheckoutKeys.Currency]);
			//paymentDetails.OrderTotal.currencyID = CurrencyCodeType.USD;
			//No currency symbol. Decimal separator must be a period (.), and the thousands separator must be a comma (,)
			paymentDetails.OrderTotal.Value = details[CheckoutKeys.Amount];

			DoDirectPaymentReq paymentRequest = new DoDirectPaymentReq();
			paymentRequest.DoDirectPaymentRequest = request;

			//FINISH set up req
			//setup request Header, API credentials
			PayPalAPIAASoapBinding paypalInterface = new PayPalAPIAASoapBinding();
			UserIdPasswordType user = new UserIdPasswordType();

			//set api credentials - username, password, signature
			user.Username = Username;
			user.Password = Password;
			user.Signature = Signature;
			// setup service url
			paypalInterface.Url = ServiceUrl;
			paypalInterface.RequesterCredentials = new CustomSecurityHeaderType();
			paypalInterface.RequesterCredentials.Credentials = user;

			//make call return response
			DoDirectPaymentResponseType paymentResponse = new DoDirectPaymentResponseType();
			paymentResponse = paypalInterface.DoDirectPayment(paymentRequest);
			//write response xml to the ret object
			ret.RawResponse = SerializeObject(paymentResponse);
			
			switch (paymentResponse.Ack)
			{
				case AckCodeType.Success:
				case AckCodeType.SuccessWithWarning:
					ret.Succeed = true;
					ret.TransactionId = paymentResponse.TransactionID;
					ret.TransactionStatus = TransactionStatus.Approved;
					break;
				default: // show errors if Ack is NOT Success
					ret.Succeed = false;
					ret.TransactionStatus = TransactionStatus.Declined;
					if (paymentResponse.Errors != null &&
						paymentResponse.Errors.Length > 0)
					{
						ret.StatusCode = PayPalProKeys.ErrorPrefix + paymentResponse.Errors[0].ErrorCode;
					}
					break;
			}
			return ret;
		}
		public TransactionResult SubmitPaymentTransaction(CheckoutDetails details)
		{
			//init result structure
			TransactionResult ret = new TransactionResult();
			//create request content
			string data = GetRequestData(details);
			// create webrequest instance
			HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(ServiceUrl);
			webRequest.Method = "POST";
			webRequest.ContentLength = data.Length;
			webRequest.ContentType = "application/x-www-form-urlencoded";
			// send service request
			StreamWriter sw = null;
			try
			{
				sw = new StreamWriter(webRequest.GetRequestStream());
				sw.Write(data);
			}
			finally
			{
				if (sw != null)
					sw.Close();
			}
			// read service response
			AIMResponse aimResponse = null;
			HttpWebResponse webResponse = null;
			try
			{
				// get response
				webResponse = (HttpWebResponse)webRequest.GetResponse();
				// emit new response
				aimResponse = new AIMResponse(webResponse.GetResponseStream(), DELIMITER_CHAR);
			}
			finally
			{
				webResponse.Close();
				webRequest.Abort();
			}
			// copy raw service response
			ret.RawResponse = aimResponse.RawResponse;
			// read service response status
			switch (aimResponse[AIMField.ResponseCode])
			{
				case "1": //This transaction has been approved.
				case "4": //This transaction is being held for review.
					// check MD5 signature
					if (!CheckResponseSignature(Username, MD5_Hash, aimResponse[AIMField.TransactionId], details[CheckoutKeys.Amount],
						aimResponse[AIMField.ResponseSignature]))
					{
						throw new Exception(MD5_INVALID_MSG);
					}
					//
					ret.Succeed = true;
					//
					ret.TransactionId = aimResponse[AIMField.TransactionId];
					// mark transaction as a completed
					ret.TransactionStatus = TransactionStatus.Approved;
					//
					break;
				case "2": // This transaction has been declined.
				case "3": // There has been an error processing this transaction.
					//
					ret.StatusCode = String.Concat(AuthorizeNetKeys.ErrorPrefix, aimResponse[AIMField.ResponseCode], 
						aimResponse[AIMField.ResponseReasonCode]);
					//
					ret.Succeed = false;
					//
					ret.TransactionStatus = TransactionStatus.Declined;
					//
					break;
			}
			// return result
			return ret;
		}