当前位置: 首页>>代码示例>>C#>>正文


C# IInvoice.CurrencyCode方法代码示例

本文整理汇总了C#中IInvoice.CurrencyCode方法的典型用法代码示例。如果您正苦于以下问题:C# IInvoice.CurrencyCode方法的具体用法?C# IInvoice.CurrencyCode怎么用?C# IInvoice.CurrencyCode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IInvoice的用法示例。


在下文中一共展示了IInvoice.CurrencyCode方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ProcessPayment

        /// <summary>
        ///     Processes the Authorize and AuthorizeAndCapture transactions
        /// </summary>
        /// <param name="invoice">The <see cref="IInvoice" /> to be paid</param>
        /// <param name="payment">The <see cref="IPayment" /> record</param>
        /// <param name="transactionMode">Authorize or AuthorizeAndCapture</param>
        /// <param name="amount">The money amount to be processed</param>
        /// <returns>The <see cref="IPaymentResult" /></returns>
        public IPaymentResult ProcessPayment(IInvoice invoice, IPayment payment, TransactionMode transactionMode, decimal amount)
        {
            if (!IsValidCurrencyCode(invoice.CurrencyCode()))
            return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Invalid currency. Invoice Currency: '{0}'", invoice.CurrencyCode()))), invoice, false);

              if (transactionMode == TransactionMode.Authorize) {

            //var paymentId = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.QuickpayPaymentId);
            var currency = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.PaymentCurrency);
            var amountAuthorizedMinorString = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.PaymentAmount);
            var amountAuthorized = decimal.Parse(amountAuthorizedMinorString) / (IsZeroDecimalCurrency(currency) ? 100 : 1);

            if (invoice.CurrencyCode() != currency) {
              return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Currency mismatch. Invoice Currency: {0}, Payment Currency: {1}", invoice.CurrencyCode(), currency))), invoice, false);
            }

            if (invoice.Total > amountAuthorized) {
              return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Amount mismatch. Invoice Amount: {0}, Payment Amount: {1}", invoice.Total.ToString("F2"), amountAuthorized.ToString("F2")))), invoice, false);
            }

            payment.Authorized = true;

            return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, invoice.ShippingLineItems().Any());
              }

              return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("{0}", "QuickPay Payment AuthorizeAndCapture Not Implemented Yet"))), invoice, false);
        }
开发者ID:joelbhansen,项目名称:MerchelloQuickPayProvider,代码行数:35,代码来源:QuickPayPaymentProcessor.cs

示例2: ProcessPayment

        /// <summary>
        ///     Processes the Authorize and AuthorizeAndCapture transactions
        /// </summary>
        /// <param name="invoice">The <see cref="IInvoice" /> to be paid</param>
        /// <param name="payment">The <see cref="IPayment" /> record</param>
        /// <param name="transactionMode">Authorize or AuthorizeAndCapture</param>
        /// <param name="amount">The money amount to be processed</param>
        /// <param name="creditCard">The <see cref="CreditCardFormData" /></param>
        /// <returns>The <see cref="IPaymentResult" /></returns>
        public IPaymentResult ProcessPayment(IInvoice invoice, IPayment payment, TransactionMode transactionMode,
            decimal amount, CreditCardFormData creditCard)
        {
            if (!IsValidCurrencyCode(invoice.CurrencyCode()))
                return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception("Invalid currency")), invoice,
                    false);

            // The minimum amount is $0.50 (or equivalent in charge currency).
            // Test that the payment meets the minimum amount (for USD only).
            if (invoice.CurrencyCode() == "USD")
            {
                if (amount < 0.5m)
                    return
                        new PaymentResult(
                            Attempt<IPayment>.Fail(payment, new Exception("Invalid amount (less than 0.50 USD)")),
                            invoice, false);
            }
            else
            {
                if (amount < 1)
                    return
                        new PaymentResult(
                            Attempt<IPayment>.Fail(payment,
                                new Exception("Invalid amount (less than 1 " + invoice.CurrencyCode() + ")")),
                            invoice, false);
            }

            var requestParams = StripeHelper.PreparePostDataForProcessPayment(invoice.GetBillingAddress(), transactionMode,
                ConvertAmount(invoice, amount), invoice.CurrencyCode(), creditCard, invoice.PrefixedInvoiceNumber(),
                string.Format("Full invoice #{0}", invoice.PrefixedInvoiceNumber()));

            // https://stripe.com/docs/api#create_charge
            try
            {
                var response = StripeHelper.MakeStripeApiRequest("https://api.stripe.com/v1/charges", "POST", requestParams, _settings);
                return GetProcessPaymentResult(invoice, payment, response);
            }
            catch (WebException ex)
            {
                return GetProcessPaymentResult(invoice, payment, (HttpWebResponse) ex.Response);
            }
        }
