/// <summary> /// Does the actual work capturing a payment /// </summary> /// <param name="invoice">The <see cref="IInvoice"/></param> /// <param name="payment">The previously Authorize payment to be captured</param> /// <param name="amount">The amount to capture</param> /// <param name="args">Any arguments required to process the payment.</param> /// <returns>The <see cref="IPaymentResult"/></returns> protected override IPaymentResult PerformCapturePayment(IInvoice invoice, IPayment payment, decimal amount, ProcessorArgumentCollection args) { var result = _processor.PriorAuthorizeCapturePayment(invoice, payment); GatewayProviderService.Save(payment); if (!result.Payment.Success) { GatewayProviderService.ApplyPaymentToInvoice( payment.Key, invoice.Key, AppliedPaymentType.Denied, result.Payment.Exception.Message, 0); } else { GatewayProviderService.ApplyPaymentToInvoice( payment.Key, invoice.Key, AppliedPaymentType.Debit, payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.CaptureTransactionResult), amount); } return result; }
public IPaymentResult AuthorizePayment(IInvoice invoice, IPayment payment, string signature, string data) { MessageObject messageObject = VerifyResponse(data, signature); var id = messageObject.GetAttribute(SaferPayConstants.MessageAttributes.Id); var token = messageObject.GetAttribute(SaferPayConstants.MessageAttributes.Token); if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(token)) { return new PaymentResult(Attempt<IPayment>.Fail(payment), invoice, false); } // save this values to payment payment.ExtendedData.SetValue(SaferPayConstants.MessageAttributes.Id, id); payment.ExtendedData.SetValue(SaferPayConstants.MessageAttributes.Token, id); // Complete order for saferpay MessageObject payComplete = _messageFactory.CreateRequest(SaferPayConstants.PayCompleteKey); payComplete.SetAttribute(SaferPayConstants.MessageAttributes.AccountId, _settings.AccountId); payComplete.SetAttribute(SaferPayConstants.MessageAttributes.Id, id); payComplete.SetAttribute(SaferPayConstants.MessageAttributes.Token, token); MessageObject payCompleteResult = payComplete.Capture(); // authorize in merchello payment.Authorized = true; return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, true); }
public void AddPayment(IPayment payment) { try { if (!IsEnabled) return; using (var connection = new MySqlConnection(_mySqlProvider.ConnectionString)) { connection.Execute( @"INSERT INTO Payment(Block, AccountId, Amount, CreatedAt) VALUES(@blockId, @accountId, @amount, @createdAt)", new { blockId = payment.BlockId, accountId = payment.AccountId, amount = payment.Amount, createdAt = DateTime.Now }); } } catch (Exception e) { _logger.Error("An exception occured while committing payment; {0:l}", e.Message); } }
public Transaction(IAccount account, IPayment payout, string currency) { Account = account; Payment = payout; Currency = currency; CreatedAt = DateTime.Now; }
public DirectpayRequest(IPayment payment, IDictionary parameters) { foreach (KeyValuePair<string, string> temp in PaymentConvert(payment)) { parameters.Add(temp.Key, temp.Value); } _formData = BuildFormData(parameters); }
/// <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); }
protected override IPaymentResult PerformCapturePayment(IInvoice invoice, IPayment payment, decimal amount, ProcessorArgumentCollection args) { var payedTotalList = invoice.AppliedPayments().Select(item => item.Amount).ToList(); var payedTotal = (payedTotalList.Count == 0 ? 0 : payedTotalList.Aggregate((a, b) => a + b)); var isPartialPayment = amount + payedTotal < invoice.Total; var result = _processor.CapturePayment(invoice, payment, amount, isPartialPayment); //GatewayProviderService.Save(payment); if (!result.Payment.Success) { //payment.VoidPayment(invoice, payment.PaymentMethodKey.Value); GatewayProviderService.ApplyPaymentToInvoice(payment.Key, invoice.Key, AppliedPaymentType.Denied, "PayPal: request capture error: " + result.Payment.Exception.Message, 0); } else { GatewayProviderService.Save(payment); GatewayProviderService.ApplyPaymentToInvoice(payment.Key, invoice.Key, AppliedPaymentType.Debit, "PayPal: captured", amount); //GatewayProviderService.ApplyPaymentToInvoice(payment.Key, invoice.Key, AppliedPaymentType.Debit, payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.CaptureTransactionResult), amount); } return result; }
/// <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) { if (!payment.Authorized) return new PaymentResult(Attempt<IPayment>.Fail(payment, new InvalidOperationException("Payment is not Authorized")), invoice, false); payment.Collected = true; return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, true); }
public IPaymentResult InitializePayment(IInvoice invoice, IPayment payment, ProcessorArgumentCollection args) { string postUrl = GetPostUrl(invoice, payment); payment.ExtendedData.SetValue("RedirectUrl", postUrl); HttpContext.Current.Response.Redirect(postUrl); return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, true); }
/// <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="args"></param> /// <returns>The <see cref="IPaymentResult"/></returns> public IPaymentResult ProcessPayment(IInvoice invoice, IPayment payment, ProcessorArgumentCollection args) { var setExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType { ReturnURL = String.Format("{0}/App_Plugins/Merchello.PayPal/PayPalExpressCheckout.html?InvoiceKey={1}&PaymentKey={2}&PaymentMethodKey={3}", GetWebsiteUrl(), invoice.Key, payment.Key, payment.PaymentMethodKey), CancelURL = "http://localhost/cancel", PaymentDetails = new List<PaymentDetailsType> { GetPaymentDetails(invoice) } }; var setExpressCheckout = new SetExpressCheckoutReq(); var setExpressCheckoutRequest = new SetExpressCheckoutRequestType(setExpressCheckoutRequestDetails); setExpressCheckout.SetExpressCheckoutRequest = setExpressCheckoutRequest; var config = new Dictionary<string, string> { {"mode", "sandbox"}, {"account1.apiUsername", _settings.ApiUsername}, {"account1.apiPassword", _settings.ApiPassword}, {"account1.apiSignature", _settings.ApiSignature} }; var service = new PayPalAPIInterfaceServiceService(config); var responseSetExpressCheckoutResponseType = service.SetExpressCheckout(setExpressCheckout); // If this were using a service we might want to store some of the transaction data in the ExtendedData for record payment.ExtendedData.SetValue("RedirectUrl", "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + responseSetExpressCheckoutResponseType.Token); return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, false); }
/// <summary> /// Initialize purchase controller /// </summary> /// <param name="courseCtrl">Course API</param> /// <param name="myCourseCtrl">MyCourse API</param> /// <param name="userProfileRepo">User profile repository</param> /// <param name="classRoomRepo">Class room repository</param> /// <param name="classCalendarRepo">Class calendar repository</param> /// <param name="lessonCatalogRepo">Lesson catalog repository</param> /// <param name="userActivityRepo">User activity repository</param> /// <param name="paymentRepo">Payment repository</param> public PurchaseController(CourseController courseCtrl, MyCourseController myCourseCtrl, IUserProfileRepository userProfileRepo, IClassRoomRepository classRoomRepo, IClassCalendarRepository classCalendarRepo, ILessonCatalogRepository lessonCatalogRepo, IUserActivityRepository userActivityRepo, IPaymentRepository paymentRepo, IOptions<AppConfigOptions> appConfig, IOptions<ErrorMessageOptions> errorMsgs, ILoggerFactory loggerFactory, IPayment payment, IDateTime dateTime) { _courseCtrl = courseCtrl; _myCourseCtrl = myCourseCtrl; _userprofileRepo = userProfileRepo; _classRoomRepo = classRoomRepo; _classCalendarRepo = classCalendarRepo; _lessonCatalogRepo = lessonCatalogRepo; _userActivityRepo = userActivityRepo; _paymentRepo = paymentRepo; _dateTime = dateTime; _appConfig = appConfig.Value; _errorMsgs = errorMsgs.Value; _logger = loggerFactory.CreateLogger<PurchaseController>(); _payment = payment; }
private static NameValueCollection getQueryString(IPayment payment) { try { var queryString = HttpUtility.ParseQueryString(String.Empty); queryString["merchantAccount"] = Globals.Instance.settings["AdyenMerchantAccount"]; queryString["skinCode"] = Globals.Instance.settings["AdyenPaypalSkinCode"]; queryString["shipBeforeDate"] = DateTime.Now.AddDays(5).ToUniversalTime().ToString("yyyy-MM-dd"); queryString["sessionValidity"] = DateTime.Now.AddHours(3).ToUniversalTime().ToString("s", DateTimeFormatInfo.InvariantInfo) + "Z"; ; queryString["allowedMethods"] = "paypal"; //queryString["paymentAmount"] = payment.amount.ToString(CultureInfo.InvariantCulture); queryString["paymentAmount"] = 50.ToString(CultureInfo.InvariantCulture); queryString["currencyCode"] = payment.currency; queryString["shopperLocale"] = "de_DE"; queryString["merchantReference"] = payment.paymentRef; queryString["brandCode"] = "paypal"; queryString["merchantReturnData"] = payment.paymentRef; return queryString; } catch(Exception exp) { log.Error(exp); throw; } }
protected override IPaymentResult PerformCapturePayment(IInvoice invoice, IPayment payment, decimal amount, ProcessorArgumentCollection args) { var token = args["token"]; var payerId = args["PayerID"]; var result = _processor.ComplitePayment(invoice, payment, token, payerId); GatewayProviderService.Save(payment); // TODO GatewayProviderService.ApplyPaymentToInvoice(payment.Key, invoice.Key, AppliedPaymentType.Debit, "Cash payment", payment.Amount); /* if (!result.Payment.Success) { GatewayProviderService.ApplyPaymentToInvoice(payment.Key, invoice.Key, AppliedPaymentType.Denied, result.Payment.Exception.Message, 0); } else { GatewayProviderService.ApplyPaymentToInvoice(payment.Key, invoice.Key, AppliedPaymentType.Debit, payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.CaptureTransactionResult), amount); } */ return result; }
public void Action(string addInfo, IPayment payment) { if (log.IsDebugEnabled) { log.Debug("invoked " + addInfo + " " + payment); } var paymentTransaction = new PaymentTransaction(this); if (DateTime.Now < dontLeakUntil) return; if (alreadyLeakedSize < MaxMemoryLeakSize) { paymentTransaction.SendData(new long[MemoryGrowSize]); alreadyLeakedSize += MemoryGrowSize; if (log.IsDebugEnabled) { log.Debug(string.Format("{0} MB leaked, {1} MB in total", MemoryGrowSize / MB, alreadyLeakedSize / MB)); } } else { if (log.IsDebugEnabled) { log.Debug(string.Format("maximum amount of memory leak reached ({0} MB)", MaxMemoryLeakSize / MB)); } // try to allocate an impossibly large array to trigger OutOfMemoryException paymentTransaction.SendData(new long[int.MaxValue]); // dispose all leaked data OnAbortTransaction(); // don't leak for some time dontLeakUntil = DateTime.Now + pauseLeakingTimeSpan; alreadyLeakedSize = 0; } }
public void Action(string addInfo, IPayment payment) { if (log.IsDebugEnabled) { log.Debug("invoked " + addInfo + " " + payment); } using (MessageQueue mq = getOrCreateMessageQueue()) { mq.Send(payment, addInfo); } }
public bool MakePayment(decimal amountToBePaid, IPayment paymentAgent) { paymentAgent.SetAmountToBePaid(amountToBePaid); bool result = paymentAgent.MakePayment(); //ödeme yapılamazsa kesin error message'ini göster StatusMessage = paymentAgent.StatusMessage; PaymentCode = paymentAgent.PaymentCode; return result; }
public AddEditPaymentForm(Common.MFType mfType, IPaymentType paymentType, IPayment payment) : this(mfType, paymentType) { this.Text = Common.TextEdit; lstPaymentTypes.Text = payment.TypeName; dtpPaymentDate.Value = payment.PaymentDate; txtAmount.Text = payment.Amount.ToString(Common.FormatMoney); txtComment.Text = payment.Comment; }
/// <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="purchaseOrder">The <see cref="PurchaseOrderFormData"></see></param> /// <returns>The <see cref="IPaymentResult"/></returns> public IPaymentResult ProcessPayment(IInvoice invoice, IPayment payment, decimal amount, PurchaseOrderFormData purchaseOrder) { if (string.IsNullOrEmpty(purchaseOrder.PurchaseOrderNumber)) { return new PaymentResult(Attempt<IPayment>.Fail(payment, new Exception(string.Format("Error Purchase Order Number is empty"))), invoice, false); } invoice.PoNumber = purchaseOrder.PurchaseOrderNumber; payment.Authorized = true; return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, true); }
public PaymentEntity(IPayment iPayment) { Id = iPayment.Id; Deleted = iPayment.Deleted; LastUpdated = iPayment.LastUpdated; PaymentContract = iPayment.PaymentContract; PaymentDate = iPayment.PaymentDate; PayedAmount = iPayment.PayedAmount; PaymentReceipt = iPayment.PaymentReceipt; }
public static void createSave(IPayment payment, PaymentResult paymentResult) { try { paymentRef = payment.paymentRef; save(buildPaymentNotice(paymentResult)); } catch (Exception exp) { log.Error(exp); throw; } }
/// <summary> /// Does the actual work of capturing a payment /// </summary> /// <param name="invoice">The <see cref="IInvoice"/></param> /// <param name="payment"></param> /// <param name="amount"></param> /// <param name="args">Any arguments required to process the payment. (Maybe a username, password or some Api Key)</param> /// <returns>The <see cref="IPaymentResult"/></returns> protected override IPaymentResult PerformCapturePayment(IInvoice invoice, IPayment payment, decimal amount, ProcessorArgumentCollection args) { payment.Amount += amount; payment.Collected = true; payment.Authorized = true; GatewayProviderService.Save(payment); var appliedPayment = GatewayProviderService.ApplyPaymentToInvoice(payment.Key, invoice.Key, AppliedPaymentType.Debit, "Cash payment", amount); return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, invoice.Total == amount); }
public string GetPostUrl(IInvoice invoice, IPayment payment) { MessageObject pay = GetMessage(invoice, payment); string postUrl = pay.GetUrl(); if (string.IsNullOrWhiteSpace(postUrl)) { /* ToDo: log this */ /* couldnt created the url */ throw new Exception(); } return postUrl; }
public IPaymentResult ComplitePayment(IInvoice invoice, IPayment payment, string token, string payerId) { var config = new Dictionary<string, string> { {"mode", "sandbox"}, {"account1.apiUsername", _settings.ApiUsername}, {"account1.apiPassword", _settings.ApiPassword}, {"account1.apiSignature", _settings.ApiSignature} }; var service = new PayPalAPIInterfaceServiceService(config); var getExpressCheckoutDetails = new GetExpressCheckoutDetailsReq { GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token) }; var expressCheckoutDetailsResponse = service.GetExpressCheckoutDetails(getExpressCheckoutDetails); if (expressCheckoutDetailsResponse != null) { if (expressCheckoutDetailsResponse.Ack == AckCodeType.SUCCESS) { // do express checkout var doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq(); var doExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType { Token = token, PayerID = payerId, PaymentDetails = new List<PaymentDetailsType> {GetPaymentDetails(invoice)} }; var doExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType(doExpressCheckoutPaymentRequestDetails); doExpressCheckoutPayment.DoExpressCheckoutPaymentRequest = doExpressCheckoutPaymentRequest; var doExpressCheckoutPaymentResponse = service.DoExpressCheckoutPayment(doExpressCheckoutPayment); if (doExpressCheckoutPaymentResponse != null) { if (doExpressCheckoutPaymentResponse.Ack == AckCodeType.SUCCESS) { payment.Authorized = true; payment.Collected = true; return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, true); } } } } return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, false); }
public IPaymentResult PriorAuthorizeCapturePayment(IInvoice invoice, IPayment payment) { string stripeChargeId = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.StripeChargeId); string url = string.Format("https://api.stripe.com/v1/charges/{0}/capture", stripeChargeId); try { var response = StripeHelper.MakeStripeApiRequest(url, "POST", null, _settings); return GetCapturePaymentResult(invoice, payment, response); } catch (WebException ex) { return GetCapturePaymentResult(invoice, payment, (HttpWebResponse) ex.Response); } }
public static string redirectUrl(IPayment payment) { try { var redirectDomain = Globals.Instance.settings["AdyenRedirectDomain"]; var queryString = getQueryString(payment); queryString["merchantSig"] = HttpUtility.UrlPathEncode(buildSignature(queryString)); return redirectDomain + "?" + queryString.ToString(); } catch(Exception exp) { log.Error(exp); throw; } }
private void DeletePayment(IPayment payment, ItemControl ucPayments) { string message; message = "Are you sure you want to delete the selected item?"; if (MessageBox.Show(message, "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { payment.Delete(((IPayment)ucPayments.SelectedRow).Id); ucPayments.PopulateList(new SortableBindingList<IPayment>(payment.GetPayments(_year, _week))); _modified = true; } }
internal Payment(IPayment paymentEntity, IDataAccessFacade dataAccessFacade) { this.dataAccessFacade = dataAccessFacade; this._paymentEntity = paymentEntity; // Create Models of payer and payee if (_paymentEntity.Payer is ISupplier) { _payer = new Supplier(dataAccessFacade, (ISupplier)_paymentEntity.Payer); _payee = new Customer((ICustomer)_paymentEntity.Payee, dataAccessFacade); } else if (_paymentEntity.Payer is ICustomer) { _payer = new Customer((ICustomer)_paymentEntity.Payer, dataAccessFacade); _payee = new Supplier(dataAccessFacade, (ISupplier)_paymentEntity.Payee); } }
bool CheckOrder(IPayment order, out string message) { if (order == null) { message = string.Format("order(no:{0}) is not found.", order.OrderNo); return false; } if (order.Prepaid) { message = string.Format("order(no:{0}) was paid.", order.OrderNo); return false; } if (order.Closed) { message = string.Format("order(no:{0}) has been closed.", order.OrderNo); return false; } message = string.Empty; return true; }
public static IPayment CreatePayment(IPayment thisPayment) { if (Connect()) { try { SqlCommand Command = Connection.CreateCommand(); Command.CommandType = CommandType.StoredProcedure; Command.CommandText = "fif_payment_create"; if (thisPayment.Sale != null) { Command.Parameters.AddWithValue("activity_id", thisPayment.Sale.ActivityId); } else if (thisPayment.Team != null) { Command.Parameters.AddWithValue("activity_id", thisPayment.Team.ActivityId); } else if (thisPayment.Event != null) { Command.Parameters.AddWithValue("activity_id", thisPayment.Event.ActivityId); } Command.Parameters.AddWithValue("member_id", thisPayment.Member.MemberId); Command.Parameters.AddWithValue("activity_type", thisPayment.ActivityType); Command.Parameters.AddWithValue("datetime", thisPayment.Date); Command.Parameters.Add("@payment_id", SqlDbType.Int, 0, "payment_id"); Command.Parameters["@payment_id"].Direction = ParameterDirection.Output; Command.ExecuteNonQuery(); thisPayment.PaymentId = int.Parse(Command.Parameters["@payment_id"].Value.ToString()); Disconnect(); return thisPayment; } catch { Disconnect(); return null; } } return null; }
protected virtual IDictionary<string, string> PaymentConvert(IPayment payment) { var data = payment as PaymentInfo; if (data == null) throw new Exception(""); Dictionary<string, string> dict = new Dictionary<string, string>(); dict.Add("subject", data.Subject); if (!string.IsNullOrWhiteSpace(data.Body)) { dict.Add("body", data.Body); } dict.Add("out_trade_no", data.OrderNo); dict.Add("total_fee", data.Amount.ToString("F", CultureInfo.InvariantCulture)); if (!string.IsNullOrWhiteSpace(data.ShowUrl)) { dict.Add("show_url", data.ShowUrl); } return dict; }
public virtual IKlarnaOrderService Create(IPayment payment, IMarket market) { return(Create(PaymentManager.GetPaymentMethod(payment.PaymentMethodId), market.MarketId)); }
/// <summary> /// Captures a payment for the <see cref="IInvoice"/> /// </summary> /// <param name="merchelloContext">The <see cref="IMerchelloContext"/></param> /// <param name="invoice">The invoice to be payed</param> /// <param name="payment">The</param> /// <param name="paymentMethodKey"></param> /// <param name="amount">The amount to the payment to be captured</param> /// <param name="args">Additional arguements required by the payment processor</param> /// <returns>A <see cref="IPaymentResult"/></returns> internal static IPaymentResult CapturePayment(this IPayment payment, IMerchelloContext merchelloContext, IInvoice invoice, Guid paymentMethodKey, decimal amount, ProcessorArgumentCollection args) { var paymentGatewayMethod = merchelloContext.Gateways.Payment.GetPaymentGatewayMethodByKey(paymentMethodKey); return(payment.CapturePayment(invoice, paymentGatewayMethod, amount, args)); }
public Printslip(IPayment payment, int recuurence) { //TODO: Print Slip }
/// <inheritdoc /> /// <summary> /// Processes the payment. /// </summary> /// <param name="orderGroup">The order group.</param> /// <param name="payment">The payment.</param> public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment) { if (HttpContext.Current == null) { return(PaymentProcessingResult.CreateSuccessfulResult(Utilities.Translate("ProcessPaymentNullHttpContext"))); } if (payment == null) { return(PaymentProcessingResult.CreateUnsuccessfulResult(Utilities.Translate("PaymentNotSpecified"))); } var orderForm = orderGroup.Forms.FirstOrDefault(f => f.Payments.Contains(payment)); if (orderForm == null) { return(PaymentProcessingResult.CreateUnsuccessfulResult(Utilities.Translate("PaymentNotAssociatedOrderForm"))); } SetSecurityProtocolToTls12(); if (string.IsNullOrEmpty(payment.TransactionType) && !string.IsNullOrEmpty(_paymentMethodConfiguration.PaymentAction)) { payment.TransactionType = _paymentMethodConfiguration.PaymentAction; _orderRepository.Save(orderGroup); } PaymentProcessingResult paymentProcessingResult; var cart = orderGroup as ICart; // the order which is created by Commerce Manager if (cart == null && orderGroup is IPurchaseOrder) { if (payment.TransactionType == TransactionType.Capture.ToString()) { paymentProcessingResult = ProcessPaymentCapture(orderGroup, payment); RestoreSecurityProtocol(); return(paymentProcessingResult); } // When "Refund" shipment in Commerce Manager, this method will be invoked with the TransactionType is Credit if (payment.TransactionType == TransactionType.Credit.ToString()) { paymentProcessingResult = ProcessPaymentRefund(orderGroup, payment); RestoreSecurityProtocol(); return(paymentProcessingResult); } // right now we do not support processing the order which is created by Commerce Manager paymentProcessingResult = PaymentProcessingResult.CreateUnsuccessfulResult("The current payment method does not support order type."); RestoreSecurityProtocol(); return(paymentProcessingResult); // raise exception } if (cart != null && cart.OrderStatus == OrderStatus.Completed) { // return true because this shopping cart has been paid already on PayPal // when program flow redirects back from PayPal to PayPal.aspx file, call ProcessSuccessfulTransaction, run WorkFlow paymentProcessingResult = PaymentProcessingResult.CreateSuccessfulResult(Utilities.Translate("ProcessPaymentStatusCompleted")); RestoreSecurityProtocol(); return(paymentProcessingResult); } // CHECKOUT paymentProcessingResult = ProcessPaymentCheckout(cart, payment); RestoreSecurityProtocol(); return(paymentProcessingResult); }
/// <summary> /// Refunds a payment /// </summary> /// <param name="invoice">The invoice to be the payment was applied</param> /// <param name="payment">The payment to be refunded</param> /// <param name="paymentGatewayMethod">The <see cref="IPaymentGatewayMethod"/></param> /// <param name="amount">The amount to be refunded</param> /// <returns>A <see cref="IPaymentResult"/></returns> public static IPaymentResult RefundPayment(this IInvoice invoice, IPayment payment, IPaymentGatewayMethod paymentGatewayMethod, decimal amount) { return(invoice.RefundPayment(payment, paymentGatewayMethod, amount, new ProcessorArgumentCollection())); }
/// <summary> /// Voids a payment /// </summary> /// <param name="invoice">The invoice to be the payment was applied</param> /// <param name="payment">The payment to be voided</param> /// <param name="paymentGatewayMethod">The <see cref="IPaymentGatewayMethod"/></param> /// <param name="args">Additional arguements required by the payment processor</param> /// <returns>A <see cref="IPaymentResult"/></returns> public static IPaymentResult VoidPayment(this IInvoice invoice, IPayment payment, IPaymentGatewayMethod paymentGatewayMethod, ProcessorArgumentCollection args) { return(paymentGatewayMethod.VoidPayment(invoice, payment, args)); }
/// <summary> /// Voids a payment /// </summary> /// <param name="invoice">The invoice to be the payment was applied</param> /// <param name="payment">The payment to be voided</param> /// <param name="paymentMethodKey">The <see cref="IPaymentGatewayMethod"/> key</param> /// <param name="args">Additional arguements required by the payment processor</param> /// <returns>A <see cref="IPaymentResult"/></returns> public static IPaymentResult VoidPayment(this IInvoice invoice, IPayment payment, Guid paymentMethodKey, ProcessorArgumentCollection args) { return(invoice.VoidPayment(MerchelloContext.Current, payment, paymentMethodKey, args)); }
public ReleaseRemainingPaymentStep(IPayment payment, MarketId marketId, KlarnaOrderServiceFactory klarnaOrderServiceFactory) : base(payment, marketId, klarnaOrderServiceFactory) { }
/// <summary> /// Processes the successful transaction, was called when PayPal.com redirect back. /// </summary> /// <param name="orderGroup">The order group that was processed.</param> /// <param name="payment">The order payment.</param> /// <param name="acceptUrl">The redirect url when finished.</param> /// <param name="cancelUrl">The redirect url when error happens.</param> /// <returns>The url redirection after process.</returns> public string ProcessSuccessfulTransaction(IOrderGroup orderGroup, IPayment payment, string acceptUrl, string cancelUrl) { if (HttpContext.Current == null) { return(cancelUrl); } if (HttpContext.Current.Session != null) { HttpContext.Current.Session.Remove("LastCouponCode"); } if (!(orderGroup is ICart cart)) { // return to the shopping cart page immediately and show error messages return(ProcessUnsuccessfulTransaction(cancelUrl, Utilities.Translate("CommitTranErrorCartNull"))); } string redirectionUrl; using (var scope = new TransactionScope()) { SetSecurityProtocolToTls12(); var getDetailRequest = new GetExpressCheckoutDetailsRequestType { Token = payment.Properties[PayPalExpTokenPropertyName] as string // Add request-specific fields to the request. }; // Execute the API operation and obtain the response. var caller = PayPalApiHelper.GetPayPalApiCallerServices(_paymentMethodConfiguration); var getDetailsResponse = caller.GetExpressCheckoutDetails(new GetExpressCheckoutDetailsReq { GetExpressCheckoutDetailsRequest = getDetailRequest }); var errorCheck = _payPalApiHelper.CheckErrors(getDetailsResponse); if (!string.IsNullOrEmpty(errorCheck)) { RestoreSecurityProtocol(); // unsuccessful get detail call return(ProcessUnsuccessfulTransaction(cancelUrl, errorCheck)); } var expressCheckoutDetailsResponse = getDetailsResponse.GetExpressCheckoutDetailsResponseDetails; // get commerceOrderId from what we put to PayPal instead of getting from cookie payment.Properties[PayPalOrderNumberPropertyName] = expressCheckoutDetailsResponse.InvoiceID; //process details sent from paypal, changing addresses if required string emptyAddressMsg; //process billing address var payPalBillingAddress = expressCheckoutDetailsResponse.BillingAddress; if (payPalBillingAddress != null && AddressHandling.IsAddressChanged(payment.BillingAddress, payPalBillingAddress)) { emptyAddressMsg = _payPalApiHelper.ProcessOrderAddress(expressCheckoutDetailsResponse.PayerInfo, payPalBillingAddress, payment.BillingAddress, CustomerAddressTypeEnum.Billing, "CommitTranErrorPayPalBillingAddressEmpty"); if (!string.IsNullOrEmpty(emptyAddressMsg)) { RestoreSecurityProtocol(); return(ProcessUnsuccessfulTransaction(cancelUrl, emptyAddressMsg)); } } //process shipping address var payPalShippingAddress = expressCheckoutDetailsResponse.PaymentDetails[0].ShipToAddress; if (payPalShippingAddress != null && AddressHandling.IsAddressChanged(cart.GetFirstShipment().ShippingAddress, payPalShippingAddress)) { //when address was changed on PayPal site, it might cause changing tax value changed and changing order value also. var taxValueBefore = _taxCalculator.GetTaxTotal(cart, cart.Market, cart.Currency); var shippingAddress = orderGroup.CreateOrderAddress("address"); emptyAddressMsg = _payPalApiHelper.ProcessOrderAddress(expressCheckoutDetailsResponse.PayerInfo, payPalShippingAddress, shippingAddress, CustomerAddressTypeEnum.Shipping, "CommitTranErrorPayPalShippingAddressEmpty"); if (!string.IsNullOrEmpty(emptyAddressMsg)) { RestoreSecurityProtocol(); return(ProcessUnsuccessfulTransaction(cancelUrl, emptyAddressMsg)); } cart.GetFirstShipment().ShippingAddress = shippingAddress; var taxValueAfter = _taxCalculator.GetTaxTotal(cart, cart.Market, cart.Currency); if (taxValueBefore != taxValueAfter) { RestoreSecurityProtocol(); _orderRepository.Save(cart); // Saving cart to submit order address changed. scope.Complete(); return(ProcessUnsuccessfulTransaction(cancelUrl, Utilities.Translate("ProcessPaymentTaxValueChangedWarning"))); } } // Add request-specific fields to the request. // Create the request details object. var doExpressChkOutPaymentReqDetails = CreateExpressCheckoutPaymentRequest(getDetailsResponse, orderGroup, payment); // Execute the API operation and obtain the response. var doCheckOutResponse = caller.DoExpressCheckoutPayment(new DoExpressCheckoutPaymentReq { DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType(doExpressChkOutPaymentReqDetails) }); errorCheck = _payPalApiHelper.CheckErrors(doCheckOutResponse); if (!string.IsNullOrEmpty(errorCheck)) { RestoreSecurityProtocol(); // unsuccessful doCheckout response return(ProcessUnsuccessfulTransaction(cancelUrl, errorCheck)); } // everything is fine, this is a flag to tell ProcessPayment know about this case: redirect back from PayPal with accepted payment var errorMessages = new List <string>(); var cartCompleted = DoCompletingCart(cart, errorMessages); if (!cartCompleted) { RestoreSecurityProtocol(); return(UriSupport.AddQueryString(cancelUrl, "message", string.Join(";", errorMessages.Distinct().ToArray()))); } // Place order var purchaseOrder = MakePurchaseOrder(doCheckOutResponse, cart, payment); // Commit changes scope.Complete(); redirectionUrl = CreateRedirectionUrl(purchaseOrder, acceptUrl, payment.BillingAddress.Email); RestoreSecurityProtocol(); } _logger.Information($"PayPal transaction succeeds, redirect end user to {redirectionUrl}"); return(redirectionUrl); }
private DoExpressCheckoutPaymentRequestDetailsType CreateExpressCheckoutPaymentRequest(GetExpressCheckoutDetailsResponseType getDetailsResponse, IOrderGroup orderGroup, IPayment payment) { var checkoutDetailsResponse = getDetailsResponse.GetExpressCheckoutDetailsResponseDetails; var doExpressChkOutPaymentReqDetails = new DoExpressCheckoutPaymentRequestDetailsType { Token = payment.Properties[PayPalExpTokenPropertyName] as string, PayerID = checkoutDetailsResponse.PayerInfo.PayerID }; if (Enum.TryParse(_paymentMethodConfiguration.PaymentAction, out TransactionType transactionType)) { if (transactionType == TransactionType.Authorization) { doExpressChkOutPaymentReqDetails.PaymentAction = PaymentActionCodeType.AUTHORIZATION; } else if (transactionType == TransactionType.Sale) { doExpressChkOutPaymentReqDetails.PaymentAction = PaymentActionCodeType.SALE; } } var sentDetails = _payPalApiHelper.GetPaymentDetailsType(payment, orderGroup, payment.Properties[PayPalOrderNumberPropertyName] as string, _acceptUrl); doExpressChkOutPaymentReqDetails.PaymentDetails = new List <PaymentDetailsType> { sentDetails }; var newShippingAddressFromPayPal = checkoutDetailsResponse.PaymentDetails[0].ShipToAddress; if (newShippingAddressFromPayPal != null) { doExpressChkOutPaymentReqDetails.PaymentDetails[0].ShipToAddress = newShippingAddressFromPayPal; } return(doExpressChkOutPaymentReqDetails); }
/// <summary> /// Refunds a payment /// </summary> /// <param name="invoice">The invoice to be the payment was applied</param> /// <param name="payment">The payment to be refunded</param> /// <param name="paymentMethodKey">The key of the <see cref="IPaymentGatewayMethod"/></param> /// <param name="amount">The amount to be refunded</param> /// <param name="args">Additional arguements required by the payment processor</param> /// <returns>A <see cref="IPaymentResult"/></returns> public static IPaymentResult RefundPayment(this IPayment payment, IInvoice invoice, Guid paymentMethodKey, decimal amount, ProcessorArgumentCollection args) { return(payment.RefundPayment(MerchelloContext.Current, invoice, paymentMethodKey, amount, args)); }
/// <summary> /// Refunds a payment /// </summary> /// <param name="invoice">The invoice to be the payment was applied</param> /// <param name="payment">The payment to be refunded</param> /// <param name="paymentMethodKey">The key of the <see cref="IPaymentGatewayMethod"/></param> /// <param name="amount">The amount to be refunded</param> /// <returns>A <see cref="IPaymentResult"/></returns> public static IPaymentResult RefundPayment(this IPayment payment, IInvoice invoice, Guid paymentMethodKey, decimal amount) { return(payment.RefundPayment(invoice, paymentMethodKey, amount, new ProcessorArgumentCollection())); }
private IPurchaseOrder MakePurchaseOrder(DoExpressCheckoutPaymentResponseType doCheckOutResponse, ICart cart, IPayment payment) { var orderReference = _orderRepository.SaveAsPurchaseOrder(cart); var purchaseOrder = _orderRepository.Load <IPurchaseOrder>(orderReference.OrderGroupId); purchaseOrder.OrderNumber = payment.Properties[PayPalOrderNumberPropertyName] as string; // read PayPal's transactionId here, in order to store it, refund ... var paymentTransactionId = doCheckOutResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID; UpdateTransactionIdOfPaymentMethod(purchaseOrder, paymentTransactionId); // Update last order date time for CurrentContact UpdateLastOrderTimestampOfCurrentContact(CustomerContext.Current.CurrentContact, purchaseOrder.Created); AddCartNotesToPurchaseOrder(purchaseOrder, cart); AddNoteToPurchaseOrder(string.Empty, $"New order placed by {PrincipalInfo.CurrentPrincipal.Identity.Name} in Public site", Guid.Empty, purchaseOrder); AddCartPropertiesToPurchaseOrder(purchaseOrder, cart); // Remove old cart _orderRepository.Delete(cart.OrderLink); purchaseOrder.OrderStatus = OrderStatus.InProgress; // Update display name of product by current language Utilities.UpdateDisplayNameWithCurrentLanguage(purchaseOrder); _orderRepository.Save(purchaseOrder); return(purchaseOrder); }
public RegisterPaymentStep(IPayment payment) : base(payment) { }
/// <summary> /// Voids a payment /// </summary> /// <param name="invoice">The invoice to be the payment was applied</param> /// <param name="merchelloContext">The <see cref="IMerchelloContext"/></param> /// <param name="payment">The payment to be voided</param> /// <param name="paymentMethodKey">The <see cref="IPaymentGatewayMethod"/> key</param> /// <param name="args">Additional arguements required by the payment processor</param> /// <returns>A <see cref="IPaymentResult"/></returns> internal static IPaymentResult VoidPayment(this IInvoice invoice, IMerchelloContext merchelloContext, IPayment payment, Guid paymentMethodKey, ProcessorArgumentCollection args) { var paymentGatewayMethod = merchelloContext.Gateways.Payment.GetPaymentGatewayMethodByKey(paymentMethodKey); return(paymentGatewayMethod.VoidPayment(invoice, payment, args)); }
public abstract bool ProcessAuthorization(IPayment payment, IOrderGroup orderGroup, ref string message);
/// <summary> /// Voids a payment /// </summary> /// <param name="invoice">The invoice to be the payment was applied</param> /// <param name="payment">The payment to be voided</param> /// <param name="paymentMethodKey">The <see cref="IPaymentGatewayMethod"/> key</param> /// <returns>A <see cref="IPaymentResult"/></returns> public static IPaymentResult VoidPayment(this IInvoice invoice, IPayment payment, Guid paymentMethodKey) { return(invoice.VoidPayment(payment, paymentMethodKey, new ProcessorArgumentCollection())); }
/// <summary> /// Does the actual work of refunding the payment /// </summary> /// <param name="invoice">The invoice to be the payment was applied</param> /// <param name="payment">The payment to be refunded</param> /// <param name="amount">The amount of the payment to be refunded</param> /// <param name="args">Additional arguments required by the payment processor</param> /// <returns>A <see cref="IPaymentResult"/></returns> protected abstract IPaymentResult PerformRefundPayment(IInvoice invoice, IPayment payment, decimal amount, ProcessorArgumentCollection args);
/// <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 names = creditCard.CardholderName.Split(' '); // Declare a response Paymentech.Response response; // Create an authorize transaction var transaction = new Transaction(RequestType.NEW_ORDER_TRANSACTION); // Populate the required fields for the given transaction type. You can use’ // the Paymentech Transaction Appendix to help you populate the transaction’ /* * Message Types * MO – Mail Order transaction * RC – Recurring Payment * EC– eCommerce transaction * IV – IVR [PINLess Debit Only] */ transaction["IndustryType"] = "EC"; /* * Message Types * A – Authorization request * AC – Authorization and Mark for Capture * FC – Force-Capture request * R – Refund request */ transaction["MessageType"] = transactionMode == TransactionMode.Authorize ? "A" : "AC"; transaction["MerchantID"] = "041756"; transaction["BIN"] = "000001"; // Credit Card Number transaction["AccountNum"] = creditCard.CardNumber; transaction["OrderID"] = invoice.InvoiceNumber.ToString(CultureInfo.InstalledUICulture); transaction["Amount"] = amount.ToString("0.00", CultureInfo.InstalledUICulture); // Expiration date transaction["Exp"] = creditCard.ExpireMonth.PadLeft(2) + creditCard.ExpireYear; transaction["AVSname"] = address.Name; transaction["AVSaddress1"] = address.Address1; transaction["AVSaddress2"] = address.Address2; transaction["AVScity"] = address.Locality; transaction["AVSstate"] = address.Region; transaction["AVSzip"] = address.PostalCode; transaction["AVScountryCode"] = address.CountryCode; transaction["CardSecVal"] = creditCard.CardCode; /* * CardSecValInd * 1 - Value is Present * 2 - Value on card but illegible * 9 - Cardholder states data not available */ transaction["CardSecValInd"] = "1"; /* * CardSecValInd * A – Auto Generate the CustomerRefNum * S – Use CustomerRefNum Element */ transaction["CustomerProfileFromOrderInd"] = "A"; /* * CustomerProfileOrderOverrideInd * NO No mapping to order data * OI Use <CustomerRefNum> for <OrderID> and <ECOrderNum> or <MailOrderNum> * OD Use <CustomerReferNum> for <Comments> * OA Use <CustomerRefNum> for <OrderID> and <Comments> */ transaction["CustomerProfileOrderOverrideInd"] = "NO"; transaction["Comments"] = invoice.InvoiceNumber.ToString(CultureInfo.InstalledUICulture); response = transaction.Process(); // API Error if (response == null) { return(new PaymentResult(Attempt <IPayment> .Fail(payment, new Exception("Chase Paymentech unknown error")), invoice, false)); } if (response.Error) { return(new PaymentResult(Attempt <IPayment> .Fail(payment, new Exception(string.Format("Error {0}", response))), invoice, false)); } if (response.Declined) { payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.AuthorizeDeclinedResult, string.Format("Declined ({0} : {1})", response.ResponseCode, response.Message)); return(new PaymentResult(Attempt <IPayment> .Fail(payment, new Exception(string.Format("Declined ({0} : {1})", response.ResponseCode, response.Message))), invoice, false)); } if (response.Approved) { payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.TransactionReferenceNumber, string.Format("Approved ({0})", response.TxRefNum)); payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.AuthorizationTransactionCode, string.Format("{0},{1}", response.ResponseCode)); payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.AvsResult, response.AVSRespCode); 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}", response))), invoice, false)); }
private SetExpressCheckoutRequestDetailsType SetupExpressCheckoutReqDetailsType(ICart cart, IPayment payment, string orderNumber) { var setExpressChkOutReqDetails = _payPalApiHelper.CreateExpressCheckoutReqDetailsType(payment, _paymentMethodConfiguration); // This key is sent to PayPal using https so it is not likely it will come from other because // only PayPal knows this key to send back to us var acceptSecurityKey = Utilities.GetAcceptUrlHashValue(orderNumber); var cancelSecurityKey = Utilities.GetCancelUrlHashValue(orderNumber); _acceptUrl = UriSupport.AbsoluteUrlBySettings(_paymentMethodConfiguration.SuccessUrl); _cancelUrl = UriSupport.AbsoluteUrlBySettings(_paymentMethodConfiguration.CancelUrl); var acceptUrl = UriSupport.AddQueryString(_acceptUrl, "accept", "true"); acceptUrl = UriSupport.AddQueryString(acceptUrl, "hash", acceptSecurityKey); var cancelUrl = UriSupport.AddQueryString(_cancelUrl, "accept", "false"); cancelUrl = UriSupport.AddQueryString(cancelUrl, "hash", cancelSecurityKey); setExpressChkOutReqDetails.CancelURL = cancelUrl; setExpressChkOutReqDetails.ReturnURL = acceptUrl; setExpressChkOutReqDetails.PaymentDetails = new List <PaymentDetailsType> { _payPalApiHelper.GetPaymentDetailsType(payment, cart, orderNumber, _acceptUrl) }; setExpressChkOutReqDetails.BillingAddress = AddressHandling.ToAddressType(payment.BillingAddress); return(setExpressChkOutReqDetails); }
/// <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 address = invoice.GetBillingAddress(); // Declare a response Paymentech.Response response; // Create an authorize transaction var transaction = new Transaction(RequestType.MARK_FOR_CAPTURE_TRANSACTION); var txRefNum = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.TransactionReferenceNumber); if (!payment.Authorized || string.IsNullOrEmpty(txRefNum)) { return(new PaymentResult(Attempt <IPayment> .Fail(payment, new InvalidOperationException("Payment is not Authorized or TransactionCodes not present")), invoice, false)); } transaction["MerchantID"] = "041756"; transaction["BIN"] = "000001"; transaction["OrderID"] = invoice.InvoiceNumber.ToString(CultureInfo.InstalledUICulture); transaction["TaxInd"] = "1"; transaction["Tax"] = invoice.TotalTax().ToString(CultureInfo.InstalledUICulture); transaction["PCOrderNum"] = invoice.InvoiceNumber.ToString(CultureInfo.InstalledUICulture); transaction["PCDestZip"] = address.PostalCode; transaction["PCDestAddress1"] = address.Address1; transaction["PCDestAddress2"] = address.Address2; transaction["PCDestCity"] = address.Locality; transaction["PCDestState"] = address.Region; transaction["TxRefNum"] = txRefNum; response = transaction.Process(); // API Error if (response == null) { return(new PaymentResult(Attempt <IPayment> .Fail(payment, new Exception("Chase Paymentech unknown error")), invoice, false)); } if (response.Error) { return(new PaymentResult(Attempt <IPayment> .Fail(payment, new Exception(string.Format("Error {0}", response))), invoice, false)); } if (response.Declined) { payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.AuthorizeDeclinedResult, string.Format("Declined ({0} : {1})", response.ResponseCode, response.Message)); return(new PaymentResult(Attempt <IPayment> .Fail(payment, new Exception(string.Format("Declined ({0} : {1})", response.ResponseCode, response.Message))), invoice, false)); } if (response.Approved) { payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.TransactionReferenceNumber, string.Format("Approved ({0})", response.TxRefNum)); payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.AuthorizationTransactionCode, string.Format("{0},{1}", response.ResponseCode)); payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.AvsResult, response.AVSRespCode); 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}", response))), invoice, false)); }
public PaymentOperation(IPayment _odeme) { this._odeme = _odeme; }
/// <summary> /// Captures a payment for the <see cref="IInvoice"/> /// </summary> /// <param name="invoice">The invoice to be payed</param> /// <param name="payment">The</param> /// <param name="paymentMethodKey">The <see cref="IPaymentMethod"/> key</param> /// <param name="amount">The amount to the payment to be captured</param> /// <param name="args">Additional arguements required by the payment processor</param> /// <returns>A <see cref="IPaymentResult"/></returns> public static IPaymentResult CapturePayment(this IInvoice invoice, IPayment payment, Guid paymentMethodKey, decimal amount, ProcessorArgumentCollection args) { return(invoice.CapturePayment(MerchelloContext.Current, payment, paymentMethodKey, amount, args)); }
/// <summary> /// Create payment request /// </summary> /// <param name="paymentMethodDto"></param> /// <param name="payment"></param> /// <param name="orderForm"></param> /// <param name="orderGroup"></param> /// <returns></returns> private PaymentRequest CreatePaymentRequest(PaymentMethodDto paymentMethodDto, IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup) { var request = new PaymentRequest(); if (orderGroup.CustomerId != Guid.Empty) { var customerContact = CustomerContext.Current.GetContactById(orderGroup.CustomerId); if (customerContact != null) { request.PanHash = customerContact[NetaxeptConstants.CustomerPanHashFieldName]?.ToString(); } } var calculatedTotals = _orderGroupCalculator.Service.GetOrderGroupTotals(orderGroup); request.Amount = PaymentStepHelper.GetAmount(payment.Amount); request.TaxTotal = PaymentStepHelper.GetAmount(calculatedTotals.TaxTotal.Amount); request.CurrencyCode = orderGroup.Currency.CurrencyCode; request.OrderDescription = "Netaxept order"; request.OrderNumber = CartOrderNumberHelper.GenerateOrderNumber(orderGroup); request.Language = paymentMethodDto.GetParameter(NetaxeptConstants.TerminalLanguageField); request.EnableEasyPayments = bool.Parse(paymentMethodDto.GetParameter(NetaxeptConstants.EnableEasyPaymentField, "false")); request.SuccessUrl = payment.Properties.GetStringValue(NetaxeptConstants.CallbackUrl, string.Empty); request.CustomerNumber = (orderGroup.CustomerId != Guid.Empty ? orderGroup.CustomerId.ToString() : string.Empty); var billingAddress = payment.BillingAddress; if (billingAddress != null) { request.CustomerFirstname = billingAddress.FirstName; request.CustomerLastname = billingAddress.LastName; request.CustomerEmail = billingAddress.Email; request.CustomerAddress1 = billingAddress.Line1; request.CustomerAddress2 = !string.IsNullOrEmpty(billingAddress.Line2) ? billingAddress.Line2 : billingAddress.Line1; request.CustomerPostcode = billingAddress.PostalCode; request.CustomerTown = billingAddress.City; request.CustomerCountry = ConvertThreeLetterNameToTwoLetterName(billingAddress.CountryCode); request.CustomerPhoneNumber = GetValidPhonenumber(billingAddress.DaytimePhoneNumber ?? billingAddress.EveningPhoneNumber); } return(request); }
/// <summary> /// Does the actual work of voiding a payment /// </summary> /// <param name="invoice">The invoice to which the payment is associated</param> /// <param name="payment">The payment to be voided</param> /// <param name="args">Additional arguments required by the payment processor</param> /// <returns>A <see cref="IPaymentResult"/></returns> protected override IPaymentResult PerformVoidPayment(IInvoice invoice, IPayment payment, ProcessorArgumentCollection args) { throw new System.NotImplementedException(); }
internal static PaymentDisplay ToPaymentDisplay(this IPayment payment) { return(AutoMapper.Mapper.Map <PaymentDisplay>(payment)); }
protected AuthorizePaymentStepBase(IPayment payment, MarketId marketId, KlarnaOrderServiceFactory klarnaOrderServiceFactory) : base(payment, marketId, klarnaOrderServiceFactory) { }
public static async Task FillInfo( ApplicationDbContext context, IPayment paymentService, Member member) { IWebDriver driver = new FirefoxDriver(Environment.CurrentDirectory); driver.Url = member.RegisterLink; // **********FILL IN INFO************* WebDriverWait waitFillInfo = new WebDriverWait(driver, TimeSpan.FromMinutes(1)); waitFillInfo.Until(c => c.FindElement(By.XPath("//*[@id='main']/div[2]/section/form/div[2]/div/button"))); IWebElement favourite1Radio = driver.FindElement(By.CssSelector("input#artist_0 + label")); IWebElement favourite2Radio = driver.FindElement(By.CssSelector("input#artist_1 + label")); IWebElement favourite3Radio = driver.FindElement(By.CssSelector("input#artist_2 + label")); IWebElement favourite4Radio = driver.FindElement(By.CssSelector("input#artist_3 + label")); IWebElement favourite5Radio = driver.FindElement(By.CssSelector("input#artist_4 + label")); IWebElement chineseLastNameText = driver.FindElement(By.Id("member-name")); IWebElement chineseFirstNameText = driver.FindElement(By.Id("member-name2")); IWebElement katakanaLastNameText = driver.FindElement(By.Name("family_name_kn")); IWebElement katakanaFirstNameText = driver.FindElement(By.Name("name_kn")); IWebElement zipCodeText = driver.FindElement(By.Id("zip")); SelectElement addressSelect = new SelectElement(driver.FindElement(By.Name("address_1"))); IWebElement cityText = driver.FindElement(By.Id("city")); IWebElement areaText = driver.FindElement(By.Id("area")); IWebElement buildingText = driver.FindElement(By.Id("building")); IWebElement roomText = driver.FindElement(By.Id("room_no")); IWebElement careOfText = driver.FindElement(By.Id("care_of")); IWebElement tel1Text = driver.FindElement(By.Id("tel1")); IWebElement tel2Text = driver.FindElement(By.Id("tel2")); IWebElement tel3Text = driver.FindElement(By.Id("tel3")); IWebElement mobile1Text = driver.FindElement(By.Id("mobile1")); IWebElement mobile2Text = driver.FindElement(By.Id("mobile2")); IWebElement mobile3Text = driver.FindElement(By.Id("mobile3")); SelectElement birthdayYearSelect = new SelectElement(driver.FindElement(By.Id("birthday-year"))); SelectElement birthdayMonthSelect = new SelectElement(driver.FindElement(By.Name("birthday[month]"))); SelectElement birthdayDaySelect = new SelectElement(driver.FindElement(By.Name("birthday[day]"))); IWebElement ageText = driver.FindElement(By.Id("age")); SelectElement sexSelect = new SelectElement(driver.FindElement(By.Id("sex"))); IWebElement password1Text = driver.FindElement(By.Id("password1")); IWebElement password2Text = driver.FindElement(By.Id("password2")); IWebElement submitButton = driver.FindElement(By.XPath("//*[@id='main']/div[2]/section/form/div[2]/div/button")); chineseLastNameText.SendKeys(member.ChineseLastName); chineseFirstNameText.SendKeys(member.ChineseFirstName); katakanaLastNameText.SendKeys(member.KatakanaLastName); katakanaFirstNameText.SendKeys(member.KatakanaFirstName); zipCodeText.SendKeys("6580032"); addressSelect.SelectByValue("兵庫県"); cityText.SendKeys("神戸市東灘区"); areaText.SendKeys("向洋町中1丁目17"); buildingText.SendKeys("アジアワンセンター"); roomText.SendKeys("room " + member.Id); //further develop later string careOf = member.EnglishFirstName + " " + member.EnglishLastName; careOfText.SendKeys(careOf); tel1Text.SendKeys("078"); tel2Text.SendKeys("856"); tel3Text.SendKeys("6368"); // mobile1Text.SendKeys("99999"); // mobile2Text.SendKeys("88888"); // mobile3Text.SendKeys(member.Phone); birthdayYearSelect.SelectByValue(member.BirthDate.Year.ToString()); birthdayMonthSelect.SelectByValue(member.BirthDate.Month.ToString()); birthdayDaySelect.SelectByValue(member.BirthDate.Day.ToString()); ageText.SendKeys(CalculateAge(member.BirthDate).ToString()); if (member.Gender == "F") { sexSelect.SelectByIndex(0); } else if (member.Gender == "M") { sexSelect.SelectByIndex(1); } // 6 大野智 7 櫻井翔 8 相葉 9 二宮 10 松本 if (member.Favourite.Name == "大野智") { favourite4Radio.Click(); } if (member.Favourite.Name == "櫻并翔") { favourite5Radio.Click(); } if (member.Favourite.Name == "相葉雅紀") { favourite1Radio.Click(); } if (member.Favourite.Name == "二宮和也") { favourite3Radio.Click(); } if (member.Favourite.Name == "松本潤") { favourite2Radio.Click(); } password1Text.SendKeys("PPass12345word"); password2Text.SendKeys("PPass12345word"); submitButton.Submit(); // **********CONFIRM INFO************* WebDriverWait waitConfirm = new WebDriverWait(driver, TimeSpan.FromMinutes(1)); waitConfirm.Until(c => c.FindElement(By.ClassName("checkbox"))); IWebElement agreement = driver.FindElement(By.ClassName("checkbox")); agreement.Click(); IWebElement confirmButton = driver.FindElement(By.XPath("/html/body/div/main/div[2]/section/form/div[2]/div[3]/button")); confirmButton.Click(); // **********CREATE PAYMENT************* WebDriverWait waitPayment = new WebDriverWait(driver, TimeSpan.FromMinutes(1)); waitPayment.Until(c => c.FindElement(By.XPath("/html/body/div/main/div[2]/section/div/div[4]/div[6]/div/p"))); IWebElement limitLabel = driver.FindElement(By.XPath("/html/body/div/main/div[2]/section/div/div[4]/div[2]/div/p")); IWebElement amountLabel = driver.FindElement(By.XPath("/html/body/div/main/div[2]/section/div/div[4]/div[3]/div/p")); IWebElement bankLabel = driver.FindElement(By.XPath("/html/body/div/main/div[2]/section/div/div[4]/div[4]/div/p")); IWebElement customerLabel = driver.FindElement(By.Id("payeasyCustId")); IWebElement confirmLabel = driver.FindElement(By.XPath("/html/body/div/main/div[2]/section/div/div[4]/div[6]/div/p")); var newPayment = new Payment { Limit = limitLabel.Text, Amount = amountLabel.Text, PaymentBank = bankLabel.Text, PaymentCustomer = customerLabel.Text, PaymentConfirm = confirmLabel.Text, Paid = false, MemberId = member.Id, Member = member }; await paymentService.Create(newPayment); driver.Close(); // but this part of code is also expected to return something // return Task.Run(() => { Console.WriteLine("Hello Task library!"); }); }
/// <summary> /// Refunds a payment /// </summary> /// <param name="invoice">The invoice to be the payment was applied</param> /// <param name="payment">The payment to be refunded</param> /// <param name="paymentGatewayMethod">The <see cref="IPaymentGatewayMethod"/></param> /// <param name="amount">The amount to be refunded</param> /// <param name="args">Additional arguements required by the payment processor</param> /// <returns>A <see cref="IPaymentResult"/></returns> public static IPaymentResult RefundPayment(this IPayment payment, IInvoice invoice, IPaymentGatewayMethod paymentGatewayMethod, decimal amount, ProcessorArgumentCollection args) { return(paymentGatewayMethod.RefundPayment(invoice, payment, amount, args)); }
/// <summary> /// Captures an authorized payment. /// </summary> /// <para> /// See API doc here https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/DoCapture_API_Operation_SOAP/ /// </para> /// <param name="orderGroup">The order group to process.</param> /// <param name="payment">The payment to process</param> /// <returns>return false and set the message will make the WorkFlow activity raise PaymentExcetion(message)</returns> private PaymentProcessingResult ProcessPaymentCapture(IOrderGroup orderGroup, IPayment payment) { // Implement refund feature logic for current payment gateway var captureAmount = payment.Amount; if (!(orderGroup is IPurchaseOrder purchaseOrder) || captureAmount <= 0) { return(PaymentProcessingResult.CreateUnsuccessfulResult("Nothing to capture")); } var captureRequest = new DoCaptureRequestType { AuthorizationID = payment.TransactionID, // original transactionID (which PayPal gave us when DoExpressCheckoutPayment, DoDirectPayment, or CheckOut) Amount = _payPalApiHelper.ToPayPalAmount(captureAmount, orderGroup.Currency), // if refund with Partial, we have to set the Amount CompleteType = payment.Amount >= purchaseOrder.GetTotal().Amount ? CompleteCodeType.COMPLETE : CompleteCodeType.NOTCOMPLETE, InvoiceID = purchaseOrder.OrderNumber }; captureRequest.Note = $"[{payment.PaymentMethodName}-{payment.TransactionID}] captured {captureAmount}{captureRequest.Amount.currencyID} for [PurchaseOrder-{purchaseOrder.OrderNumber}]"; var caller = PayPalApiHelper.GetPayPalApiCallerServices(_paymentMethodConfiguration); var doCaptureReq = new DoCaptureReq { DoCaptureRequest = captureRequest }; var captureResponse = caller.DoCapture(doCaptureReq); var errorCheck = _payPalApiHelper.CheckErrors(captureResponse); if (!string.IsNullOrEmpty(errorCheck)) { return(PaymentProcessingResult.CreateUnsuccessfulResult(errorCheck)); } var captureResponseDetails = captureResponse.DoCaptureResponseDetails; var paymentInfo = captureResponseDetails.PaymentInfo; // Extract the response details. payment.ProviderTransactionID = paymentInfo.TransactionID; payment.Status = paymentInfo.PaymentStatus.ToString(); var message = $"[{payment.PaymentMethodName}] [Capture payment-{paymentInfo.TransactionID}] [Status: {paymentInfo.PaymentStatus.ToString()}] " + $".Response: {captureResponse.Ack.ToString()} at Timestamp={captureResponse.Timestamp}: {paymentInfo.GrossAmount.value}{paymentInfo.GrossAmount.currencyID}"; // add a new order note about this capture AddNoteToPurchaseOrder("CAPTURE", message, purchaseOrder.CustomerId, purchaseOrder); _orderRepository.Save(purchaseOrder); return(PaymentProcessingResult.CreateSuccessfulResult(message)); }