public void CanConvertToJsonMinimalWithAllCheckoutSessionScopes()
        {
            CheckoutSessionScope[] scopes = new CheckoutSessionScope[] {
                CheckoutSessionScope.Name,
                CheckoutSessionScope.Email,
                CheckoutSessionScope.PostalCode,
                CheckoutSessionScope.ShippingAddress,
                CheckoutSessionScope.PhoneNumber,
                CheckoutSessionScope.PrimeStatus,
                CheckoutSessionScope.BillingAddress
            };

            // arrange
            var request = new CreateCheckoutSessionRequest
                          (
                checkoutReviewReturnUrl: "https://example.com/review.html",
                storeId: "amzn1.application-oa2-client.000000000000000000000000000000000",
                scopes
                          );

            // act
            string json  = request.ToJson();
            string json2 = request.ToJson();

            // assert
            Assert.AreEqual(json, json2);
            Assert.AreEqual("{\"storeId\":\"amzn1.application-oa2-client.000000000000000000000000000000000\",\"scopes\":[\"name\",\"email\",\"postalCode\",\"shippingAddress\",\"phoneNumber\",\"primeStatus\",\"billingAddress\"],\"webCheckoutDetails\":{\"checkoutReviewReturnUrl\":\"https://example.com/review.html\"}}", json);
        }
        public void AdditionalPaymentButton()
        {
            // arrange
            var request = new CreateCheckoutSessionRequest
                          (
                checkoutReviewReturnUrl: "https://example.com/review.html",
                storeId: "amzn1.application-oa2-client.000000000000000000000000000000000"
                          );

            request.WebCheckoutDetails.CheckoutMode          = CheckoutMode.ProcessOrder;
            request.AddressDetails.Name                      = "Paul Smith";
            request.AddressDetails.AddressLine1              = "9999 First Avenue";
            request.AddressDetails.City                      = "New York";
            request.AddressDetails.StateOrRegion             = "NY";
            request.AddressDetails.PostalCode                = "10016";
            request.AddressDetails.CountryCode               = "US";
            request.AddressDetails.PhoneNumber               = "212555555";
            request.AddressDetails.DistrictOrCounty          = "Manhattan";
            request.PaymentDetails.PaymentIntent             = PaymentIntent.AuthorizeWithCapture;
            request.PaymentDetails.ChargeAmount.Amount       = 10;
            request.PaymentDetails.ChargeAmount.CurrencyCode = Currency.USD;
            request.PaymentDetails.PresentmentCurrency       = Currency.USD;
            request.MerchantMetadata.MerchantReferenceId     = "Merchant Ref ID";
            request.MerchantMetadata.MerchantStoreName       = "Store Name";
            request.MerchantMetadata.NoteToBuyer             = "Buyer Note";

            // act
            string json  = request.ToJson();
            string json2 = request.ToJson();

            // assert
            Assert.AreEqual(json, json2);
            Assert.AreEqual("{\"storeId\":\"amzn1.application-oa2-client.000000000000000000000000000000000\",\"addressDetails\":{\"districtOrCounty\":\"Manhattan\",\"name\":\"Paul Smith\",\"addressLine1\":\"9999 First Avenue\",\"city\":\"New York\",\"stateOrRegion\":\"NY\",\"postalCode\":\"10016\",\"countryCode\":\"US\",\"phoneNumber\":\"212555555\"},\"webCheckoutDetails\":{\"checkoutReviewReturnUrl\":\"https://example.com/review.html\",\"checkoutMode\":\"ProcessOrder\"},\"paymentDetails\":{\"paymentIntent\":\"AuthorizeWithCapture\",\"chargeAmount\":{\"amount\":10,\"currencyCode\":\"USD\"},\"presentmentCurrency\":\"USD\"},\"merchantMetadata\":{\"merchantReferenceId\":\"Merchant Ref ID\",\"merchantStoreName\":\"Store Name\",\"noteToBuyer\":\"Buyer Note\"}}", json);
        }
        public void CanConvertParameterlessCtorToJsonMinimal()
        {
            // arrange
            var request = new CreateCheckoutSessionRequest();

            // act
            string json  = request.ToJson();
            string json2 = request.ToJson();

            // assert
            Assert.AreEqual(json, json2);

            // verify request object still allows all setters after being serialized
            request.MerchantMetadata.CustomInformation   = metadataToTest.CustomInformation;
            request.MerchantMetadata.MerchantReferenceId = metadataToTest.MerchantReferenceId;
            request.MerchantMetadata.MerchantStoreName   = metadataToTest.MerchantStoreName;
            request.MerchantMetadata.NoteToBuyer         = metadataToTest.NoteToBuyer;
            request.ChargePermissionType                            = ChargePermissionType.Recurring;
            request.RecurringMetadata.Frequency.Unit                = FrequencyUnit.Variable;
            request.RecurringMetadata.Frequency.Value               = 2;
            request.RecurringMetadata.Amount.Amount                 = 12.34m;
            request.RecurringMetadata.Amount.CurrencyCode           = Currency.USD;
            request.DeliverySpecifications.AddressRestrictions.Type = RestrictionType.Allowed;
            request.DeliverySpecifications.AddressRestrictions.AddCountryRestriction("US")
            .AddZipCodesRestriction("12345");
            request.DeliverySpecifications.SpecialRestrictions.Add(SpecialRestriction.RestrictPackstations);
            request.DeliverySpecifications.SpecialRestrictions.Add(SpecialRestriction.RestrictPOBoxes);
            request.PaymentDetails.ChargeAmount.Amount           = 1080M;
            request.PaymentDetails.ChargeAmount.CurrencyCode     = Currency.EUR;
            request.PaymentDetails.TotalOrderAmount.Amount       = 1080M;
            request.PaymentDetails.TotalOrderAmount.CurrencyCode = Currency.EUR;
            request.PaymentDetails.PaymentIntent = PaymentIntent.Authorize;
        }
        public async Task<CreateCheckoutSessionResponse> CreateCheckoutSession([FromBody] CreateCheckoutSessionRequest req)
        {
            // Create new Checkout Session for the order
            // Other optional params include:
            //  [billing_address_collection] - to display billing address details on the page
            //  [customer] - if you have an existing Stripe Customer ID
            //  [customer_email] - lets you prefill the email input in the form
            //  For full details see https:#stripe.com/docs/api/checkout/sessions/create

            //  ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param
            var options = new SessionCreateOptions
            {
                SuccessUrl = $"{this.options.Value.Domain}/success.html?session_id={{CHECKOUT_SESSION_ID}}",
                CancelUrl = $"{this.options.Value.Domain}/canceled.html",
                PaymentMethodTypes = new List<string> { "card" },
                Mode = "payment",
                LineItems = new List<SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Quantity = req.Quantity,
                        Price = this.options.Value.Price,
                    },
                },
            };

            var service = new SessionService(this.client);
            var session = await service.CreateAsync(options);

            return new CreateCheckoutSessionResponse
            {
                SessionId = session.Id,
            };
        }
        public ActionResult <string> Sessions()
        {
            var sessionsRequest = new CreateCheckoutSessionRequest();

            sessionsRequest.merchantAccount = _merchant_account; // required
            sessionsRequest.channel         = (CreateCheckoutSessionRequest.ChannelEnum?)PaymentRequest.ChannelEnum.Web;

            var amount = new Amount("EUR", 1000); // value is 10€ in minor units

            sessionsRequest.amount = amount;
            var orderRef = System.Guid.NewGuid();

            sessionsRequest.reference = orderRef.ToString(); // required

            // required for 3ds2 redirect flow
            sessionsRequest.returnUrl = $"https://localhost:5001/Home/Redirect?orderRef={orderRef}";

            try
            {
                var res = _checkout.Sessions(sessionsRequest);
                _logger.LogInformation($"Response for Payment API::\n{res}\n");
                return(res.ToJson());
            }
            catch (Adyen.HttpClient.HttpClientException e)
            {
                _logger.LogError($"Request for Payments failed::\n{e.ResponseBody}\n");
                throw e;
            }
        }
        public void CanConvertToJsonRecurring()
        {
            // arrange
            var request = new CreateCheckoutSessionRequest
                          (
                checkoutReviewReturnUrl: "https://example.com/review.html",
                storeId: "amzn1.application-oa2-client.000000000000000000000000000000000"
                          );

            request.MerchantMetadata.CustomInformation   = metadataToTest.CustomInformation;
            request.MerchantMetadata.MerchantReferenceId = metadataToTest.MerchantReferenceId;
            request.MerchantMetadata.MerchantStoreName   = metadataToTest.MerchantStoreName;
            request.MerchantMetadata.NoteToBuyer         = metadataToTest.NoteToBuyer;
            request.ChargePermissionType                  = ChargePermissionType.Recurring;
            request.RecurringMetadata.Frequency.Unit      = FrequencyUnit.Variable;
            request.RecurringMetadata.Frequency.Value     = 2;
            request.RecurringMetadata.Amount.Amount       = 12.34m;
            request.RecurringMetadata.Amount.CurrencyCode = Currency.USD;

            // act
            string json  = request.ToJson();
            string json2 = request.ToJson();

            // assert
            Assert.AreEqual(json, json2);
            Assert.AreEqual("{\"storeId\":\"amzn1.application-oa2-client.000000000000000000000000000000000\",\"webCheckoutDetails\":{\"checkoutReviewReturnUrl\":\"https://example.com/review.html\"},\"merchantMetadata\":{\"merchantReferenceId\":\"123\",\"merchantStoreName\":\"myStore\",\"noteToBuyer\":\"myBuyerNote\",\"customInformation\":\"foo\"},\"chargePermissionType\":\"Recurring\",\"recurringMetadata\":{\"frequency\":{\"unit\":\"Variable\",\"value\":2},\"amount\":{\"amount\":12.34,\"currencyCode\":\"USD\"}}}", json);
        }
        public ActionResult <CreateCheckoutSessionResponse> CreateCheckoutSession([FromBody] CreateCheckoutSessionRequest req)
        {
            var options = new SessionCreateOptions
            {
                PaymentMethodTypes = new List <string>
                {
                    "bacs_debit",
                },
                LineItems = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Price    = this.options.Value.Price,
                        Quantity = req.Quantity,
                    },
                },
                Mode = "payment",
                PaymentIntentData = new SessionPaymentIntentDataOptions
                {
                    SetupFutureUsage = "off_session",
                },

                SuccessUrl = this.options.Value.Domain + "/success.html?session_id={CHECKOUT_SESSION_ID}",
                CancelUrl  = this.options.Value.Domain + "/canceled.html",
            };

            var     service = new SessionService();
            Session session = service.Create(options);

            return(new CreateCheckoutSessionResponse
            {
                SessionId = session.Id,
            });
        }
