예제 #1
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            var            pm      = new PaymentMediator();
            PaymentDetails details = new PaymentDetails(new PaymentItem("Total", new PaymentCurrencyAmount(selectedProduct.UnitPrice.ToString(), "USD")), new List <PaymentItem>()
            {
                new PaymentItem(selectedProduct.ProductName, new PaymentCurrencyAmount(selectedProduct.UnitPrice.ToString(), "USD"))
            })
            {
                ShippingOptions = CreateShippingOptions()
            };
            List <PaymentMethodData> methods = new List <PaymentMethodData>()
            {
                new PaymentMethodData(new List <String>()
                {
                    "basic-card"
                })
            };
            PaymentMerchantInfo merchantInfo = new PaymentMerchantInfo(new Uri("http://www.contoso.com"));
            PaymentOptions      options      = new PaymentOptions()
            {
                RequestShipping = true, ShippingType = PaymentShippingType.Delivery, RequestPayerEmail = PaymentOptionPresence.Optional, RequestPayerName = PaymentOptionPresence.Required, RequestPayerPhoneNumber = PaymentOptionPresence.None
            };

            var paymentRequest = new PaymentRequest(
                details,
                methods,
                merchantInfo,
                options);

            var result = await pm.SubmitPaymentRequestAsync(paymentRequest);

            UpdateUserStatus(result);
        }
예제 #2
0
        private async void Pay_Click(object sender, RoutedEventArgs e)
        {
            // Package line items and total to submit to Microsoft Payments
            var paymentItems = new List <PaymentItem>();

            foreach (OrderDetail detail in OrderDetails)
            {
                paymentItems.Add(new PaymentItem(detail.ProductName,
                                                 new PaymentCurrencyAmount(detail.NetAmountString, "USD")));
            }

            var paymentDetails = new PaymentDetails();

            paymentDetails.Total = new PaymentItem("Total",
                                                   new PaymentCurrencyAmount(OrderTotal, "USD"));
            paymentDetails.DisplayItems    = paymentItems;
            paymentDetails.ShippingOptions = CreateShippingOptions();
            var paymentOptions = new PaymentOptions()
            {
                RequestShipping         = true,
                ShippingType            = PaymentShippingType.Delivery,
                RequestPayerEmail       = PaymentOptionPresence.Optional,
                RequestPayerName        = PaymentOptionPresence.Required,
                RequestPayerPhoneNumber = PaymentOptionPresence.None
            };
            var merchantInfo   = new PaymentMerchantInfo(new Uri("http://www.contoso.com"));
            var paymentMethods = new List <PaymentMethodData>();

            paymentMethods.Add(new PaymentMethodData(new List <string>()
            {
                "basic-card"
            }));

            // Send payment request to Microsoft for cardholder authentication
            // Microsoft prompts user to enter CVV
            var paymentRequest = new PaymentRequest(paymentDetails,
                                                    paymentMethods, merchantInfo, paymentOptions);
            var mediator = new PaymentMediator();
            var result   = await mediator.SubmitPaymentRequestAsync(paymentRequest);

            await UpdateUI(result);
        }
예제 #3
0
        public async Task PurchaseProductAsync(Product product)
        {
            if (product != null)
            {
                PaymentMediator mediator = new PaymentMediator();
                ((IInitializeWithWindow)(object)mediator).Initialize(this.handle);

                PaymentDetails paymentDetails = new PaymentDetails(
                    new PaymentItem(
                        "Total",
                        new PaymentCurrencyAmount(
                            product.Price.ToString(CultureInfo.CurrentCulture),
                            "GBP")),
                    new List <PaymentItem>()
                {
                    new PaymentItem(
                        product.Name,
                        new PaymentCurrencyAmount(
                            product.Price.ToString(
                                CultureInfo.CurrentCulture),
                            "GBP"))
                })
                {
                    ShippingOptions =
                        GetShippingOptions()
                };
                List <PaymentMethodData> methods =
                    new List <PaymentMethodData> {
                    new PaymentMethodData(new List <string>()
                    {
                        "basic-card"
                    })
                };
                PaymentMerchantInfo merchantInfo = new PaymentMerchantInfo(new Uri("http://www.myenterprise.co.uk"));
                PaymentOptions      options      = new PaymentOptions()
                {
                    RequestShipping         = true,
                    ShippingType            = PaymentShippingType.Delivery,
                    RequestPayerEmail       = PaymentOptionPresence.Optional,
                    RequestPayerName        = PaymentOptionPresence.Required,
                    RequestPayerPhoneNumber = PaymentOptionPresence.None
                };

                PaymentRequest paymentRequest = new PaymentRequest(paymentDetails, methods, merchantInfo, options);

                PaymentRequestSubmitResult res = await mediator.SubmitPaymentRequestAsync(paymentRequest);

                if (res.Status == PaymentRequestStatus.Succeeded)
                {
                    await res.Response.CompleteAsync(PaymentRequestCompletionStatus.Succeeded);

                    NotificationService.Current.Show(
                        "Payment Successful",
                        $"The payment for '{product}' was successful!",
                        null,
                        null);
                }
                else
                {
                    NotificationService.Current.Show(
                        "Payment Failed",
                        $"A problem occurred while paying for '{product}'!",
                        null,
                        null);
                }
            }
        }
