public void OnPost() { string nonce = Request.Form["nonce"]; PaymentsApi paymentsApi = new PaymentsApi(configuration: this.configuration); // Every payment you process with the SDK must have a unique idempotency key. // If you're unsure whether a particular payment succeeded, you can reattempt // it with the same idempotency key without worrying about double charging // the buyer. string uuid = NewIdempotencyKey(); // Monetary amounts are specified in the smallest unit of the applicable currency. // This amount is in cents. It's also hard-coded for $1.00, // which isn't very useful. Money amount = new Money(100, "USD"); // To learn more about splitting payments with additional recipients, // see the Payments API documentation on our [developer site] // (https://developer.squareup.com/docs/payments-api/overview). CreatePaymentRequest createPaymentRequest = new CreatePaymentRequest(AmountMoney: amount, IdempotencyKey: uuid, SourceId: nonce); try { var response = paymentsApi.CreatePayment(createPaymentRequest); this.ResultMessage = "Payment complete! " + response.ToJson(); } catch (ApiException e) { this.ResultMessage = e.Message; } }
public PaymentStatusResponse checkStatus(PaymentRequest request) { PaymentStatusResponse result = new PaymentStatusResponse(); // POST https://connect.squareup.com/v2/locations/{location_id}/orders/batch-retrieve // Body string[] order_ids // order_id this line to be remove // request.ReferenceId = "oNtObOW0XqUxAKEU9a6xCC6VxvbZY"; if (string.IsNullOrEmpty(request.ReferenceId)) { return(result); } var orderRequest = new CheckOrderRequest { OrderIDs = new List <string>() }; orderRequest.OrderIDs.Add(request.ReferenceId); var httpResult = PaymentsApi.CheckOrder(orderRequest, Setting); var deserializeResult = JsonConvert.DeserializeObject <CheckOrderResponse>(httpResult); if (deserializeResult == null) { return(result); } result = GetPaidStatus(result, deserializeResult.Orders[0].State); return(result); }
public SimplifyPaymentProcessor( SimplifyPaymentSettings simplifyPaymentSettings, ISettingService settingService, IPaymentService paymentService, IStoreContext storeContext, ICurrencyService currencyService, CurrencySettings currencySettings, IOrderService orderService, ILocalizationService localizationService, IEncryptionService encryptionService, ILogger logger ) { this._simplifyPaymentSettings = simplifyPaymentSettings; this._settingService = settingService; this._paymentService = paymentService; this._storeContext = storeContext; this._currencyService = currencyService; this._currencySettings = currencySettings; this._orderService = orderService; this._localizationService = localizationService; this._encryptionService = encryptionService; this._logger = logger; this._paymentsApi = new PaymentsApi(); }
public void GetAllPaymentsTest() { string authorization = "Basic asdadsa"; mockRestClient.Expects.One.Method(v => v.Execute(new RestRequest())).With(NMock.Is.TypeOf(typeof(RestRequest))).WillReturn(getPaymentResponse); ApiClient apiClient = new ApiClient(mockRestClient.MockObject); apiClient.Configuration = null; Configuration configuration = new Configuration { ApiClient = apiClient, Username = "******", Password = "******", AccessToken = null, ApiKey = null, ApiKeyPrefix = null, TempFolderPath = null, DateTimeFormat = null, Timeout = 60000, UserAgent = "asdasd" }; instance = new PaymentsApi(configuration); var response = instance.GetAllPayments(authorization); Assert.IsInstanceOf <PaymentCollection>(response, "response is PaymentCollection"); }
public async Task GetAsync_requests_proper_uri(PaymentQueryState state, int page, string expectedPath) { // arrange var expectedRequest = new PaymentPageQuery { State = state, Page = page, }; var expectedResult = new IamportResponse <PagedResult <Payment> > { HttpStatusCode = HttpStatusCode.OK, }; var client = GetMockClient(expectedResult); var sut = new PaymentsApi(client); // act var result = await sut.GetAsync(expectedRequest); // assert Mock.Get(client) .Verify(mocked => mocked.RequestAsync <object, PagedResult <Payment> >( It.Is <IamportRequest>(req => req.ApiPathAndQueryString.EndsWith(expectedPath)))); }
public static void RetrieveSingleGiftAidPayment(int giftAidPaymentId, FileInfo excelFile) { var client = CreateClient(); var paymentClient = new PaymentsApi(client.HttpChannel); if (excelFile == null) { var paymentReport = paymentClient.RetrieveReport <GiftAidPayment>(giftAidPaymentId); foreach (var item in paymentReport.Donations) { Console.WriteLine("£{0} Gift Aid on {1:dd/MM/yyyy} from a donation of {2}", item.NetGiftAidAmount, item.Date, item.Amount); } } else { var excelData = paymentClient.RetrieveReport(giftAidPaymentId, DataFileFormat.excel); using (var fs = new FileStream(excelFile.FullName, FileMode.Create)) { fs.Write(excelData, 0, excelData.Length); fs.Close(); } Console.WriteLine("Saved!"); } }
public static void RetrieveSingleDonationPayment(int paymentId, FileInfo excelFile) { var client = CreateClient(); var paymentsClient = new PaymentsApi(client.HttpChannel); if (excelFile == null) { var paymentReport = paymentsClient.RetrieveReport <DonatoionPayment>(paymentId); foreach (var item in paymentReport.Donations) { Console.WriteLine("£{0} on {1:dd/MM/yyyy} from donor {2} {3} who said: '{4}'", item.Amount, item.Date, item.Donor.FirstName, item.Donor.LastName, item.MessageFromDonor); } } else { var excelData = paymentsClient.RetrieveReport(paymentId, DataFileFormat.excel); using (var fs = new FileStream(excelFile.FullName, FileMode.Create)) { fs.Write(excelData, 0, excelData.Length); fs.Close(); } Console.WriteLine("Saved!"); } }
public static void RetrieveSingleDonationPayment(int paymentId, FileInfo excelFile) { var client = CreateClient(); var paymentsClient = new PaymentsApi(client.HttpChannel); if (excelFile == null) { var paymentReport = paymentsClient.RetrieveReport<DonatoionPayment>(paymentId); foreach (var item in paymentReport.Donations) { Console.WriteLine("£{0} on {1:dd/MM/yyyy} from donor {2} {3} who said: '{4}'", item.Amount, item.Date, item.Donor.FirstName, item.Donor.LastName, item.MessageFromDonor); } } else { var excelData = paymentsClient.RetrieveReport(paymentId, DataFileFormat.excel); using (var fs = new FileStream(excelFile.FullName, FileMode.Create)) { fs.Write(excelData, 0, excelData.Length); fs.Close(); } Console.WriteLine("Saved!"); } }
public async Task CancelAsync_requests_proper_uri() { // arrange var expectedRequest = new PaymentCancellation { IamportId = Guid.NewGuid().ToString(), }; var expectedResult = new IamportResponse <Payment> { HttpStatusCode = HttpStatusCode.OK, Content = new Payment { IamportId = expectedRequest.IamportId, } }; var client = GetMockClient(expectedRequest, expectedResult); var sut = new PaymentsApi(client); // act var result = await sut.CancelAsync(expectedRequest); // assert Mock.Get(client) .Verify(mocked => mocked.RequestAsync <PaymentCancellation, Payment>( It.Is <IamportRequest <PaymentCancellation> >(req => req.ApiPathAndQueryString.EndsWith("payments/cancel")))); }
public void RegisterProfile() { var paymentData = new { CardNumber = "4111111111111111", ExpiryMonth = 12, ExpiryYear = DateTime.Today.Year }; string token; var mockWebClient = TokenandWebClientSetup(out token); mockWebClient.Setup( x => x.UploadString(new Uri(BaseUri, @"patients/payments"), "POST", "{\"CardNumber\":\"4111111111111111\",\"ExpiryMonth\":12,\"ExpiryYear\":2015}")).Returns( @"{" + "\"$id\": \"1\"," + "\"success\": true," + "\"data\": {" + "\"$id\": \"2\"," + "\"profileId\": \"31867556\"," + "\"paymentProfileId\": \"32565287\"" + "}," + "\"message\": \"Success\"" + "}" ); var target = new PaymentsApi(Settings.Default.BaseUrl, token, 1, Settings.Default.ApiDeveloperId, Settings.Default.ApiKey, mockWebClient.Object); var result = target.RegisterProfile(paymentData); Assert.Greater((int)result["data"]["profileId"], 1); }
public IPaymentResponse GetHtmlDetail(RenderContext context) { if (this.Setting == null) { return(null); } // todo 需要转换为货币的最低单位 // square APi 货币的最小面额指定。例如,美元金额以美分指定,https://developer.squareup.com/docs/build-basics/working-with-monetary-amounts var amount = new Money { Amount = SquareCommon.GetSquareAmount(decimal.Parse(context.Request.Get("totalAmount"))), Currency = context.Request.Get("currency") }; var squareResponseNonce = context.Request.Get("nonce"); var result = PaymentsApi.CreatPayment(squareResponseNonce, amount, Setting); var deserializeResult = JsonConvert.DeserializeObject <PaymentResponse>(result); if (deserializeResult.Payment.Status == "APPROVED" || deserializeResult.Payment.Status == "COMPLETED") { var res = new PaidResponse(); res.paymemtMethodReferenceId = deserializeResult.Payment.ID; return(res); } else if (deserializeResult.Payment.Status == "CANCELED" || deserializeResult.Payment.Status == "FAILED") { return(new FailedResponse("FAILED")); } else { // TODO: please check. return(new FailedResponse("No response")); } }
public static void RetrieveSingleGiftAidPayment(int giftAidPaymentId, FileInfo excelFile) { var client = CreateClient(); var paymentClient = new PaymentsApi(client.HttpChannel); if (excelFile == null) { var paymentReport = paymentClient.RetrieveReport<GiftAidPayment>(giftAidPaymentId); foreach (var item in paymentReport.Donations) { Console.WriteLine("£{0} Gift Aid on {1:dd/MM/yyyy} from a donation of {2}", item.NetGiftAidAmount, item.Date, item.Amount); } } else { var excelData = paymentClient.RetrieveReport(giftAidPaymentId, DataFileFormat.excel); using (var fs = new FileStream(excelFile.FullName, FileMode.Create)) { fs.Write(excelData, 0, excelData.Length); fs.Close(); } Console.WriteLine("Saved!"); } }
public static void RetrievePaymentList(DateTime startDate, DateTime endDate, FileInfo excelFile) { var client = CreateClient(); var paymentclient = new PaymentsApi(client.HttpChannel); if (excelFile == null) { var list = paymentclient.RetrievePaymentsBetween(startDate, endDate); if (!list.Any()) Console.WriteLine("No payments found for the dates entered"); foreach (var item in list) { Console.WriteLine("#{0} £{1} ({2}) paid to account {3} on {4:dd/MM/yyyy}", item.PaymentRef, item.Net, item.PaymentType, item.Account, item.PaymentDate); Console.WriteLine("Full report: {0}", item.Url); Console.WriteLine(); } } else { var excelData = paymentclient.RetrievePaymentsBetween(startDate, endDate, DataFileFormat.excel); using (var fs = new FileStream(excelFile.FullName, FileMode.Create)) { fs.Write(excelData, 0, excelData.Length); fs.Close(); } Console.WriteLine("Saved!"); } }
public PaymentStatusResponse checkStatus(PaymentRequest request) { PaymentStatusResponse result = new PaymentStatusResponse(); // POST https://connect.squareup.com/v2/locations/{location_id}/orders/batch-retrieve if (string.IsNullOrEmpty(request.ReferenceId)) { return(result); } var orderRequest = new CheckOrderRequest { OrderIDs = new List <string>() }; orderRequest.OrderIDs.Add(request.ReferenceId); var deserializeResult = PaymentsApi.CheckOrder(orderRequest, Setting); if (deserializeResult == null) { return(result); } result = GetPaidStatus(result, deserializeResult.Orders[0].State); return(result); }
public void GetPaymentListAndDownloadSeveralPayments() { var clientConfiguration = GetDefaultDataClientConfiguration() .With((clientConfig) => clientConfig.WireDataFormat = WireDataFormat.Json) .With((clientConfig) => clientConfig.IsZipSupportedByClient = true); var client = new JustGivingDataClient(clientConfiguration); var paymentClient = new PaymentsApi(client.HttpChannel); int count = 0; const int numberToDownload = 10; var payments = paymentClient.RetrievePaymentsBetween(new DateTime(2012, 06, 01), new DateTime(2012, 06, 30)); foreach (var payment in payments) { if (count >= numberToDownload) { break; } var report = client.Payment.RetrieveReport <Payment>(payment.PaymentRef); Assert.That(report, Is.Not.Null); count++; } }
public static void RetrievePaymentList(DateTime startDate, DateTime endDate, FileInfo excelFile) { var client = CreateClient(); var paymentclient = new PaymentsApi(client.HttpChannel); if (excelFile == null) { var list = paymentclient.RetrievePaymentsBetween(startDate, endDate); if (!list.Any()) { Console.WriteLine("No payments found for the dates entered"); } foreach (var item in list) { Console.WriteLine("#{0} £{1} ({2}) paid to account {3} on {4:dd/MM/yyyy}", item.PaymentRef, item.Net, item.PaymentType, item.Account, item.PaymentDate); Console.WriteLine("Full report: {0}", item.Url); Console.WriteLine(); } } else { var excelData = paymentclient.RetrievePaymentsBetween(startDate, endDate, DataFileFormat.excel); using (var fs = new FileStream(excelFile.FullName, FileMode.Create)) { fs.Write(excelData, 0, excelData.Length); fs.Close(); } Console.WriteLine("Saved!"); } }
public async Task PreparationAsync_requests_proper_uri() { // arrange var expectedRequest = new PaymentPreparation { Amount = 1000, TransactionId = Guid.NewGuid().ToString(), }; var expectedResult = new IamportResponse <PaymentPreparation> { HttpStatusCode = HttpStatusCode.OK, Content = new PaymentPreparation { TransactionId = expectedRequest.TransactionId, Amount = expectedRequest.Amount, } }; var expectedPath = $"payments/prepare"; var client = GetMockClient(expectedRequest, expectedResult); var sut = new PaymentsApi(client); // act var result = await sut.PrepareAsync(expectedRequest); // assert Mock.Get(client) .Verify(mocked => mocked.RequestAsync <PaymentPreparation, PaymentPreparation>( It.Is <IamportRequest <PaymentPreparation> >(req => req.ApiPathAndQueryString.EndsWith(expectedPath)))); }
public static PtsV2PaymentsPost201Response Run() { string clientReferenceInformationCode = "123456"; Ptsv2paymentsClientReferenceInformation clientReferenceInformation = new Ptsv2paymentsClientReferenceInformation( Code: clientReferenceInformationCode ); bool processingInformationCapture = true; string processingInformationCommerceIndicator = "retail"; Ptsv2paymentsProcessingInformation processingInformation = new Ptsv2paymentsProcessingInformation( Capture: processingInformationCapture, CommerceIndicator: processingInformationCommerceIndicator ); string orderInformationAmountDetailsTotalAmount = "100.00"; string orderInformationAmountDetailsCurrency = "USD"; Ptsv2paymentsOrderInformationAmountDetails orderInformationAmountDetails = new Ptsv2paymentsOrderInformationAmountDetails( TotalAmount: orderInformationAmountDetailsTotalAmount, Currency: orderInformationAmountDetailsCurrency ); Ptsv2paymentsOrderInformation orderInformation = new Ptsv2paymentsOrderInformation( AmountDetails: orderInformationAmountDetails ); string pointOfSaleInformationEntryMode = "swiped"; int pointOfSaleInformationTerminalCapability = 2; string pointOfSaleInformationTrackData = "%B38000000000006^TEST/CYBS ^2012121019761100 00868000000?;38000000000006=20121210197611868000?"; Ptsv2paymentsPointOfSaleInformation pointOfSaleInformation = new Ptsv2paymentsPointOfSaleInformation( EntryMode: pointOfSaleInformationEntryMode, TerminalCapability: pointOfSaleInformationTerminalCapability, TrackData: pointOfSaleInformationTrackData ); var requestObj = new CreatePaymentRequest( ClientReferenceInformation: clientReferenceInformation, ProcessingInformation: processingInformation, OrderInformation: orderInformation, PointOfSaleInformation: pointOfSaleInformation ); try { var configDictionary = new Configuration().GetConfiguration(); var clientConfig = new CyberSource.Client.Configuration(merchConfigDictObj: configDictionary); var apiInstance = new PaymentsApi(clientConfig); PtsV2PaymentsPost201Response result = apiInstance.CreatePayment(requestObj); Console.WriteLine(result); return(result); } catch (Exception e) { Console.WriteLine("Exception on calling the API : " + e.Message); return(null); } }
public void ErrorIfAuthenticationFails() { _dataClientConfiguration = GetDefaultDataClientConfiguration().With((clientConfig) => clientConfig.Password = "******"); _client = new JustGivingDataClient(_dataClientConfiguration); var paymentClient = new PaymentsApi(_client.HttpChannel); var response = paymentClient.NoOp(); Assert.That(response, Is.EqualTo(HttpStatusCode.Unauthorized)); }
public void CanDoNoOp() { _dataClientConfiguration = GetDefaultDataClientConfiguration(); _client = new JustGivingDataClient(_dataClientConfiguration); var paymentClient = new PaymentsApi(_client.HttpChannel); var response = paymentClient.NoOp(); Assert.That(response, Is.EqualTo(HttpStatusCode.OK)); }
public void main() { // Configure API key authorization, get an Access Token, Create an Order, Get an Order try { authorizationApi = new AuthorizationApi("https://api-sandbox.afterpay.com/v2/"); authorizationApi.Configuration.MerchantId = "MerchantId"; authorizationApi.Configuration.MerchantSecretKey = "MerchantSecretKey"; authorizationApi.Configuration.UserAgent = "Afterpay SDK; .netCore3.1; Git Example"; // Create Acces Token var authentication = authorizationApi.AuthorizationCreateToken(); checkoutsApi = new CheckoutsApi(authorizationApi.Configuration); paymentsApi = new PaymentsApi(authorizationApi.Configuration); Debug.WriteLine(authentication); } catch (Exception e) { Debug.Print("Exception when calling AuthorizationApi: " + e.Message); } try { // Create Checkout var createCheckoutRequest = CreateCheckoutRequest(); var response = checkoutsApi.CheckoutsCreate(createCheckoutRequest); var checkout = checkoutsApi.CheckoutsGet(response.Token); string orderToken = null; var authorization = authorizationApi.AuthorizationCreateToken(); orderToken = "OrderToken"; var auth = new Auth("1", orderToken, "Auth for Order"); var authResponse = paymentsApi.PaymentAuth(auth); var amount = new Money("0.00", "NZD"); var capture = new Capture("1", "1", amount, "Capture for Order"); // Request Id needs to increas for each partial refund var id = "OrderId"; var captureResponse = paymentsApi.PaymentCapture(id, capture); } catch (Exception e) { Debug.Print("Exception when calling OrdersApi: " + e.Message); } }
public static PtsV2PaymentsPost201Response Run() { string clientReferenceInformationCode = "TC50171_3"; Ptsv2paymentsClientReferenceInformation clientReferenceInformation = new Ptsv2paymentsClientReferenceInformation( Code: clientReferenceInformationCode ); string paymentInformationInstrumentIdentifierId = "7010000000016241111"; Ptsv2paymentsPaymentInformationInstrumentIdentifier paymentInformationInstrumentIdentifier = new Ptsv2paymentsPaymentInformationInstrumentIdentifier( Id: paymentInformationInstrumentIdentifierId ); Ptsv2paymentsPaymentInformation paymentInformation = new Ptsv2paymentsPaymentInformation( InstrumentIdentifier: paymentInformationInstrumentIdentifier ); string orderInformationAmountDetailsTotalAmount = "102.21"; string orderInformationAmountDetailsCurrency = "USD"; Ptsv2paymentsOrderInformationAmountDetails orderInformationAmountDetails = new Ptsv2paymentsOrderInformationAmountDetails( TotalAmount: orderInformationAmountDetailsTotalAmount, Currency: orderInformationAmountDetailsCurrency ); Ptsv2paymentsOrderInformation orderInformation = new Ptsv2paymentsOrderInformation( AmountDetails: orderInformationAmountDetails ); string tokenInformationNetworkTokenOption = "ignore"; Ptsv2paymentsTokenInformation tokenInformation = new Ptsv2paymentsTokenInformation( NetworkTokenOption: tokenInformationNetworkTokenOption ); var requestObj = new CreatePaymentRequest( ClientReferenceInformation: clientReferenceInformation, PaymentInformation: paymentInformation, OrderInformation: orderInformation, TokenInformation: tokenInformation ); try { var configDictionary = new Configuration().GetConfiguration(); var clientConfig = new CyberSource.Client.Configuration(merchConfigDictObj: configDictionary); var apiInstance = new PaymentsApi(clientConfig); PtsV2PaymentsPost201Response result = apiInstance.CreatePayment(requestObj); Console.WriteLine(result); return(result); } catch (Exception e) { Console.WriteLine("Exception on calling the API : " + e.Message); return(null); } }
public void Init() { authorizationApi = new AuthorizationApi("https://api-sandbox.afterpay.com/v2/"); authorizationApi.Configuration.MerchantId = "MerchantId"; authorizationApi.Configuration.MerchantSecretKey = "MerchantSecretKey"; authorizationApi.Configuration.UserAgent = "Afterpay SDK; .netCore3.1; Test Payments Api"; var response = authorizationApi.AuthorizationCreateToken(); instance = new PaymentsApi(authorizationApi.Configuration); }
public void AuthenticationSuccess_DoesNotReturnHttp401Unauthorised() { var clientConfiguration = GetDefaultDataClientConfiguration() .With((clientConfig) => clientConfig.IsZipSupportedByClient = true); var client = new JustGivingDataClient(clientConfiguration); var paymentClient = new PaymentsApi(client.HttpChannel); var payment = paymentClient.RetrieveReport <Payment>(_paymentId); Assert.That(payment.HttpStatusCode, Is.Not.EqualTo(HttpStatusCode.Unauthorized)); }
public void AuthenticationSuccess_DoesNotReturnHttp401Unauthorised() { var clientConfiguration = GetDefaultDataClientConfiguration() .With((clientConfig) => clientConfig.IsZipSupportedByClient = true); var client = new JustGivingDataClient(clientConfiguration); var paymentClient = new PaymentsApi(client.HttpChannel); var payment = paymentClient.RetrieveReport<Payment>(_paymentId); Assert.That(payment.HttpStatusCode, Is.Not.EqualTo(HttpStatusCode.Unauthorized)); }
public void AuthenticationFailure_ReturnsHttp401Unauthorised() { var clientConfiguration = GetDefaultDataClientConfiguration() .With((clientConfig) => clientConfig.Username = "") .With((clientConfig) => clientConfig.Password = ""); var client = new JustGivingDataClient(clientConfiguration); var paymentClient = new PaymentsApi(client.HttpChannel); var exception = Assert.Throws <ErrorResponseException>(() => paymentClient.RetrieveReport <Payment>(_paymentId)); Assert.That(exception.Message.Contains("401")); }
public void AuthenticationFailure_ReturnsHttp401Unauthorised() { var clientConfiguration = GetDefaultDataClientConfiguration() .With((clientConfig) => clientConfig.Username = "") .With((clientConfig) => clientConfig.Password = ""); var client = new JustGivingDataClient(clientConfiguration); var paymentClient = new PaymentsApi(client.HttpChannel); var exception = Assert.Throws<ErrorResponseException>(() => paymentClient.RetrieveReport<Payment>(_paymentId)); Assert.That(exception.Message.Contains("401")); }
protected virtual void Dispose(bool disposing) { if (_isDisposed) { return; } if (disposing) { LearnerMatchApi?.Reset(); PaymentsApi?.Reset(); } _isDisposed = true; }
public async Task CancelAsync_throws_ValidationException(string iamportId, string transactionId) { // arrange var expectedRequest = new PaymentCancellation { IamportId = iamportId, TransactionId = transactionId, }; var expectedResult = new IamportResponse <Payment>(); var client = GetMockClient(expectedRequest, expectedResult); var sut = new PaymentsApi(client); // act/assert await Assert.ThrowsAsync <ValidationException>( () => sut.CancelAsync(expectedRequest)); }
public IPaymentResponse Charge(PaymentRequest request) { if (this.Setting == null) { return(null); } CreateCheckoutRequest checkoutRequest = GetCheckoutRequest(request); var deserializeResult = PaymentsApi.CheckoutCreatOrder(checkoutRequest, Setting); // 把OrderID赋值到request referenceID 为了后面 checkStatus 使用 request.ReferenceId = deserializeResult.Checkout.Order.ID; PaymentManager.UpdateRequest(request, Context); return(new RedirectResponse(deserializeResult.Checkout.CheckoutPageURL, Guid.Empty)); }
public IPaymentResponse Charge(PaymentRequest request) { if (this.Setting == null) { return(null); } // todo 需要转换为货币的最低单位 CreateCheckoutRequest checkoutRequest = GetCheckoutRequest(request); var result = PaymentsApi.CheckoutCreatOrder(checkoutRequest, Setting); var deserializeResult = JsonConvert.DeserializeObject <CreateCheckoutResponse>(result); return(new RedirectResponse(deserializeResult.Checkout.CheckoutPageURL, Guid.Empty)); }
public async Task GetPreparationAsync_throws_IamportResponseException_when_response_code_is_not_success() { // arrange var expectedRequest = Guid.NewGuid().ToString(); var expectedResult = new IamportResponse <PaymentPreparation> { Code = -1, HttpStatusCode = HttpStatusCode.InternalServerError, }; var client = GetMockClient(expectedResult); var sut = new PaymentsApi(client); // act/assert await Assert.ThrowsAsync <IamportResponseException>( () => sut.GetPreparationAsync(expectedRequest)); }
public async Task PreparationAsync_throws_ValidationException(decimal amount, string transactionId) { // arrange var expectedRequest = new PaymentPreparation { Amount = amount, TransactionId = transactionId, }; var expectedResult = new IamportResponse <PaymentPreparation>(); var client = GetMockClient(expectedRequest, expectedResult); var sut = new PaymentsApi(client); // act/assert await Assert.ThrowsAsync <ValidationException>( () => sut.PrepareAsync(expectedRequest)); }
public static TransactionResult ProcessCapture(TransactionRequest captureRequest, SquareSettings squareSettings, ILogger logger) { var order = captureRequest.Order; var config = GetConfiguration(squareSettings); var paymentId = captureRequest.GetParameterAs <string>("paymentId"); var paymentsApi = new PaymentsApi(config); //perform the call var paymentResponse = paymentsApi.CompletePayment(paymentId); var transactionResult = new TransactionResult() { OrderGuid = order.Guid, TransactionGuid = Guid.NewGuid().ToString(), }; if (paymentResponse != null) { var payment = paymentResponse.Payment; transactionResult.Success = true; transactionResult.TransactionAmount = (decimal)(payment.AmountMoney.Amount ?? 0) / 100; transactionResult.ResponseParameters = new Dictionary <string, object>() { { "PaymentId", payment.Id }, { "ReferenceId", payment.ReferenceId } }; if (payment.Status == "COMPLETED") { transactionResult.NewStatus = PaymentStatus.Complete; } else { transactionResult.NewStatus = PaymentStatus.Failed; var errors = string.Join(",", paymentResponse.Errors); logger.Log <TransactionResult>(LogLevel.Warning, "The capture for Order#" + order.Id + " by square failed." + errors); transactionResult.Exception = new Exception("An error occurred while capturing payment. Error Details: " + errors); transactionResult.Success = false; } } else { logger.Log <TransactionResult>(LogLevel.Warning, "The capture for Order#" + order.Id + " by square failed. No response received."); transactionResult.Success = false; transactionResult.Exception = new Exception("An error occurred while capturing payment"); } return(transactionResult); }
public IPaymentResponse CreatPayment(RenderContext context) { if (this.Setting == null) { return(null); } // square 货币的最小面额指定。https://developer.squareup.com/docs/build-basics/working-with-monetary-amounts var currency = context.Request.Get("currency"); var totalAmount = decimal.Parse(context.Request.Get("totalAmount")); var requestIdStr = context.Request.Get("paymentRequestId"); var amount = new Money { Amount = CurrencyDecimalPlaceConverter.ToMinorUnit(currency, totalAmount), Currency = currency }; var deserializeResult = PaymentsApi.CreatPayment(context.Request.Get("nonce"), amount, Setting, requestIdStr); // 把paymentID赋值到request referenceID 为了后面 checkStatus 使用 var paymentRequestIdStr = context.Request.Get("paymentRequestId"); Guid paymentRequestId; if (Guid.TryParse(paymentRequestIdStr, out paymentRequestId)) { var request = PaymentManager.GetRequest(paymentRequestId, context); request.ReferenceId = deserializeResult.Payment.ID; PaymentManager.UpdateRequest(request, context); } if (deserializeResult.Payment.Status == "APPROVED" || deserializeResult.Payment.Status == "COMPLETED") { var res = new PaidResponse(); res.paymemtMethodReferenceId = deserializeResult.Payment.ID; return(res); } else if (deserializeResult.Payment.Status == "CANCELED" || deserializeResult.Payment.Status == "FAILED") { return(new FailedResponse("FAILED")); } else { // TODO: please check. return(new FailedResponse("No response")); } }
public void GetCustomer() { string token; var mockWebClient = TokenandWebClientSetup(out token); //var mockWebClient = TokenandWebClientSetupRemoteCall(out token); mockWebClient.Setup(x => x.DownloadString(new Uri(BaseUri, "patients/15/payments"))) .Returns("{\"PaymentProfile\":[{\"CardNumber\":\"4111111111111111\", \"ExpiryMonth\":\"12\", \"ExpiryYear\":\"2015\" }]}"); var target = new PaymentsApi(Settings.Default.BaseUrl, token, 1, Settings.Default.ApiDeveloperId, Settings.Default.ApiKey, mockWebClient.Object); var actual = target.GetCustomerProfile(15); Assert.False(target.NotFound); Assert.False(target.ServerError); Assert.NotNull(actual); //Assert.AreEqual(actual.PaymentProfiles[0].CardNumber.Value, "XXXX1111"); }
public void GetPaymentListAndDownloadSeveralPayments() { var clientConfiguration = GetDefaultDataClientConfiguration() .With((clientConfig) => clientConfig.WireDataFormat = WireDataFormat.Json) .With((clientConfig) => clientConfig.IsZipSupportedByClient = true); var client = new JustGivingDataClient(clientConfiguration); var paymentClient = new PaymentsApi(client.HttpChannel); int count = 0; const int numberToDownload = 10; var payments = paymentClient.RetrievePaymentsBetween(new DateTime(2012, 06, 01), new DateTime(2012, 06, 30)); foreach(var payment in payments) { if (count >= numberToDownload) break; var report = client.Payment.RetrieveReport<Payment>(payment.PaymentRef); Assert.That(report, Is.Not.Null); count++; } }
protected void CreatePaymentsClient(JustGivingDataClient client) { PaymentsClient = new PaymentsApi(client.HttpChannel); }