开发者ID:vonbv,项目名称:MerchelloStripeProvider,代码行数:51,代码来源:StripePaymentProcessor.cs

示例3: PriorAuthorizeCapturePayment

        public IPaymentResult PriorAuthorizeCapturePayment(IInvoice invoice, IPayment payment, decimal amount)
        {
            var api = new QuickPayApi(_settings.ApiKey);
              var paymentId = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.QuickpayPaymentId);
              //var amountMinor = int.Parse(payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.QuickpayPaymentAmount));
              var amountMinor = IsZeroDecimalCurrency(invoice.CurrencyCode()) ? amount.ToString("F0") : (amount * 100).ToString("F0");

              try {
            var captureResult = api.CapturePayment(paymentId, amountMinor);

            if (captureResult.Accepted && captureResult.Operations.Any(x => x.Type == "capture" && x.Amount.ToString("F0") == amountMinor)) {
              LogHelper.Info<QuickPayPaymentProcessor>(string.Format("QuickPay Capture PaymentId {0} Success:\r\n{1}", paymentId, captureResult));
              return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, invoice.ShippingLineItems().Any());
            } else {
              LogHelper.Info<QuickPayPaymentProcessor>(string.Format("QuickPay Capture PaymentId {0} Error:\r\n{1}", paymentId, captureResult));
              return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("{0}", "QuickPay unknown error"))), invoice, false);
            }
              } catch (Exception x) {
            LogHelper.Error<QuickPayPaymentProcessor>(string.Format("QuickPay Capture PaymentId {0} Error:\r\n{1}", paymentId, x.Message), x);
            return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("{0}", "QuickPay unknown error"))), invoice, false);
              }
        }
开发者ID:joelbhansen,项目名称:MerchelloQuickPayProvider,代码行数:22,代码来源:QuickPayPaymentProcessor.cs

示例4: CapturePayment

		public IPaymentResult CapturePayment(IInvoice invoice, IPayment payment, decimal amount, bool isPartialPayment)
		{
			var service = GetPayPalService();
			var authorizationId = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.AuthorizationId);
			var currency = PayPalCurrency(invoice.CurrencyCode());
			var currencyDecimals = CurrencyDecimals(currency);
			
			// do express checkout
			var doCaptureRequest = new DoCaptureRequestType() 
				{
					AuthorizationID = authorizationId,
					Amount = new BasicAmountType(currency, PriceToString(amount, currencyDecimals)),
					CompleteType = (isPartialPayment ? CompleteCodeType.NOTCOMPLETE : CompleteCodeType.COMPLETE)
				};
			var doCaptureReq = new DoCaptureReq() { DoCaptureRequest = doCaptureRequest };

			//if (payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.PaymentCaptured) != "true") {
				DoCaptureResponseType doCaptureResponse;
				try {
					doCaptureResponse = service.DoCapture(doCaptureReq);
					if (doCaptureResponse.Ack != AckCodeType.SUCCESS && doCaptureResponse.Ack != AckCodeType.SUCCESSWITHWARNING) {
						return new PaymentResult(Attempt<IPayment>.Fail(payment, CreateErrorResult(doCaptureResponse.Errors)), invoice, false);
					}
				} catch (Exception ex) {
					return new PaymentResult(Attempt<IPayment>.Fail(payment, ex), invoice, false);
				}
			
				payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.TransactionId, doCaptureResponse.DoCaptureResponseDetails.PaymentInfo.TransactionID);
				payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.PaymentCaptured, "true");	
			//}
			
			payment.Authorized = true;
			payment.Collected = true;
			return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, true);
			
		}
开发者ID:drpeck,项目名称:Merchello,代码行数:36,代码来源:PayPalPaymentProcessor.cs