Exemple #8
0
        /// <summary>
        /// Creates a new Checkout Session.
        /// </summary>
        public CheckoutSessionResponse CreateCheckoutSession(CreateCheckoutSessionRequest body, Dictionary <string, string> headers = null)
        {
            var apiPath    = apiUrlBuilder.BuildFullApiPath(Constants.ApiServices.Default, Constants.Resources.WebStore.CheckoutSessions);
            var apiRequest = new ApiRequest(apiPath, HttpMethod.POST, body, headers);

            var result = CallAPI <CheckoutSessionResponse>(apiRequest);

            return(result);
        }
Exemple #9
0
        public void CanGenerateButtonSignatureFromCreateCheckoutSessionRequest()
        {
            var testRequest = new CreateCheckoutSessionRequest(checkoutReviewReturnUrl: "http://localhost:5000/checkout",
                                                               storeId: "testStoreId");
            var result = mockClient.Object.GenerateButtonSignature(testRequest);

            Assert.NotNull(result);
            Assert.AreEqual("baz", result);

            // TODO: Add additional asserts - Potential refactor needed to properly mock and test signature helper
        }
Exemple #10
0
        public void CanCreateCheckoutSession()
        {
            mockClient.Protected().As <IClientMapping>()
            .Setup(c => c.ProcessRequest <CheckoutSessionResponse>(It.IsAny <ApiRequest>(),
                                                                   It.IsAny <Dictionary <string, string> >()))
            .Returns((ApiRequest request, Dictionary <string, string> headers) => AssertPreProcessRequestFlow <CheckoutSessionResponse>(request, headers, HttpMethod.POST, Constants.Resources.WebStore.CheckoutSessions));

            var testRequest = new CreateCheckoutSessionRequest(checkoutReviewReturnUrl: "http://localhost:5000/checkout",
                                                               storeId: "testStoreId");
            var result = mockClient.Object.CreateCheckoutSession(testRequest);
        }
        public async Task <IActionResult> CreateCheckoutSession([FromBody] CreateCheckoutSessionRequest req)
        {
            // This ID is typically stored with the authenticated user in your database. For
            // demonstration purposes, we're pulling this value from environment variables.
            //
            // Note this is not required to create a Subscription, but demonstrates how you would
            // create a new Subscription using Stripe Checkout with an existing user.
            var stripeCustomerId = this.options.Value.Customer;

            var options = new SessionCreateOptions
            {
                SuccessUrl         = $"{this.options.Value.Domain}/success.html?session_id={{CHECKOUT_SESSION_ID}}",
                CancelUrl          = $"{this.options.Value.Domain}/cancel.html",
                PaymentMethodTypes = new List <string>
                {
                    "card",
                },
                Mode      = "subscription",
                LineItems = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Price    = req.PriceId,
                        Quantity = 1,
                    },
                },
                Customer = stripeCustomerId,
            };
            var service = new SessionService(this.client);

            try
            {
                var session = await service.CreateAsync(options);

                return(Ok(new CreateCheckoutSessionResponse
                {
                    SessionId = session.Id,
                }));
            }
            catch (StripeException e)
            {
                Console.WriteLine(e.StripeError.Message);
                return(BadRequest(new ErrorResponse
                {
                    ErrorMessage = new ErrorMessage
                    {
                        Message = e.StripeError.Message,
                    }
                }));
            }
        }
        public void CanConstructParameterlessCtorWithAllPropertiesInitialized()
        {
            // act
            var request = new CreateCheckoutSessionRequest();

            // assert
            Assert.IsNotNull(request);
            Assert.IsNotNull(request.WebCheckoutDetails);
            Assert.IsNotNull(request.DeliverySpecifications);
            Assert.IsNotNull(request.MerchantMetadata);
            Assert.IsNotNull(request.PaymentDetails);
            Assert.IsNotNull(request.ProviderMetadata);
            Assert.IsNotNull(request.RecurringMetadata);
        }