예제 #4
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            // <SnippetEnumerate>
            // Enumerate all the payment methods out store accepts.
            string data =
                "{" +
                "\"merchantId\":\"merchant-id-from-seller-portal\"," +
                "\"supportedNetworks\":[\"visa\",\"mastercard\"]," +
                "\"supportedTypes\":[\"credit\"]" +
                "}";

            var acceptedPaymentMethods = new[]
            {
                new PaymentMethodData(new[] { "https://pay.microsoft.com/microsoftpay" }, data)
            };

            // Determine which of our accepted payment methods are supported by the customer's payment applications.
            var paymentMediator         = new PaymentMediator();
            var supportedPaymentMethods = await paymentMediator.GetSupportedMethodIdsAsync();

            // </SnippetEnumerate>

            // <SnippetDisplayItems>
            // Describe the individual items in this purchase.
            var displayItemsInCart = new List <PaymentItem>
            {
                new PaymentItem("Contoso shoes", new PaymentCurrencyAmount("88.00", "USD")),
                new PaymentItem("Contoso shoelaces", new PaymentCurrencyAmount("0.56", "USD")),
            };

            // Calculate the total value of display items.
            var totalValue = displayItemsInCart.Sum(item => Convert.ToDecimal(item.Amount.Value));
            // </SnippetDisplayItems>

            // <SnippetTaxes>
            // Add items for any/all applicable taxes.
            decimal salesTax          = 0.095241M * totalValue;
            var     displayItemsTaxes = new[]
            {
                new PaymentItem("Taxes",
                                new PaymentCurrencyAmount(salesTax.ToString(CultureInfo.InvariantCulture), "USD"))
            };

            // Describe the complete list of display items, and total them up.
            var displayItems = displayItemsInCart.Concat(displayItemsTaxes).ToList();

            totalValue = displayItems.Sum(item => Convert.ToDecimal(item.Amount.Value));
            var totalItem = new PaymentItem("Total",
                                            new PaymentCurrencyAmount(totalValue.ToString(CultureInfo.InvariantCulture), "USD"));
            // </SnippetTaxes>

            // <SnippetDiscountRate>
            // Create an item to apply a 5% discount if the customer pays with a Contoso credit card.
            var contosoDiscountValue       = Convert.ToDecimal(totalItem.Amount.Value) * -0.05M;
            var displayItemsForContosoCard = new[]
            {
                new PaymentItem("Contoso Card Discount (5%)",
                                new PaymentCurrencyAmount($"{contosoDiscountValue}", "USD"))
            };

            displayItems.Concat(displayItemsForContosoCard);

            // Re-calculate the total value with discount
            totalValue = displayItemsInCart.Sum(item => Convert.ToDecimal(item.Amount.Value));
            var totalItemForContosoCard = new PaymentItem("Total",
                                                          new PaymentCurrencyAmount(totalValue.ToString(CultureInfo.InvariantCulture), "USD"));
            // </SnippetDiscountRate>

            // <SnippetAggregate>
            // Aggregate all of the prepared payment details.
            var details = new PaymentDetails()
            {
                DisplayItems    = displayItems,
                Total           = totalItem,
                ShippingOptions = new List <PaymentShippingOption>
                {
                    new PaymentShippingOption("Standard (3-5 business days)", new PaymentCurrencyAmount("0.00", "USD")),
                    new PaymentShippingOption("Express (2-3 buiness days)", new PaymentCurrencyAmount("4.99", "USD")),
                    new PaymentShippingOption("Overnight (1 business day)", new PaymentCurrencyAmount("11.99", "USD")),
                },
                Modifiers = new[]
                {
                    new PaymentDetailsModifier(new[] { "contoso/credit" },
                                               totalItemForContosoCard, displayItemsForContosoCard)
                },
            };
            // </SnippetAggregate>

            // <SnippetPaymentOptions>
            // Describe options for any additional information needed to process the transaction.
            var options = new PaymentOptions()
            {
                RequestPayerName        = PaymentOptionPresence.None,
                RequestPayerEmail       = PaymentOptionPresence.None,
                RequestPayerPhoneNumber = PaymentOptionPresence.None,
                RequestShipping         = true,
                ShippingType            = PaymentShippingType.Shipping
            };
            // </SnippetPaymentOptions>

            // <SnippetSubmit>
            // Create a structure describing our merchant application.
            var merchantInfo = new PaymentMerchantInfo(new Uri("https://store.contoso.com"));

            // Create a new payment request and associated internal state describing this proposed transaction.
            var request = new PaymentRequest(details, acceptedPaymentMethods, merchantInfo, options);

            // Submit the payment request for mediation and (possibly) user review and wait for the user to approve
            // or reject the request.
            var submissionResult = await paymentMediator.SubmitPaymentRequestAsync(request, (s, ev) =>
            {
                ev.Acknowledge(new PaymentRequestChangedResult(true));
            });

            if (submissionResult.Status != PaymentRequestStatus.Succeeded)
            {
                await new MessageDialog($"Payment request rejected by customer {submissionResult.Status}.").ShowAsync();
                return;
            }
            // </SnippetSubmit>

            // <SnippetComplete>
            await submissionResult.Response.CompleteAsync(PaymentRequestCompletionStatus.Succeeded);

            // </SnippetComplete>
        }