示例5: CreatePayPalPaymentDetails

		private PaymentDetailsType CreatePayPalPaymentDetails(IInvoice invoice, ProcessorArgumentCollection args = null)
		{
			
			string articleBySkuPath = args.GetArticleBySkuPath(_settings.ArticleBySkuPath.IsEmpty() ? null : GetWebsiteUrl() + _settings.ArticleBySkuPath);
			var currencyCodeType = PayPalCurrency(invoice.CurrencyCode());
			var currencyDecimals = CurrencyDecimals(currencyCodeType);

			decimal itemTotal = 0;
            decimal taxTotal = 0;
			decimal shippingTotal = 0;
			AddressType shipAddress = null;

			var paymentDetailItems = new List<PaymentDetailsItemType>();
			foreach (var item in invoice.Items)
			{
				if (item.LineItemTfKey == Merchello.Core.Constants.TypeFieldKeys.LineItem.TaxKey) 
                {
					taxTotal = item.TotalPrice;
				} 
                else if (item.LineItemTfKey == Merchello.Core.Constants.TypeFieldKeys.LineItem.ShippingKey) 
                {
					shippingTotal = item.TotalPrice;
					var address = item.ExtendedData.GetAddress(Merchello.Core.AddressType.Shipping);
					if (address != null) {
						shipAddress = new AddressType() {
							Name = address.Name,
							Street1 = address.Address1,
							Street2 = address.Address2,
							PostalCode = address.PostalCode,
							CityName = address.Locality,
							StateOrProvince = address.Region,
							CountryName = address.Country().Name,
							Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), address.Country().CountryCode, true),
							Phone = address.Phone
						};
					}
				}
                else if (item.LineItemTfKey == Merchello.Core.Constants.TypeFieldKeys.LineItem.DiscountKey)
                {
                    var discountItem = new PaymentDetailsItemType
                    {
                        Name = item.Name,
                        ItemURL = (articleBySkuPath.IsEmpty() ? null : articleBySkuPath + item.Sku),
                        Amount = new BasicAmountType(currencyCodeType, PriceToString(item.Price*-1, currencyDecimals)),
                        Quantity = item.Quantity,
                    };
                    paymentDetailItems.Add(discountItem);
                    itemTotal -= item.TotalPrice;
                } 
                else {
					var paymentItem = new PaymentDetailsItemType {
						Name = item.Name,
						ItemURL = (articleBySkuPath.IsEmpty() ? null : articleBySkuPath + item.Sku),
						Amount = new BasicAmountType(currencyCodeType, PriceToString(item.Price, currencyDecimals)),
						Quantity = item.Quantity,
					};
					paymentDetailItems.Add(paymentItem);
					itemTotal += item.TotalPrice;
				}
			}

			var paymentDetails = new PaymentDetailsType
			{
				PaymentDetailsItem = paymentDetailItems,
				ItemTotal = new BasicAmountType(currencyCodeType, PriceToString(itemTotal, currencyDecimals)),
				TaxTotal = new BasicAmountType(currencyCodeType, PriceToString(taxTotal, currencyDecimals)),
				ShippingTotal = new BasicAmountType(currencyCodeType, PriceToString(shippingTotal, currencyDecimals)),
                OrderTotal = new BasicAmountType(currencyCodeType, PriceToString(invoice.Total, currencyDecimals)),
                PaymentAction = PaymentActionCodeType.ORDER,
				InvoiceID = invoice.InvoiceNumberPrefix + invoice.InvoiceNumber.ToString("0"),
				SellerDetails = new SellerDetailsType { PayPalAccountID = _settings.AccountId },
				PaymentRequestID = "PaymentRequest",
				ShipToAddress = shipAddress,
				NotifyURL = "http://IPNhost"
			};

			return paymentDetails;
		}
开发者ID:drpeck,项目名称:Merchello,代码行数:78,代码来源:PayPalPaymentProcessor.cs