Exemple #13
0
        public CreateCheckoutSessionRequest CreateCheckoutSessionRequest(string checkoutReviewReturnUrl)
        {
            var request = new CreateCheckoutSessionRequest
                          (
                checkoutReviewReturnUrl: checkoutReviewReturnUrl,
                storeId: Options.StoreId
                          );

            var addressRestrictions = request.DeliverySpecifications.AddressRestrictions;

            addressRestrictions.Type = RestrictionType.Allowed;
            addressRestrictions.Restrictions.Add("JP", new Restriction());

            return(request);
        }
        public async Task <IActionResult> CreateCheckoutSession([FromBody] CreateCheckoutSessionRequest req)
        {
            var options = new SessionCreateOptions
            {
                // See https://stripe.com/docs/api/checkout/sessions/create
                // for additional parameters to pass.
                // {CHECKOUT_SESSION_ID} is a string literal; do not change it!
                // the actual Session ID is returned in the query parameter when your customer
                // is redirected to the success page.
                SuccessUrl         = "https://example.com/success.html?session_id={CHECKOUT_SESSION_ID}",
                CancelUrl          = "/checkout",
                PaymentMethodTypes = new List <string>
                {
                    "card",
                },
                Mode      = "subscription",
                LineItems = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Price = req.PriceId,
                        // For metered billing, do not pass quantity
                        Quantity = 1,
                    },
                },
            };

            try
            {
                var session = await _sessionService.CreateAsync(options);

                return(Ok(new CreateCheckoutSessionResponse
                {
                    SessionId = session.Id,
                }));
            }
            catch (StripeException e)
            {
                _logger.LogInformation(e.StripeError.Message);
                return(BadRequest(new ErrorResponse
                {
                    ErrorMessage = new ErrorMessage
                    {
                        Message = e.StripeError.Message,
                    }
                }));
            }
        }
        public async Task <IActionResult> CreateCheckoutSession([FromBody] CreateCheckoutSessionRequest req)
        {
            var options = new SessionCreateOptions
            {
                SuccessUrl         = req.SuccessUrl,
                CancelUrl          = req.FailureUrl,
                PaymentMethodTypes = new List <string>
                {
                    "card",
                },
                Mode      = "subscription",
                LineItems = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Price    = req.PriceId,
                        Quantity = 1,
                    },
                },
            };

            var service = new SessionService();

            service.Create(options);
            try
            {
                var session = await service.CreateAsync(options);

                return(Ok(new CreateCheckoutSessionResponse
                {
                    SessionId = session.Id,
                    PublicKey = _stripeSettings.PublicKey
                }));
            }
            catch (StripeException e)
            {
                Console.WriteLine(e.StripeError.Message);
                return(BadRequest(new ErrorResponse
                {
                    ErrorMessage = new ErrorMessage
                    {
                        Message = e.StripeError.Message,
                    }
                }));
            }
        }