예제 #5
0
        /// <summary>
        /// Starts a checkout operation and runs it to completion.
        /// </summary>
        public static async Task CheckoutAsync(ShoppingCart shoppingCart)
        {
            Uri merchantUri = new Uri("http://www.contoso.com");
            PaymentMerchantInfo merchantInfo = new PaymentMerchantInfo(merchantUri);

            PaymentOptions options = new PaymentOptions();

            options.RequestShipping         = true;
            options.ShippingType            = PaymentShippingType.Delivery;
            options.RequestPayerEmail       = PaymentOptionPresence.Optional;
            options.RequestPayerName        = PaymentOptionPresence.Required;
            options.RequestPayerPhoneNumber = PaymentOptionPresence.Optional;

            PaymentRequest request = new PaymentRequest(
                CreatePaymentDetails(shoppingCart),
                SupportedPaymentMethods,
                merchantInfo,
                options);

            IAsyncOperation <PaymentRequestSubmitResult> submitOperation = null;

            Action abortSubmitFunc = () =>
            {
                submitOperation.Cancel();
            };

            PaymentRequestChangedHandler changedHandler = (sender, args) =>
            {
                PaymentRequestChangedEventHandler(abortSubmitFunc, args, shoppingCart);
            };

            PaymentMediator mediator = new PaymentMediator();

            submitOperation = mediator.SubmitPaymentRequestAsync(request, changedHandler);

            PaymentRequestSubmitResult result = await submitOperation;

            if (result.Status != PaymentRequestStatus.Succeeded)
            {
                string message = result.Status == PaymentRequestStatus.Canceled ?
                                 "The payment was canceled." :
                                 "The payment failed.";

                MessageDialog failedMessageDialog = new MessageDialog(message);
                await failedMessageDialog.ShowAsync();

                return;
            }

            PaymentResponse response = result.Response;
            PaymentToken    token    = response.PaymentToken;

            bool paymentSucceeded = false;

            switch (token.PaymentMethodId)
            {
            case BasicCardPaymentProtocol.PaymentMethodId:
                BasicCardResponse basicCardResponse = BasicCardPaymentProtocol.ParseResponse(token.JsonDetails);

                //
                // TODO: Use data inside 'basicCardResponse' to collect payment.
                //

                paymentSucceeded = true;
                break;

            case MicrosoftPayProtocol.PaymentMethodId:
                MicrosoftPayProtocolResponse microsoftPayResponse = MicrosoftPayProtocol.ParseResponse(token.JsonDetails);

                switch (microsoftPayResponse.Format)
                {
                case "Stripe":
                    //
                    // TODO: Use data inside 'microsoftPayResponse.Token' to collect payment.
                    //

                    paymentSucceeded = true;
                    break;

                case "Error":
                    paymentSucceeded = false;
                    break;

                case "Invalid":
                    throw new Exception("The payment request was invalid.");

                default:
                    throw new Exception("Unsupported payment gateway.");
                }
                break;

            default:
                await result.Response.CompleteAsync(PaymentRequestCompletionStatus.Unknown);

                throw new Exception("Unsupported payment method ID.");
            }

            await result.Response.CompleteAsync(paymentSucceeded?PaymentRequestCompletionStatus.Succeeded : PaymentRequestCompletionStatus.Failed);

            string completionMessage = paymentSucceeded ?
                                       "The payment succeeded." :
                                       "Unable to process the payment.";

            MessageDialog messageDialog = new MessageDialog(completionMessage);
            await messageDialog.ShowAsync();
        }