示例6: ProcessPayment

        /// <summary>
        ///     Processes the Authorize and AuthorizeAndCapture transactions
        /// </summary>
        /// <param name="invoice">The <see cref="IInvoice" /> to be paid</param>
        /// <param name="payment">The <see cref="IPayment" /> record</param>
        /// <param name="transactionMode">Authorize or AuthorizeAndCapture</param>
        /// <param name="amount">The money amount to be processed</param>
        /// <param name="creditCard">The <see cref="CreditCardFormData" /></param>
        /// <returns>The <see cref="IPaymentResult" /></returns>
        public IPaymentResult ProcessPayment(IInvoice invoice, IPayment payment, TransactionMode transactionMode,
            decimal amount, CreditCardFormData creditCard)
        {
            if (!IsValidCurrencyCode(invoice.CurrencyCode()))
                return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception("Invalid currency")), invoice,
                    false);

            // The minimum amount is $0.50 (or equivalent in charge currency). 
            // Test that the payment meets the minimum amount (for USD only).
            if (invoice.CurrencyCode() == "USD")
            {
                if (amount < 0.5m)
                    return
                        new PaymentResult(
                            Attempt<IPayment>.Fail(payment, new Exception("Invalid amount (less than 0.50 USD)")),
                            invoice, false);
            }
            else
            {
                if (amount < 1)
                    return
                        new PaymentResult(
                            Attempt<IPayment>.Fail(payment,
                                new Exception("Invalid amount (less than 1 " + invoice.CurrencyCode() + ")")),
                            invoice, false);
            }

            var requestParams = new NameValueCollection();
            requestParams.Add("amount", ConvertAmount(invoice, amount));
            requestParams.Add("currency", invoice.CurrencyCode());
            if (transactionMode == TransactionMode.Authorize)
                requestParams.Add("capture", "false");
            requestParams.Add("card[number]", creditCard.CardNumber);
            requestParams.Add("card[exp_month]", creditCard.ExpireMonth);
            requestParams.Add("card[exp_year]", creditCard.ExpireYear);
            requestParams.Add("card[cvc]", creditCard.CardCode);
            requestParams.Add("card[name]", creditCard.CardholderName);

            // Billing address
            IAddress address = invoice.GetBillingAddress();
            //requestParams.Add("receipt_email", address.Email); // note: this will send receipt email - maybe there should be a setting controlling if this is passed or not. Email could also be added to metadata
            requestParams.Add("card[address_line1]", address.Address1);
            requestParams.Add("card[address_line2]", address.Address2);
            requestParams.Add("card[address_city]", address.Locality);
            if (!string.IsNullOrEmpty(address.Region)) requestParams.Add("card[address_state]", address.Region);
            requestParams.Add("card[address_zip]", address.PostalCode);
            if (!string.IsNullOrEmpty(address.CountryCode))
                requestParams.Add("card[address_country]", address.CountryCode);
            requestParams.Add("metadata[invoice_number]", invoice.PrefixedInvoiceNumber());
            requestParams.Add("description", string.Format("Full invoice #{0}", invoice.PrefixedInvoiceNumber()));

            string postData =
                requestParams.AllKeys.Aggregate("",
                    (current, key) => current + (key + "=" + HttpUtility.UrlEncode(requestParams[key]) + "&"))
                    .TrimEnd('&');

            // https://stripe.com/docs/api#create_charge
            try
            {
                var response = MakeStripeApiRequest("https://api.stripe.com/v1/charges", "POST", requestParams);
                return GetProcessPaymentResult(invoice, payment, response);
            }
            catch (WebException ex)
            {
                return GetProcessPaymentResult(invoice, payment, (HttpWebResponse) ex.Response);
            }
        }
开发者ID:arknu,项目名称:Merchello,代码行数:76,代码来源:StripePaymentProcessor.cs

示例7: ConvertAmount

 private static string ConvertAmount(IInvoice invoice, decimal amount)
 {
     // need to convert non-zero-decimal currencies
     bool isZeroDecimalCurrency = IsZeroDecimalCurrency(invoice.CurrencyCode());
     decimal stripeAmountDecimal = isZeroDecimalCurrency ? amount : (amount*100);
     return Convert.ToInt32(stripeAmountDecimal).ToString(CultureInfo.InvariantCulture);
 }
开发者ID:arknu,项目名称:Merchello,代码行数:7,代码来源:StripePaymentProcessor.cs