Exemple #16
0
        public async Task <IActionResult> CreateCheckoutSession([FromBody] CreateCheckoutSessionRequest req)
        {
            Debug.WriteLine("path " + Request.Host);
            var options = new SessionCreateOptions
            {
                SuccessUrl         = $"https://{Request.Host}/home/success?session_id={{CHECKOUT_SESSION_ID}}",
                CancelUrl          = $"https://{Request.Host}/cancel.html",
                PaymentMethodTypes = new List <string>
                {
                    "card",
                },
                Mode          = "subscription",
                CustomerEmail = User.Identity.Name,
                LineItems     = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Price    = req.PriceId,
                        Quantity = 1,
                    },
                },
            };
            var service = new SessionService(this.client);

            try
            {
                var session = await service.CreateAsync(options);

                return(Ok(new CreateCheckoutSessionResponse
                {
                    SessionId = session.Id,
                }));
            }
            catch (StripeException e)
            {
                Console.WriteLine(e.StripeError.Message);
                return(BadRequest(new ErrorResponse
                {
                    ErrorMessage = new ErrorMessage
                    {
                        Message = e.StripeError.Message,
                    }
                }));
            }
        }
Exemple #17
0
        public void CanCreateCheckoutSessionWithCustomHeader()
        {
            var myHeaderKey   = "my-header-key";
            var myHeaderValue = "some string";

            mockClient.Protected().As <IClientMapping>()
            .Setup(c => c.ProcessRequest <CheckoutSessionResponse>(It.IsAny <ApiRequest>(),
                                                                   It.IsAny <Dictionary <string, string> >()))
            .Returns((ApiRequest request, Dictionary <string, string> headers) => AssertPreProcessRequestFlowWithCustomHeader <CheckoutSessionResponse>(request, headers, myHeaderKey, HttpMethod.POST));

            var headers = new Dictionary <string, string> {
                { myHeaderKey, myHeaderValue }
            };

            var request = new CreateCheckoutSessionRequest(checkoutReviewReturnUrl: "http://localhost:5000/checkout",
                                                           storeId: "testStoreId");

            var result = mockClient.Object.CreateCheckoutSession(request, headers);
        }
