public void Update(PaymentTransaction paymentTransaction) { PaymentTransaction original = _dbContext.PaymentTransactions.FirstOrDefault(x => x.Id == paymentTransaction.Id); if (original == null) return; original.Amount = paymentTransaction.Amount; original.PayerId = paymentTransaction.PayerId; original.Status = paymentTransaction.Status; original.PaymentId = paymentTransaction.PaymentId; _dbContext.SaveChanges(); }
public ActionResult Pay(double? amount) { var currentUser = _userRepository.GetByUsername(User.Identity.Name); try { var payerId = Request.Params["PayerID"]; if (string.IsNullOrEmpty(payerId)) { if(!amount.HasValue) throw new Exception("Invalid amount"); var baseUri = string.Format("{0}://{1}/Paypal/pay?", Request.Url.Scheme, Request.Url.Authority); var paymentResponse = _paypalProcessor.CreatePayment(baseUri, amount.Value); var paymentTransaction = new PaymentTransaction { Amount = amount.Value, CreateDate = DateTime.Now, PaymentId = paymentResponse.PaymentId, Status = PaymentTransactionStatus.Pending, User = currentUser, PaymentAction = PaymentAction.Deposit, }; _paymentTransactionRepository.Add(paymentTransaction); Session.Add(paymentResponse.Guid, paymentResponse.PaymentId); return Redirect(paymentResponse.RedirectUrl); } var guid = Request.Params["guid"]; var paymentId = Session[guid] as string; var existingPaymentTransaction = _paymentTransactionRepository.GetByPaymentId(paymentId); var executedPayment = _paypalProcessor.ExecutePayment(payerId, paymentId); existingPaymentTransaction.PayerId = payerId; if (executedPayment.state.ToLower() != "approved") { existingPaymentTransaction.Status = PaymentTransactionStatus.Failed; _paymentTransactionRepository.Update(existingPaymentTransaction); return RedirectToAction("Index", "Balance", new {message = 2}); } existingPaymentTransaction.Status = PaymentTransactionStatus.Success; _paymentTransactionRepository.Update(existingPaymentTransaction); currentUser.Balance += existingPaymentTransaction.Amount; _userRepository.Update(currentUser); return RedirectToAction("Index", "Balance", new { message = 1 }); } catch (Exception ex) { return RedirectToAction("Index", "Balance", new {message = 2}); } }
public ITransactionCaptureResult CapturePayment(PaymentTransaction transaction) { var plugin = GetPluginInstance(transaction.PaymentProcessorSystemName); //plugin should be available and if it's an authorization transaction, the plugin should actually support authorize and capture/void if (plugin == null || !plugin.CaptureSupported) return null; var captureResult = plugin.Capture(new TransactionRequest() { Amount = transaction.TransactionAmount, Parameters = transaction.TransactionCodes }); return captureResult; }
/// <summary> /// 获取支付Html /// </summary> public void GetPaymentHtml(PaymentTransaction transaction, ref HtmlString html) { throw new NotImplementedException(); }
public void Add(PaymentTransaction entity) { _dbContext.PaymentTransactions.Add(entity); _dbContext.SaveChanges(); }
public void Create(PaymentTransaction paymentTransaction) { paymentTransaction.Description = $"Monto total: {paymentTransaction.TotalAmount.ToString()}, fecha: {paymentTransaction.TransactionDate.ToString()}"; paymentTransactionCrud.Create(paymentTransaction); }
public TransactionStatusChangedDomainEvent(PaymentTransaction transaction) { this.PaymentTransaction = transaction; }
public void CreatePayment(PaymentTransaction payment) { _restResponse = _requestWrapper.Create("/payment_transactions", payment); }
public IActionResult GetBlueSnapSubscription(string subscriptionId) { string responseFromServer = string.Empty; try { // Create a request using a URL that can receive a post. HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://sandbox.bluesnap.com/services/2/recurring/subscriptions/" + subscriptionId); // Set the Method property of the request to POST. request.Method = "GET"; request.Headers["Authorization"] = "Basic " + _appSettings.bluesnapBase64; request.UserAgent = ".NET Framework Test Client"; request.ContentType = "application/json"; ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // Get the response. HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse(); Console.WriteLine((myHttpWebResponse.StatusDescription)); Stream dataStream = myHttpWebResponse.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); responseFromServer = reader.ReadToEnd(); Console.WriteLine(responseFromServer); reader.Close(); dataStream.Close(); myHttpWebResponse.Close(); } catch (WebException wex) { var pageContent = new StreamReader(wex.Response.GetResponseStream()) .ReadToEnd(); Console.WriteLine(wex.Message); } Dictionary <string, string> planValues = new Dictionary <string, string>(); //XML XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(responseFromServer); try { string jsonText = JsonConvert.SerializeXmlNode(xmlDoc); JObject responseJson = JObject.Parse(jsonText); string temp = responseJson["recurring-subscription"]["plan-id"].ToString(); DatabaseRepository dbr = new DatabaseRepository(_logger, _appEnv); try { PaymentTransaction objPaymentTransaction = dbr.Single <PaymentTransaction>(t => t.trasactionId == subscriptionId); if (objPaymentTransaction.paymentdate.Date != DateTime.Now.Date && objPaymentTransaction != null) { objPaymentTransaction.amount = responseJson["recurring-subscription"]["recurring-charge-amount"].ToString(); objPaymentTransaction.paymentdate = DateTime.UtcNow; objPaymentTransaction.bluesnapSubscriptions++; dbr.Update(objPaymentTransaction); } } catch { } } catch { } return(Ok()); }
public IActionResult PostBlueSnapSubscription(string XMLData, string emailId) { string responseFromServer = string.Empty; try { // Create a request using a URL that can receive a post. HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://sandbox.bluesnap.com/services/2/recurring/subscriptions"); // Set the Method property of the request to POST. request.Method = "POST"; request.Headers["Authorization"] = "Basic " + _appSettings.bluesnapBase64; request.UserAgent = ".NET Framework Test Client"; string postData = XMLData; byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentType = "application/xml"; request.ContentLength = byteArray.Length; ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); // Get the response. HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse(); Console.WriteLine((myHttpWebResponse.StatusDescription)); dataStream = myHttpWebResponse.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); responseFromServer = reader.ReadToEnd(); Console.WriteLine(responseFromServer); reader.Close(); dataStream.Close(); myHttpWebResponse.Close(); } catch (WebException wex) { var pageContent = new StreamReader(wex.Response.GetResponseStream()) .ReadToEnd(); Console.WriteLine(wex.Message); return(BadRequest()); } DatabaseRepository dbr = new Model.DatabaseRepository(_logger, _appEnv); try { //JSON XmlDocument doc = new XmlDocument(); doc.LoadXml(responseFromServer); JObject jsonTextResponse = JObject.Parse(JsonConvert.SerializeXmlNode(doc)); User userObj = dbr.FindSingle <User>(t => t.EmailId == emailId); PaymentTransaction objPaymentTransaction = new PaymentTransaction(); objPaymentTransaction.amount = jsonTextResponse["recurring-subscription"]["recurring-charge-amount"].ToString(); objPaymentTransaction.userid = userObj.Id; objPaymentTransaction.email = userObj.EmailId; objPaymentTransaction.paymentdate = DateTime.UtcNow; objPaymentTransaction.trasactionId = jsonTextResponse["recurring-subscription"]["subscription-id"].ToString(); try { objPaymentTransaction.paymentId = jsonTextResponse["recurring-subscription"]["charge"]["charge-id"].ToString(); } catch { objPaymentTransaction.paymentId = "NA"; } objPaymentTransaction.PaymentType = Domain.Socioboard.Enum.PaymentType.bluesnap; try { objPaymentTransaction.paymentstatus = jsonTextResponse["recurring-subscription"]["status"].ToString(); } catch { objPaymentTransaction.paymentstatus = "NA"; } objPaymentTransaction.itemname = "Socioboard" + userObj.AccountType.ToString(); objPaymentTransaction.Payername = userObj.FirstName + " " + userObj.LastName; objPaymentTransaction.email = userObj.EmailId; dbr.Add <PaymentTransaction>(objPaymentTransaction); userObj.ExpiryDate = DateTime.Now.AddYears(1); userObj.PaymentStatus = Domain.Socioboard.Enum.SBPaymentStatus.Paid; userObj.TrailStatus = Domain.Socioboard.Enum.UserTrailStatus.active; userObj.PayPalAccountStatus = Domain.Socioboard.Enum.PayPalAccountStatus.added; userObj.PaymentType = Domain.Socioboard.Enum.PaymentType.bluesnap; dbr.Update <User>(userObj); return(Ok()); } catch { return(BadRequest()); } }
//return RedirectToAction("Index", "Balance", new {message = 2}); //return RedirectToAction("Index", "Balance", new {message = 1}); public ActionResult Widthdraw() { var user = _userRepository.GetByUsername(User.Identity.Name); if(user.AvailableForWithdrawal < 5.0) throw new Exception("Invalid amount"); var amountString = string.Format(CultureInfo.InvariantCulture, "{0:0.00}", user.AvailableForWithdrawal); var paypalConfig = new Dictionary<string, string>(); paypalConfig.Add("apiUsername", "gigbucket_test7_api1.test.ru"); paypalConfig.Add("apiPassword", "ANCAZ9WSDHPQ8Y8U"); paypalConfig.Add("apiSignature", "AFcWxV21C7fd0v3bYYYRCpSSRl31A2cPmRQaJrQqtqnGQmQpAFCNohRs"); paypalConfig.Add("mode", "sandbox"); MassPayResponseType responseMassPayResponseType = new MassPayResponseType(); try { MassPayReq massPay = new MassPayReq(); List<MassPayRequestItemType> massPayItemList = new List<MassPayRequestItemType>(); BasicAmountType amount = new BasicAmountType(CurrencyCodeType.USD, amountString); MassPayRequestItemType massPayRequestItem = new MassPayRequestItemType(amount); // Email Address of receiver massPayRequestItem.ReceiverEmail = user.Email; massPayItemList.Add(massPayRequestItem); MassPayRequestType massPayRequest = new MassPayRequestType(massPayItemList); massPay.MassPayRequest = massPayRequest; // Create the service wrapper object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(paypalConfig); // # API call // Invoke the massPay method in service wrapper object responseMassPayResponseType = service.MassPay(massPay, new SignatureCredential(paypalConfig["apiUsername"], paypalConfig["apiPassword"], paypalConfig["apiSignature"])); if (responseMassPayResponseType != null) { // # Success values if (responseMassPayResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS")) { var paymentTransaction = new PaymentTransaction { Amount = user.AvailableForWithdrawal, CreateDate = DateTime.Now, PaymentId = responseMassPayResponseType.Version, Status = PaymentTransactionStatus.Success, User = user, PaymentAction = PaymentAction.Withdrawal, }; _paymentTransactionRepository.Add(paymentTransaction); user.Balance = user.Balance - user.AvailableForWithdrawal; user.AvailableForWithdrawal = 0; _userRepository.Update(user); return RedirectToAction("Index", "Balance", new { message = 1 }); } // # Error Values else { var paymentTransaction = new PaymentTransaction { Amount = user.AvailableForWithdrawal, CreateDate = DateTime.Now, PaymentId = responseMassPayResponseType.Version, Status = PaymentTransactionStatus.Failed, User = user, PaymentAction = PaymentAction.Withdrawal, }; _paymentTransactionRepository.Add(paymentTransaction); return RedirectToAction("Index", "Balance", new { message = 2 }); } } } // # Exception log catch (Exception ex) { var paymentTransaction = new PaymentTransaction { Amount = user.AvailableForWithdrawal, CreateDate = DateTime.Now, PaymentId = "", Status = PaymentTransactionStatus.Failed, User = user, PaymentAction = PaymentAction.Withdrawal, }; _paymentTransactionRepository.Add(paymentTransaction); return RedirectToAction("Index", "Balance", new { message = 2 }); } return RedirectToAction("Index", "Balance", new { message = 2 }); ; }
public IHttpActionResult ProcessPayment(FormCollection parameters) { //first get the payment processor var paymentMethodName = parameters.Get(PaymentParameterNames.PaymentMethodTypeName); if (string.IsNullOrEmpty(paymentMethodName)) { VerboseReporter.ReportError("Invalid payment method", "process_payment"); return RespondFailure(); } //the transaction amount decimal amount; var amountString = parameters.Get(PaymentParameterNames.Amount) ?? "0"; decimal.TryParse(amountString, out amount); PaymentMethodType methodType; if (System.Enum.TryParse(paymentMethodName, out methodType)) { methodType = PaymentMethodType.CreditCard; } //get the payment processor now var paymentProcessor = _paymentProcessingService.GetPaymentProcessorPlugin(amount, methodType); if (paymentProcessor == null) { VerboseReporter.ReportError("Invalid payment method", "process_payment"); return RespondFailure(); } //convert form collection to dictionary to check if parameters are valid var formCollectionDictionary = parameters.ToDictionary(pair => pair.Key, pair => (object)pair.Value); var isValid = paymentProcessor.AreParametersValid(formCollectionDictionary); UserPaymentMethod paymentMethod = null; if (!isValid) { //the parameters are not valid. but that may also mean that the user is selecting an already saved payment method //and so he wouldn't have sent that data again var savedPaymentMethodIdString = parameters.Get(PaymentParameterNames.UserSavedPaymentMethodId); int savedPaymentMethodId; if (int.TryParse(savedPaymentMethodIdString, out savedPaymentMethodId)) { var userPaymentMethods = _paymentMethodService.Get(x => x.UserId == ApplicationContext.Current.CurrentUser.Id && x.Id == savedPaymentMethodId, null); if (userPaymentMethods.Any()) { paymentMethod = userPaymentMethods.First(); isValid = true; } } //still invalid? something is not right then. if (!isValid) { VerboseReporter.ReportError("Invalid parameters to process payment", "process_payment"); return RespondFailure(); } } //we save the payment method in our database if it's CreditCard if (paymentProcessor.Supports(PaymentMethodType.CreditCard)) { if (paymentMethod == null) { #region saving payment method to database var creditCardNumber = parameters.Get(PaymentParameterNames.CardNumber); //let's validate the card for level 1 check (luhn's test) first before storing var isCardValid = PaymentCardHelper.IsCardNumberValid(creditCardNumber); //card number if (!isCardValid) { VerboseReporter.ReportError("Invalid card number", "process_payment"); return RespondFailure(); } //expiration date var expireMonth = parameters.Get(PaymentParameterNames.ExpireMonth); var expireYear = parameters.Get(PaymentParameterNames.ExpireYear); if (!expireYear.IsInteger() || !expireMonth.IsInteger()) { VerboseReporter.ReportError("Invalid expiration month or year", "process_payment"); return RespondFailure(); } //card issuer var cardIssuer = PaymentCardHelper.GetCardTypeFromNumber(creditCardNumber); if (!cardIssuer.HasValue) { VerboseReporter.ReportError("Unsupported card provider", "process_payment"); return RespondFailure(); } var nameOnCard = parameters.Get(PaymentParameterNames.NameOnCard); //encrypt credit card info to store in db var key = ConfigurationManager.AppSettings.Get("EncryptionKey"); var salt = ConfigurationManager.AppSettings.Get("Salt"); var cardNumber = _cryptographyService.Encrypt(creditCardNumber, key, salt); //encrypt the card info //fine if the card is valid, but is the card number already in our record, then not possible to save the same again if (_paymentMethodService.DoesCardNumberExist(cardNumber)) { VerboseReporter.ReportError("The card number is already saved in records", "process_payment"); return RespondFailure(); } paymentMethod = new UserPaymentMethod() { UserId = ApplicationContext.Current.CurrentUser.Id, IsVerified = false, PaymentMethodType = PaymentMethodType.CreditCard, CardIssuerType = cardIssuer.ToString().ToLowerInvariant(), CardNumber = creditCardNumber, CardNumberMasked = PaymentCardHelper.MaskCardNumber(creditCardNumber), NameOnCard = nameOnCard, }; //save this payment method _paymentMethodService.Insert(paymentMethod); #endregion } } //we need to see if we should only authorize or capture as well //the idea is if it's a sponsorship context, it's better to authorize the payment transaction and capture later when //the sponsorship is accepted //we thought of initially only authorizing sponsorship transactions and capture when it's accepted. //but that flow doesn't seem to work quite well, thoughts? var authorizeOnly = false; // (parameters.Get(PaymentParameterNames.PaymentContext) ?? string.Empty) == "sponsor"; //so we are ready for payment processing, let's create a paymenttrasaction for storing in our db var paymentTransaction = new PaymentTransaction() { IsLocalTransaction = true, PaymentStatus = PaymentStatus.Pending, TransactionAmount = amount, TransactionGuid = Guid.NewGuid(), CreatedOn = DateTime.UtcNow, UserIpAddress = WebHelper.GetClientIpAddress() }; _paymentTransactionService.Insert(paymentTransaction); //now proceed further with the payment //create the transaction request var transactionRequest = new TransactionRequest() { Amount = amount, CurrencyIsoCode = "USD",//TODO: SET CURRENCY AS SELECTED BY USER PaymentProcessorSystemName = paymentProcessor.PluginInfo.SystemName, UserId = ApplicationContext.Current.CurrentUser.Id, Parameters = formCollectionDictionary, TransactionUniqueId = paymentTransaction.TransactionGuid.ToString() }; var response = paymentProcessor.Process(transactionRequest, authorizeOnly); //update values of transaction parameters for future reference paymentTransaction.TransactionCodes = response.ResponseParameters; //update payment transaction _paymentTransactionService.Update(paymentTransaction); if (response.Success) { //let's verify the payment method first if it's not if (paymentMethod != null && !paymentMethod.IsVerified) { paymentMethod.IsVerified = true; _paymentMethodService.Update(paymentMethod); } //now since the response was success, we can actually assign some credits to the user var creditCount = amount * (1 / _paymentSettings.CreditExchangeRate); var credit = new Credit() { PaymentTransactionId = paymentTransaction.Id, CreatedOnUtc = DateTime.UtcNow, CreditCount = creditCount, CreditExchangeRate = _paymentSettings.CreditExchangeRate, //if it's authorize only transaction, we assign the credits, but they won't be usable before they are approved by capture CreditTransactionType = CreditTransactionType.Issued, CreditType = CreditType.Transactional, IsExpired = false }; //save credit _creditService.Insert(credit); //get total available credits of user var usableCreditCount = _creditService.GetUsableCreditsCount(ApplicationContext.Current.CurrentUser.Id); return RespondSuccess(new { UsableCreditCount = usableCreditCount }); } VerboseReporter.ReportError("An error occured while processing payment", "process_payment"); return RespondFailure(); }
public Task StorePaymentAsync(Guid id, PaymentTransaction payment) { cache.Add(id.ToString(), payment, cachePolicy); return(Task.CompletedTask); }
public void ProcessRequest(HttpContext context) { try { CardNumber = ""; // Remove non-digits for (int i = 0; i < Provider.Request["CardNumber"].Length; i++) { if (char.IsDigit(Provider.Request["CardNumber"], i)) { CardNumber += Provider.Request["CardNumber"][i].ToString(); } } int year = 0; int.TryParse(Provider.Request["ExpiryYear"], out year); if (year < DateTime.Now.Year) { throw new Exception("Son kullanma tarihi yanlış"); } int month = 0; int.TryParse(Provider.Request["ExpiryMonth"], out month); if (!(month >= 1 && month <= 12)) { throw new Exception("Son kullanma tarihi yanlış"); } ExpiryDate = Provider.Request["ExpiryYear"] + Provider.Request["ExpiryMonth"]; CVV2 = Provider.Request["CVV2"]; if (CVV2.Length != 3 || !CVV2.CanConvertToInteger()) { throw new Exception("CCV2 kodu hatalı"); } CardType = (CardType)Enum.Parse(typeof(CardType), Provider.Request["CardType"]); string cardValid = Utility.ValidateCreditCardNumber(CardType, CardNumber); if (cardValid != "") { context.Response.Write("HATA: " + cardValid); return; } if (Transact()) { try { PaymentTransaction s = new PaymentTransaction(); s.Amount = AmountInCents; s.CheckoutType = CheckoutTypes.CreditCard; s.Result = Response; s.Save(); } catch (Exception ex) { string msg = (AmountInCents / 100d) + " TL tahsil edildi. Bu bilgi bir hata nedeniyle veritabanına kaydedilemedi. Lütfen bu bilgiyi manuel olarak kaydediniz."; Provider.SendMail("Tahsilat yapıldı ama sisteme kaydedilemedi!!!", msg); Provider.Log("Error", "Checkout", msg); } context.Response.Write("OK"); } else { context.Response.Write("HATA: Ödemenizin onaylanmasında bir hata oluştu."); Provider.Log("Error", "Checkout", (AmountInCents / 100d) + " TL tahsil edilmek istendi ama servisten " + ResponseErrorNo + " nolu hata döndü. (" + ResponseErrorMessage + ")"); } } catch (Exception ex) { context.Response.Write("HATA: " + ex.Message); Provider.Log("Error", "Checkout", ex.Message + (ex.InnerException != null ? "(" + ex.InnerException.Message + ")" : "")); } }
public void Save(PaymentTransaction paymentTransaction) { Save(paymentTransaction.Authorization); Save(paymentTransaction.Capture); }
public override async Task <PaymentUrlResponse> GetPaymentUrl(PaymentUrlRequest request, ServerCallContext context) { try { string errorMessage = string.Empty; ErrorDetails.Types.ErrorType?errorType = null; if (_supportedCurrencies.Any() && !_supportedCurrencies.Contains(request.Transaction.AssetId)) { errorMessage = $"Asset {request.Transaction.AssetId} is not supported"; errorType = ErrorDetails.Types.ErrorType.CurrencyNotSupported; } if (_supportedCountries.Any() && !string.IsNullOrEmpty(request.Details.CountryIso3) && !_supportedCountries.Contains(request.Details.CountryIso3)) { errorMessage = $"Country {request.Details.CountryIso3} is not supported"; errorType = ErrorDetails.Types.ErrorType.CountryNotSupported; } if (errorType != null) { _log.Warning(errorMessage); return(new PaymentUrlResponse { Error = new ErrorDetails { ErrorType = errorType.Value, Message = errorMessage } }); } var bankCardsFees = await _feeCalculatorClient.GetBankCardFees(); var feeAmount = Math.Round(request.Transaction.Amount * bankCardsFees.Percentage, 15); var totalAmount = (decimal)request.Transaction.Amount + (decimal)feeAmount; var url = await _link4PayApiService.GetPaymentUrlAsync(new CardPaymentRequest { Merchant = new MerchantInfo { CustomerId = request.Transaction.ExternalClientId, MerchantId = _link4PaySettings.ClientId }, Transaction = new TransactionInfo { TxnAmount = totalAmount.ToString("F2"), CurrencyCode = request.Transaction.AssetId, TxnReference = request.Transaction.TransactionId, Payout = false }, Customer = new CustomerInfo { BillingAddress = new AddressInfo { FirstName = request.Details?.FirstName, LastName = request.Details?.LastName, EmailId = request.Details?.Email, MobileNo = request.Details?.Phone } }, Url = new UrlInfo { SuccessUrl = $"{(string.IsNullOrEmpty(request.Urls?.OkUrl?.Trim()) ? _successUrl : request.Urls?.OkUrl)}?v=1", FailUrl = string.IsNullOrEmpty(request.Urls?.FailUrl?.Trim()) ? _failUrl : request.Urls?.FailUrl, CancelUrl = string.IsNullOrEmpty(request.Urls?.CancelUrl?.Trim()) ? _cancelUrl : request.Urls?.CancelUrl } }); if (string.IsNullOrEmpty(url)) { return(new PaymentUrlResponse { Error = new ErrorDetails { ErrorType = ErrorDetails.Types.ErrorType.Unknown, Message = "Error getting the payment url" } }); } await _rawLogRepository.RegisterEventAsync( RawLogEvent.Create("Payment Url has been created", request.ToJson()), request.Transaction.ClientId); var info = OtherPaymentInfo.Create( firstName: request.Details.FirstName, lastName: request.Details.LastName, city: string.Empty, zip: string.Empty, address: string.Empty, country: request.Details.CountryIso3, email: request.Details.Email, contactPhone: request.Details.Phone, dateOfBirth: string.Empty) .ToJson(); var pt = PaymentTransaction.Create( request.Transaction.TransactionId, CashInPaymentSystem.Link4Pay, request.Transaction.ClientId, request.Transaction.Amount, feeAmount, request.Transaction.AssetId, null, request.Transaction.AssetId, info ); await Task.WhenAll( _paymentTransactionsRepository.CreateAsync(pt), _paymentTransactionEventsLog.WriteAsync(PaymentTransactionLogEvent.Create(request.Transaction.TransactionId, "", "Registered", request.Transaction.ClientId)), _paymentTransactionEventsLog.WriteAsync(PaymentTransactionLogEvent.Create(request.Transaction.TransactionId, url, "Payment Url has created", request.Transaction.ClientId)) ); return(new PaymentUrlResponse { PaymentUrl = url, OkUrl = $"{(string.IsNullOrEmpty(request.Urls?.OkUrl?.Trim()) ? _successUrl : request.Urls?.OkUrl)}?v=1", FailUrl = string.IsNullOrEmpty(request.Urls?.FailUrl?.Trim()) ? _failUrl : request.Urls?.FailUrl, CancelUrl = string.IsNullOrEmpty(request.Urls?.CancelUrl?.Trim()) ? _cancelUrl : request.Urls?.CancelUrl }); } catch (Exception ex) { _log.Error(ex); return(new PaymentUrlResponse { Error = new ErrorDetails { ErrorType = ErrorDetails.Types.ErrorType.Unknown, Message = "Error getting the payment url" } }); } }
/// <summary> /// 初始化 /// 绑定时使用 /// </summary> public TestApiPayForm(PaymentTransaction transaction) { Transaction = transaction; }
public ITransactionRefundResult RefundPayment(PaymentTransaction transaction) { throw new System.NotImplementedException(); }
private void InsertTransaction(Int64 userid, string transactionnumber, string amount, int tokencredit, int tokenId) { TokenModel token = GetTokenById(tokenId); DateTime tokenExpiresOn = DateTime.UtcNow.AddDays(token.ExpireDurationInDays); using (var db = new UnseentalentdbDataContext()) { var objpayment = new PaymentTransaction(); objpayment.Amount = Convert.ToDouble(amount); objpayment.IsActive = true; objpayment.IsDeleted = false; objpayment.TokenId = tokenId; objpayment.TransactionDate = DateTime.UtcNow; objpayment.TransactionNumber = transactionnumber; objpayment.UserId = userid; db.PaymentTransactions.InsertOnSubmit(objpayment); db.SubmitChanges(); var objtoken = new Managetoken(); objtoken.CreateDate = DateTime.UtcNow; objtoken.IsActive = true; objtoken.TokenId = tokenId; objtoken.UserId = userid; objtoken.UniqueTokenId = "UST-" + CommonHelpers.GetUniqueKey(10); objtoken.WillExpireOn = tokenExpiresOn; objtoken.RemainingUploadCount = token.NoOfUploadsAllowed; db.Managetokens.InsertOnSubmit(objtoken); db.SubmitChanges(); } }
/// <summary> /// 调用发货接口 /// </summary> public void DeliveryGoods( PaymentTransaction transaction, string logisticsName, string invoiceNo) { throw new NotImplementedException(); }