示例8: SetSagePayApiData

        //TODO: refactor away to a Service that wraps the SagePay kit horribleness
        private void SetSagePayApiData(IFormPayment request, IInvoice invoice, IPayment payment)
        {
            // Get Merchello data
            var billingAddress = invoice.GetBillingAddress();
            var shippingAddress = billingAddress;

            // Shipment - only use a shipping address if there is shipment info in the invoice
            var shipmentLineItem = invoice.ShippingLineItems().FirstOrDefault();
            if (shipmentLineItem != null)
            {
                var shipment = shipmentLineItem.ExtendedData.GetShipment<InvoiceLineItem>();
                shippingAddress = shipment.GetDestinationAddress();
            }
            
            // SagePay details
            request.VpsProtocol = Settings.ProtocolVersion;
            request.TransactionType = Settings.TransactionType;
            request.Vendor = Settings.VendorName;
            request.VendorTxCode = SagePayFormIntegration.GetNewVendorTxCode();
            request.Amount = payment.Amount;
            request.Currency = invoice.CurrencyCode();
            request.Description = "Goods from " + Settings.VendorName;
            
            // TODO:  Is there a basket summary I can access?  Or convert the Basket to a sagepay format

            // Set ReturnUrl and CancelUrl of SagePay request to SagePayApiController.
            Func<string, string> adjustUrl = (url) =>
            {
                if (!url.StartsWith("http")) url = GetWebsiteUrl() + (url[0] == '/' ? "" : "/") + url;
                url = url.Replace("{invoiceKey}", invoice.Key.ToString(), StringComparison.InvariantCultureIgnoreCase);
                url = url.Replace("{paymentKey}", payment.Key.ToString(), StringComparison.InvariantCultureIgnoreCase);
                return url;
            };

            request.SuccessUrl = adjustUrl("/umbraco/MerchelloSagePay/SagePayApi/SuccessPayment?InvoiceKey={invoiceKey}&PaymentKey={paymentKey}");
            request.FailureUrl = adjustUrl("/umbraco/MerchelloSagePay/SagePayApi/AbortPayment?InvoiceKey={invoiceKey}&PaymentKey={paymentKey}");

            // Billing details
            request.BillingSurname = billingAddress.TrySplitLastName();
            request.BillingFirstnames = billingAddress.TrySplitFirstName();
            request.BillingAddress1 = billingAddress.Address1;
            request.BillingAddress2 = billingAddress.Address2;
            request.BillingPostCode = billingAddress.PostalCode;
            request.BillingCity = billingAddress.Locality;
            request.BillingCountry = invoice.BillToCountryCode;
            request.CustomerEmail = billingAddress.Email;

            // Shipping details
            request.DeliverySurname = shippingAddress.TrySplitLastName();
            request.DeliveryFirstnames = shippingAddress.TrySplitFirstName();
            request.DeliveryAddress1 = shippingAddress.Address1;
            request.DeliveryCity = shippingAddress.Locality;
            request.DeliveryCountry = shippingAddress.CountryCode;
            request.DeliveryPostCode = shippingAddress.PostalCode;

            //Optional
            //request.CustomerName = cart.Billing.FirstNames + " " + cart.Billing.Surname;
            
            //request.VendorEmail = Settings.VendorEmail;
            //request.SendEmail = Settings.SendEmail;

            //request.EmailMessage = Settings.EmailMessage;
            //request.BillingAddress2 = billingAddress.Address2;
            //request.BillingPostCode = billingAddress.PostalCode;
            //request.BillingState = billingAddress.Region;
            //request.BillingPhone = billingAddress.Phone;
            //request.DeliveryAddress2 = shippingAddress.Address2;
            //request.DeliveryPostCode = shippingAddress.PostalCode;
            //request.DeliveryState = shippingAddress.Region;
            //request.DeliveryPhone = shippingAddress.Phone;

        }
开发者ID:chrisdaaaaay,项目名称:Merchello.Plugins.SagePay,代码行数:73,代码来源:SagePayFormPaymentProcessor.cs