Exemple #18
0
        public async Task <IActionResult> CreateCheckoutSession([FromBody] CreateCheckoutSessionRequest req)
        {
            var options = new SessionCreateOptions
            {
                SuccessUrl         = $"{this.options.Value.Domain}/Home/Success?session_id={{CHECKOUT_SESSION_ID}}",
                CancelUrl          = $"{this.options.Value.Domain}/Home/Index",
                PaymentMethodTypes = new List <string>
                {
                    "card",
                },
                Mode      = "subscription",
                LineItems = new List <SessionLineItemOptions>
                {
                    new SessionLineItemOptions
                    {
                        Price    = req.PriceId,
                        Quantity = 1,
                    },
                },
            };
            var service = new SessionService(this.client);

            try
            {
                var session = await service.CreateAsync(options);

                return(Ok(new CreateCheckoutSessionResponse
                {
                    SessionId = session.Id,
                }));
            }
            catch (StripeException e)
            {
                Console.WriteLine(e.StripeError.Message);
                return(BadRequest(new ErrorResponse
                {
                    ErrorMessage = new ErrorMessage
                    {
                        Message = e.StripeError.Message,
                    }
                }));
            }
        }
        public void CanConstructWithAllPropertiesInitialized()
        {
            // act
            var request = new CreateCheckoutSessionRequest
                          (
                checkoutReviewReturnUrl: "https://example.com/review.html",
                storeId: "amzn1.application-oa2-client.000000000000000000000000000000000"
                          );

            // assert
            Assert.IsNotNull(request);
            Assert.IsNotNull(request.WebCheckoutDetails);
            Assert.IsNotNull(request.DeliverySpecifications);
            Assert.IsNotNull(request.MerchantMetadata);
            Assert.IsNotNull(request.PaymentDetails);
            Assert.IsNotNull(request.ProviderMetadata);
            Assert.IsNotNull(request.RecurringMetadata);
            Assert.AreEqual("https://example.com/review.html", request.WebCheckoutDetails.CheckoutReviewReturnUrl);
            Assert.AreEqual("amzn1.application-oa2-client.000000000000000000000000000000000", request.StoreId);
        }
        public void DenySingleCountry()
        {
            // arrange
            var request = new CreateCheckoutSessionRequest
                          (
                checkoutReviewReturnUrl: "https://example.com/review.html",
                storeId: "amzn1.application-oa2-client.000000000000000000000000000000000"
                          );

            request.DeliverySpecifications.AddressRestrictions.Type = RestrictionType.NotAllowed;
            request.DeliverySpecifications.AddressRestrictions.AddCountryRestriction("US");

            // act
            var jsonResult  = request.ToJson();
            var jsonResult2 = request.ToJson();

            // assert
            Assert.AreEqual(jsonResult, jsonResult2);
            Assert.IsTrue(jsonResult.Contains("\"deliverySpecifications\":{\"addressRestrictions\":{\"type\":\"NotAllowed\",\"restrictions\":{\"US\":{}}}}"));
        }
        public void OneCountryWithOneStateAndOneZipCode()
        {
            // arrange
            var request = new CreateCheckoutSessionRequest
                          (
                checkoutReviewReturnUrl: "https://example.com/review.html",
                storeId: "amzn1.application-oa2-client.000000000000000000000000000000000"
                          );

            request.DeliverySpecifications.AddressRestrictions.Type = RestrictionType.Allowed;
            request.DeliverySpecifications.AddressRestrictions.AddCountryRestriction("DE").AddStateOrRegionRestriction("RLP").AddZipCodesRestriction("12345");

            // act
            var jsonResult  = request.ToJson();
            var jsonResult2 = request.ToJson();

            // assert
            Assert.AreEqual(jsonResult, jsonResult2);
            Assert.IsTrue(jsonResult.Contains("addressRestrictions\":{\"type\":\"Allowed\",\"restrictions\":{\"DE\":{\"statesOrRegions\":[\"RLP\"],\"zipCodes\":[\"12345\"]}}}}"));
        }
        public void OneCountryWithTwoStatesAndAnotherCountry()
        {
            // arrange
            var request = new CreateCheckoutSessionRequest
                          (
                checkoutReviewReturnUrl: "https://example.com/review.html",
                storeId: "amzn1.application-oa2-client.000000000000000000000000000000000"
                          );

            request.DeliverySpecifications.AddressRestrictions.Type = RestrictionType.Allowed;
            request.DeliverySpecifications.AddressRestrictions.AddCountryRestriction("US").AddStateOrRegionRestriction("WA").AddStateOrRegionRestriction("NY");
            request.DeliverySpecifications.AddressRestrictions.AddCountryRestriction("DE");

            // act
            var jsonResult  = request.ToJson();
            var jsonResult2 = request.ToJson();

            // assert
            Assert.AreEqual(jsonResult, jsonResult2);
            Assert.IsTrue(jsonResult.Contains("\"deliverySpecifications\":{\"addressRestrictions\":{\"type\":\"Allowed\",\"restrictions\":{\"US\":{\"statesOrRegions\":[\"WA\",\"NY\"]},\"DE\":{}}}}"));
        }
        public void AllowSingleCountryButApplySpecialRestrictions()
        {
            // arrange
            var request = new CreateCheckoutSessionRequest
                          (
                checkoutReviewReturnUrl: "https://example.com/review.html",
                storeId: "amzn1.application-oa2-client.000000000000000000000000000000000"
                          );

            request.DeliverySpecifications.AddressRestrictions.Type = RestrictionType.Allowed;
            request.DeliverySpecifications.AddressRestrictions.AddCountryRestriction("DE");
            request.DeliverySpecifications.SpecialRestrictions.Add(SpecialRestriction.RestrictPackstations);
            request.DeliverySpecifications.SpecialRestrictions.Add(SpecialRestriction.RestrictPOBoxes);

            // act
            var jsonResult  = request.ToJson();
            var jsonResult2 = request.ToJson();

            // assert
            Assert.AreEqual(jsonResult, jsonResult2);
            Assert.IsTrue(jsonResult.Contains("\"deliverySpecifications\":{\"specialRestrictions\":[\"RestrictPackstations\",\"RestrictPOBoxes\"],\"addressRestrictions\":{\"type\":\"Allowed\",\"restrictions\":{\"DE\":{}}}}"));
        }
        public void CanConvertToJsonMerchantMetaData()
        {
            // arrange
            var request = new CreateCheckoutSessionRequest
                          (
                checkoutReviewReturnUrl: "https://example.com/review.html",
                storeId: "amzn1.application-oa2-client.000000000000000000000000000000000"
                          );

            request.MerchantMetadata.CustomInformation   = metadataToTest.CustomInformation;
            request.MerchantMetadata.MerchantReferenceId = metadataToTest.MerchantReferenceId;
            request.MerchantMetadata.MerchantStoreName   = metadataToTest.MerchantStoreName;
            request.MerchantMetadata.NoteToBuyer         = metadataToTest.NoteToBuyer;

            // act
            string json  = request.ToJson();
            string json2 = request.ToJson();

            // assert
            Assert.AreEqual(json, json2);
            Assert.AreEqual("{\"storeId\":\"amzn1.application-oa2-client.000000000000000000000000000000000\",\"webCheckoutDetails\":{\"checkoutReviewReturnUrl\":\"https://example.com/review.html\"},\"merchantMetadata\":{\"merchantReferenceId\":\"123\",\"merchantStoreName\":\"myStore\",\"noteToBuyer\":\"myBuyerNote\",\"customInformation\":\"foo\"}}", json);
        }
        public void CanConvertToJsonDeliverySpecifications()
        {
            // arrange
            var request = new CreateCheckoutSessionRequest
                          (
                checkoutReviewReturnUrl: "https://example.com/review.html",
                storeId: "amzn1.application-oa2-client.000000000000000000000000000000000"
                          );

            request.DeliverySpecifications.AddressRestrictions.Type = RestrictionType.Allowed;
            request.DeliverySpecifications.AddressRestrictions.AddCountryRestriction("US").AddZipCodesRestriction("12345");
            request.DeliverySpecifications.SpecialRestrictions.Add(SpecialRestriction.RestrictPackstations);
            request.DeliverySpecifications.SpecialRestrictions.Add(SpecialRestriction.RestrictPOBoxes);

            // act
            string json  = request.ToJson();
            string json2 = request.ToJson();

            // assert
            Assert.AreEqual(json, json2);
            Assert.AreEqual("{\"storeId\":\"amzn1.application-oa2-client.000000000000000000000000000000000\",\"deliverySpecifications\":{\"specialRestrictions\":[\"RestrictPackstations\",\"RestrictPOBoxes\"],\"addressRestrictions\":{\"type\":\"Allowed\",\"restrictions\":{\"US\":{\"zipCodes\":[\"12345\"]}}}},\"webCheckoutDetails\":{\"checkoutReviewReturnUrl\":\"https://example.com/review.html\"}}", json);
        }
        public void CanConstructWithAllCheckoutSessionScopes()
        {
            CheckoutSessionScope[] scopes = new CheckoutSessionScope[] {
                CheckoutSessionScope.Name,
                CheckoutSessionScope.Email,
                CheckoutSessionScope.PostalCode,
                CheckoutSessionScope.ShippingAddress,
                CheckoutSessionScope.PhoneNumber,
                CheckoutSessionScope.PrimeStatus,
                CheckoutSessionScope.BillingAddress
            };
            // act
            var request = new CreateCheckoutSessionRequest
                          (
                checkoutReviewReturnUrl: "https://example.com/review.html",
                storeId: "amzn1.application-oa2-client.000000000000000000000000000000000",
                scopes
                          );

            // assert
            Assert.IsNotNull(request);
            Assert.IsNotNull(request.WebCheckoutDetails);
            Assert.IsNotNull(request.DeliverySpecifications);
            Assert.IsNotNull(request.MerchantMetadata);
            Assert.IsNotNull(request.PaymentDetails);
            Assert.IsNotNull(request.ProviderMetadata);
            Assert.IsNotNull(request.RecurringMetadata);
            Assert.IsNotNull(request.CheckoutSessionScope);
            Assert.Contains(CheckoutSessionScope.Name, request.CheckoutSessionScope);
            Assert.Contains(CheckoutSessionScope.Email, request.CheckoutSessionScope);
            Assert.Contains(CheckoutSessionScope.PostalCode, request.CheckoutSessionScope);
            Assert.Contains(CheckoutSessionScope.ShippingAddress, request.CheckoutSessionScope);
            Assert.Contains(CheckoutSessionScope.PhoneNumber, request.CheckoutSessionScope);
            Assert.Contains(CheckoutSessionScope.PrimeStatus, request.CheckoutSessionScope);
            Assert.Contains(CheckoutSessionScope.BillingAddress, request.CheckoutSessionScope);
            Assert.AreEqual("https://example.com/review.html", request.WebCheckoutDetails.CheckoutReviewReturnUrl);
            Assert.AreEqual("amzn1.application-oa2-client.000000000000000000000000000000000", request.StoreId);
        }
        public void CanConvertToJsonMinimal()
        {
            // arrange
            var request = new CreateCheckoutSessionRequest
                          (
                checkoutReviewReturnUrl: "https://example.com/review.html",
                storeId: "amzn1.application-oa2-client.000000000000000000000000000000000"
                          );

            // act
            string json  = request.ToJson();
            string json2 = request.ToJson();

            // assert
            Assert.AreEqual(json, json2);
            Assert.AreEqual("{\"storeId\":\"amzn1.application-oa2-client.000000000000000000000000000000000\",\"webCheckoutDetails\":{\"checkoutReviewReturnUrl\":\"https://example.com/review.html\"}}", json);

            // verify request object still allows all setters after being serialized
            request.MerchantMetadata.CustomInformation   = metadataToTest.CustomInformation;
            request.MerchantMetadata.MerchantReferenceId = metadataToTest.MerchantReferenceId;
            request.MerchantMetadata.MerchantStoreName   = metadataToTest.MerchantStoreName;
            request.MerchantMetadata.NoteToBuyer         = metadataToTest.NoteToBuyer;
            request.ChargePermissionType                            = ChargePermissionType.Recurring;
            request.RecurringMetadata.Frequency.Unit                = FrequencyUnit.Variable;
            request.RecurringMetadata.Frequency.Value               = 2;
            request.RecurringMetadata.Amount.Amount                 = 12.34m;
            request.RecurringMetadata.Amount.CurrencyCode           = Currency.USD;
            request.DeliverySpecifications.AddressRestrictions.Type = RestrictionType.Allowed;
            request.DeliverySpecifications.AddressRestrictions.AddCountryRestriction("US").AddZipCodesRestriction("12345");
            request.DeliverySpecifications.SpecialRestrictions.Add(SpecialRestriction.RestrictPackstations);
            request.DeliverySpecifications.SpecialRestrictions.Add(SpecialRestriction.RestrictPOBoxes);
            request.PaymentDetails.ChargeAmount.Amount           = 1080M;
            request.PaymentDetails.ChargeAmount.CurrencyCode     = Currency.EUR;
            request.PaymentDetails.TotalOrderAmount.Amount       = 1080M;
            request.PaymentDetails.TotalOrderAmount.CurrencyCode = Currency.EUR;
            request.PaymentDetails.PaymentIntent = PaymentIntent.Authorize;
        }
        public void CanConvertToJsonWithCheckoutSessionScope()
        {
            CheckoutSessionScope[] scopes = new CheckoutSessionScope[] {
                CheckoutSessionScope.Name,
                CheckoutSessionScope.Email,
                CheckoutSessionScope.PostalCode,
            };

            // arrange
            var request = new CreateCheckoutSessionRequest
                          (
                checkoutReviewReturnUrl: "https://example.com/review.html",
                storeId: "amzn1.application-oa2-client.000000000000000000000000000000000",
                scopes
                          );

            // act
            string json  = request.ToJson();
            string json2 = request.ToJson();

            // assert
            Assert.AreEqual(json, json2);
            Assert.AreEqual("{\"storeId\":\"amzn1.application-oa2-client.000000000000000000000000000000000\",\"scopes\":[\"name\",\"email\",\"postalCode\"],\"webCheckoutDetails\":{\"checkoutReviewReturnUrl\":\"https://example.com/review.html\"}}", json);
        }
        /// <summary>
        /// Generates the signature string for the Amazon Pay Checkout button.
        /// </summary>
        /// <param name="request">The payload for generating a CheckoutSession as CreateCheckoutSessionRequest object.</param>
        /// <returns>Signature string that can be assigned to the front-end button's "signature" parameter.</returns>
        public string GenerateButtonSignature(CreateCheckoutSessionRequest request)
        {
            var signature = GenerateButtonSignature(request.ToJson());

            return(signature);
        }
Exemple #30
0
        public string CreateButtonSignature(CreateCheckoutSessionRequest request)
        {
            var client = new WebStoreClient(_config);

            return(client.GenerateButtonSignature(request));
        }