示例9: ProcessPayment

        /// <summary>
        /// Processes the Authorize and AuthorizeAndCapture transactions
        /// </summary>
        /// <param name="invoice">The <see cref="IInvoice"/> to be paid</param>
        /// <param name="payment">The <see cref="IPayment"/> record</param>
        /// <param name="transactionMode">Authorize or AuthorizeAndCapture</param>
        /// <param name="amount">The money amount to be processed</param>
        /// <param name="creditCard">The <see cref="CreditCardFormData"/></param>
        /// <returns>The <see cref="IPaymentResult"/></returns>
        public IPaymentResult ProcessPayment(IInvoice invoice, IPayment payment, TransactionMode transactionMode, decimal amount, CreditCardFormData creditCard)
        {
            var address = invoice.GetBillingAddress();
            
            var form = GetInitialRequestForm(invoice.CurrencyCode());

            var names = creditCard.CardholderName.Split(' ');

            form.Add("x_type", 
                    transactionMode == TransactionMode.Authorize ?
                    "AUTH_ONLY" : "AUTH_CAPTURE"
                );
           
            // Credit card information            
            form.Add("x_card_num", creditCard.CardNumber);
            form.Add("x_exp_date", creditCard.ExpireMonth.PadLeft(2) + creditCard.ExpireYear);
            form.Add("x_card_code", creditCard.CardCode);
            form.Add("x_customer_ip", creditCard.CustomerIp);

            // Billing address
            form.Add("x_first_name", names.Count() > 1 ? names[0] : creditCard.CardholderName);
            form.Add("x_last_name", names.Count() > 1 ? names[1] : string.Empty);
            form.Add("x_email", address.Email);
            if(!string.IsNullOrEmpty(address.Organization)) form.Add("x_company", address.Organization);
            form.Add("x_address", address.Address1);
            form.Add("x_city", address.Locality);
            if(!string.IsNullOrEmpty(address.Region)) form.Add("x_state", address.Region);
            form.Add("x_zip", address.PostalCode);
            if(!string.IsNullOrEmpty(address.CountryCode)) form.Add("x_country", address.CountryCode);

            // Invoice information
            form.Add("x_amount", amount.ToString("0.00", CultureInfo.InstalledUICulture));

            // maximum length 20 chars
            form.Add("x_invoice_num", invoice.PrefixedInvoiceNumber());
            form.Add("x_description", string.Format("Full invoice #{0}", invoice.PrefixedInvoiceNumber()));

            var reply = GetAuthorizeNetReply(form);

            // API Error
            if(string.IsNullOrEmpty(reply)) return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception("Authorize.NET unknown error")), invoice, false);

            var fields = reply.Split('|');

            switch (fields[0])
            {
                case "3" :
                    return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Error {0}", reply))), invoice, false);
                case "2" :                    
                    payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.AuthorizeDeclinedResult, string.Format("Declined ({0} : {1})", fields[2], fields[3]));
                    return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Declined ({0} : {1})", fields[2], fields[3]))), invoice, false);
                case "1" :
                    payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.AuthorizationTransactionCode, string.Format("{0},{1}", fields[6], fields[4]));
                    payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.AuthorizationTransactionResult, string.Format("Approved ({0}: {1})", fields[2], fields[3]));
                    payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.AvsResult, fields[5]);
                    payment.Authorized = true;
                    if (transactionMode == TransactionMode.AuthorizeAndCapture) payment.Collected = true;                    
                    return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, true);
            }

            return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Error {0}", reply))), invoice, false);
        }
开发者ID:arknu,项目名称:Merchello,代码行数:71,代码来源:AuthorizeNetPaymentProcessor.cs

示例10: VoidPayment

        public IPaymentResult VoidPayment(IInvoice invoice, IPayment payment)
        {
            // assert last 4 digits of cc is present
            var cc4 = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.CcLastFour);
            if(string.IsNullOrEmpty(cc4)) return new PaymentResult(Attempt<IPayment>.Fail(payment, new InvalidOperationException("The last four digits of the credit card are not available")), invoice, false);

            // assert the transaction code is present
            var codes = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.AuthorizationTransactionCode);
            if (!payment.Authorized || string.IsNullOrEmpty(codes)) return new PaymentResult(Attempt<IPayment>.Fail(payment, new InvalidOperationException("Payment is not Authorized or TransactionCodes not present")), invoice, false);

            var form = GetInitialRequestForm(invoice.CurrencyCode());
            form.Add("x_type", "CREDIT");
            form.Add("x_trans_id", codes.Split(',').First());

            form.Add("x_card_num", cc4.DecryptWithMachineKey());
            
            form.Add("x_type", "VOID");
            

            var reply = GetAuthorizeNetReply(form);

            // API Error
            if (string.IsNullOrEmpty(reply)) return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception("Authorize.NET unknown error")), invoice, false);

            var fields = reply.Split('|');

            switch (fields[0])
            {
                case "3":
                    return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Error {0}", reply))), invoice, false);
                case "2":
                    payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.VoidDeclinedResult, string.Format("Declined ({0} : {1})", fields[2], fields[3]));
                    return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Declined ({0} : {1})", fields[2], fields[3]))), invoice, false);
                case "1":
                    return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, true);
            }

            return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Error {0}", reply))), invoice, false);
        }
开发者ID:arknu,项目名称:Merchello,代码行数:39,代码来源:AuthorizeNetPaymentProcessor.cs

示例11: RefundPayment

        /// <summary>
        /// Refunds a payment amount
        /// </summary>
        /// <param name="invoice">The <see cref="IInvoice"/> associated with the payment</param>
        /// <param name="payment">The <see cref="IPayment"/> to be refunded</param>
        /// <param name="amount">The amount of the <see cref="IPayment"/> to be refunded</param>
        /// <returns></returns>
        public IPaymentResult RefundPayment(IInvoice invoice, IPayment payment, decimal amount)
        {

            // assert last 4 digits of cc is present
            var cc4 = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.CcLastFour);
            if(string.IsNullOrEmpty(cc4)) return new PaymentResult(Attempt<IPayment>.Fail(payment, new InvalidOperationException("The last four digits of the credit card are not available")), invoice, false);

            // assert the transaction code is present
            var codes = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.AuthorizationTransactionCode);
            if (!payment.Authorized || string.IsNullOrEmpty(codes)) return new PaymentResult(Attempt<IPayment>.Fail(payment, new InvalidOperationException("Payment is not Authorized or TransactionCodes not present")), invoice, false);

            var form = GetInitialRequestForm(invoice.CurrencyCode());
            form.Add("x_type", "CREDIT");
            form.Add("x_trans_id", codes.Split(',').First());

            form.Add("x_card_num", cc4.DecryptWithMachineKey());
            form.Add("x_amount", amount.ToString("0.00", CultureInfo.InvariantCulture));
            
            //x_invoice_num is 20 chars maximum. hence we also pass x_description
            form.Add("x_invoice_num", invoice.PrefixedInvoiceNumber().Substring(0, 20));
            form.Add("x_description", string.Format("Full order #{0}", invoice.PrefixedInvoiceNumber()));
            form.Add("x_type", "CREDIT");
            

            var reply = GetAuthorizeNetReply(form);

            // API Error
            if (string.IsNullOrEmpty(reply)) return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception("Authorize.NET unknown error")), invoice, false);

            var fields = reply.Split('|');

            switch (fields[0])
            {
                case "3":
                    return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Error {0}", reply))), invoice, false);
                case "2":
                    payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.RefundDeclinedResult, string.Format("Declined ({0} : {1})", fields[2], fields[3]));
                    return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Declined ({0} : {1})", fields[2], fields[3]))), invoice, false);
                case "1":
                    return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, true);
            }

            return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Error {0}", reply))), invoice, false);
        }
开发者ID:arknu,项目名称:Merchello,代码行数:51,代码来源:AuthorizeNetPaymentProcessor.cs

示例12: PriorAuthorizeCapturePayment

        /// <summary>
        /// Captures a previously authorized payment
        /// </summary>
        /// <param name="invoice">The invoice associated with the <see cref="IPayment"/></param>
        /// <param name="payment">The <see cref="IPayment"/> to capture</param>
        /// <returns>The <see cref="IPaymentResult"/></returns>
        public IPaymentResult PriorAuthorizeCapturePayment(IInvoice invoice, IPayment payment)
        {
            var codes = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.AuthorizationTransactionCode);
            if(!payment.Authorized || string.IsNullOrEmpty(codes)) return new PaymentResult(Attempt<IPayment>.Fail(payment, new InvalidOperationException("Payment is not Authorized or TransactionCodes not present")), invoice, false);

            var form = GetInitialRequestForm(invoice.CurrencyCode());
            form.Add("x_type", "PRIOR_AUTH_CAPTURE");
            form.Add("x_trans_id", codes.Split(',').First());

            var reply = GetAuthorizeNetReply(form);

            // API Error
            if (string.IsNullOrEmpty(reply)) return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception("Authorize.NET unknown error")), invoice, false);

            var fields = reply.Split('|');

            switch (fields[0])
            {
                case "3":
                    return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Error {0}", reply))), invoice, false);
                case "2":
                    payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.CaptureDeclinedResult, string.Format("Declined ({0} : {1})", fields[2], fields[3]));
                    return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Declined ({0} : {1})", fields[2], fields[3]))), invoice, false);
                case "1":
                    payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.CaputureTransactionCode, string.Format("{0},{1}", fields[6], fields[4]));
                    payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.CaptureTransactionResult, string.Format("Approved ({0}: {1})", fields[2], fields[3]));
                    payment.Collected = true;
                    return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, true);
            }

            return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Error {0}", reply))), invoice, false);
        }
开发者ID:arknu,项目名称:Merchello,代码行数:38,代码来源:AuthorizeNetPaymentProcessor.cs

示例13: SetSagePayApiData

        //TODO: refactor away to a Service that wraps the SagePay kit horribleness
        private void SetSagePayApiData(IDirectPayment request, IInvoice invoice, IPayment payment, CreditCard creditCard)
        {
            // Get Merchello data
            //TODO - what if there is no shipping info?  e.g. Classes only - Get from billing?
            var shipmentLineItem = invoice.ShippingLineItems().FirstOrDefault();
            var shipment = shipmentLineItem.ExtendedData.GetShipment<InvoiceLineItem>();
            var shippingAddress = shipment.GetDestinationAddress();
            var billingAddress = invoice.GetBillingAddress(); 
            

            // Merchello info for callback
            //request.InvoiceKey = invoice.Key;
            //request.PayerId = invoice.Pa
            //request.PaymentKey = payment.Key
            
            // SagePay details
            request.VpsProtocol = Settings.ProtocolVersion;
            request.TransactionType = Settings.TransactionType;
            request.Vendor = Settings.VendorName;
            request.VendorTxCode = SagePayAPIIntegration.GetNewVendorTxCode();
            request.Amount = payment.Amount;
            request.Currency = invoice.CurrencyCode();
            request.Description = "Goods from " + Settings.VendorName;
            
            // TODO:  Is there a basket summary I can access?  Or convert the Basket to a sagepay format

            // Billing details
            request.BillingSurname = billingAddress.TrySplitLastName();
            request.BillingFirstnames = billingAddress.TrySplitFirstName();
            request.BillingAddress1 = billingAddress.Address1;
            request.BillingAddress2 = billingAddress.Address2;
            request.BillingPostCode = billingAddress.PostalCode;
            request.BillingCity = billingAddress.Locality;
            request.BillingCountry = invoice.BillToCountryCode;

            // Shipping details
            request.DeliverySurname = shippingAddress.TrySplitLastName();
            request.DeliveryFirstnames = shippingAddress.TrySplitFirstName();
            request.DeliveryAddress1 = shippingAddress.Address1;
            request.DeliveryCity = shippingAddress.Locality;
            request.DeliveryCountry = shippingAddress.CountryCode;
            request.DeliveryPostCode = shippingAddress.PostalCode;

            request.CardType = (CardType)Enum.Parse(typeof(CardType), creditCard.CreditCardType);
            request.CardHolder = creditCard.CardholderName;
            request.CardNumber = creditCard.CardNumber;
            request.ExpiryDate = creditCard.ExpireMonth + creditCard.ExpireYear;
            request.Cv2 = creditCard.CardCode;

            request.Apply3dSecure = 0;

            if (request.CardType == CardType.PAYPAL)
            {
                Func<string, string> adjustUrl = (url) =>
                {
                    if (!url.StartsWith("http")) url = GetWebsiteUrl() + (url[0] == '/' ? "" : "/") + url;
                    url = url.Replace("{invoiceKey}", invoice.Key.ToString(), StringComparison.InvariantCultureIgnoreCase);
                    url = url.Replace("{paymentKey}", payment.Key.ToString(), StringComparison.InvariantCultureIgnoreCase);
                    return url;
                };

                request.PayPalCallbackUrl = adjustUrl("/umbraco/MerchelloSagePay/SagePayApi/PaypalCallback?InvoiceKey={invoiceKey}&PaymentKey={paymentKey}");
            }

            //Optional
            //request.CustomerName = cart.Billing.FirstNames + " " + cart.Billing.Surname;
            //request.CustomerEmail = customer.Email;
            //request.VendorEmail = Settings.VendorEmail;
            //request.SendEmail = Settings.SendEmail;

            //request.EmailMessage = Settings.EmailMessage;
            //request.BillingAddress2 = billingAddress.Address2;
            //request.BillingPostCode = billingAddress.PostalCode;
            //request.BillingState = billingAddress.Region;
            //request.BillingPhone = billingAddress.Phone;
            //request.DeliveryAddress2 = shippingAddress.Address2;
            //request.DeliveryPostCode = shippingAddress.PostalCode;
            //request.DeliveryState = shippingAddress.Region;
            //request.DeliveryPhone = shippingAddress.Phone;

        }
开发者ID:chrisdaaaaay,项目名称:Merchello.Plugins.SagePay,代码行数:82,代码来源:SagePayDirectPaymentProcessor.cs


注:本文中的IInvoice.CurrencyCode方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。