This repository has been archived by the owner on Nov 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
WindowsPaymentOperation.cs
310 lines (249 loc) · 12.1 KB
/
WindowsPaymentOperation.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
// ---------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ---------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.ApplicationModel.Payments;
using Windows.UI.Popups;
namespace YetAnotherShoppingApp
{
static class WindowsPaymentOperation
{
private static readonly string[] SupportedPaymentMethodIds = new string[]
{
BasicCardPaymentProtocol.PaymentMethodId,
};
private static readonly string[] BasicCardSupportedNetworks = new string[]
{
BasicCardNetwork.Visa,
BasicCardNetwork.Mastercard,
BasicCardNetwork.AmericanExpress,
};
private static readonly BasicCardType[] BasicCardSupportedTypes = new BasicCardType[]
{
BasicCardType.Credit,
BasicCardType.Debit,
BasicCardType.Prepaid,
};
private static readonly PaymentMethodData BasicCardPaymentMethodData = BasicCardPaymentProtocol.GeneratePaymentMethodData(BasicCardSupportedNetworks, BasicCardSupportedTypes);
private const string MicrosoftPayMerchantId = "<FILL-ME-IN>";
private static readonly PaymentMethodData MicrosoftPayMethodData = MicrosoftPayProtocol.GeneratePaymentMethodData(MicrosoftPayMerchantId, BasicCardSupportedNetworks, BasicCardSupportedTypes, testMode: true);
private static readonly PaymentMethodData[] SupportedPaymentMethods = new PaymentMethodData[]
{
BasicCardPaymentMethodData,
//MicrosoftPayMethodData,
};
/// <summary>
/// Checks to see if the OS supports at least one of our supported payment methods.
/// </summary>
public static async Task<bool> HasSupportedPaymentMethod()
{
PaymentMediator mediator = new PaymentMediator();
IReadOnlyList<string> paymentAppSupportedMethodIds = await mediator.GetSupportedMethodIdsAsync();
IEnumerable<string> methodIdIntersection = Enumerable.Intersect(SupportedPaymentMethodIds, paymentAppSupportedMethodIds);
return methodIdIntersection.Count() > 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();
}
private static void PaymentRequestChangedEventHandler(
Action abortSubmitFunc,
PaymentRequestChangedArgs args,
ShoppingCart shoppingCart)
{
switch (args.ChangeKind)
{
case PaymentRequestChangeKind.ShippingAddress:
shoppingCart.SetShippingAddress(args.ShippingAddress);
break;
case PaymentRequestChangeKind.ShippingOption:
HandleShippingOptionUpdated(args, shoppingCart);
break;
}
var result = new PaymentRequestChangedResult(
changeAcceptedByMerchant: true,
updatedPaymentDetails: CreatePaymentDetails(shoppingCart));
args.Acknowledge(result);
}
private static void HandleShippingOptionUpdated(PaymentRequestChangedArgs args, ShoppingCart shoppingCart)
{
string selectedShippingOptionId = args.SelectedShippingOption.Tag;
// If the payment provider app decides to send us nothing, just ignore the result.
if (!string.IsNullOrEmpty(selectedShippingOptionId))
{
ShippingType selectedShippingType;
if (!Enum.TryParse<ShippingType>(selectedShippingOptionId, out selectedShippingType))
{
// A proper merchant app implementation might want to just ignore the bad result and
// send a correction to the payment provider app.
throw new Exception("Unrecognized shipping method id.");
}
shoppingCart.ShippingType = selectedShippingType;
}
}
private static PaymentDetails CreatePaymentDetails(ShoppingCart shoppingCart)
{
return new PaymentDetails()
{
Total = CreateTotalCostItem(shoppingCart),
DisplayItems = CreateCostBreakdown(shoppingCart),
ShippingOptions = CreateShippingOptions(shoppingCart),
};
}
private static PaymentItem CreateTotalCostItem(ShoppingCart shoppingCart)
{
return new PaymentItem(
"Total",
CreateCurrencyAmount(shoppingCart.CostsSummary.Total));
}
private static IReadOnlyList<PaymentShippingOption> CreateShippingOptions(ShoppingCart shoppingCart)
{
List<PaymentShippingOption> paymentShippingOptions = new List<PaymentShippingOption>();
ShippingType selectedShippingType = shoppingCart.ShippingType;
IReadOnlyDictionary<ShippingType, ShoppingCartCostsSummary> cartShippingOptions = shoppingCart.CalculateShippingOptions();
ShoppingCartCostsSummary costsOfSelectedShipping = cartShippingOptions[selectedShippingType];
foreach (var kvp in cartShippingOptions)
{
ShippingType shippingType = kvp.Key;
ShoppingCartCostsSummary costs = kvp.Value;
PaymentShippingOption shippingOption = new PaymentShippingOption(
label: ShippingTypeStringUtilities.CreateShippingOptionTitle(shippingType, costs, costsOfSelectedShipping),
selected: (shippingType == selectedShippingType),
tag: shippingType.ToString(),
amount: CreateCurrencyAmount(costs.Shipping));
paymentShippingOptions.Add(shippingOption);
}
return paymentShippingOptions;
}
private static PaymentCurrencyAmount CreateCurrencyAmount(decimal value)
{
return new PaymentCurrencyAmount(
value: PriceStringUtilities.ToInvariantString(value),
currency: PriceStringUtilities.Currency);
}
private static IReadOnlyList<PaymentItem> CreateCostBreakdown(ShoppingCart shoppingCart)
{
var paymentItems = new List<PaymentItem>();
foreach (ShoppingCartEntry entry in shoppingCart.Entries)
{
string label = string.Empty;
if (entry.Quantity == 1)
{
label = entry.Product.Title;
}
else
{
label = $"{entry.Product.Title} x{entry.Quantity}";
}
decimal cost = entry.Product.Cost * entry.Quantity;
paymentItems.Add(new PaymentItem(label, CreateCurrencyAmount(cost)));
}
if (shoppingCart.CostsSummary.TotalTax != 0)
{
paymentItems.Add(new PaymentItem("Tax", CreateCurrencyAmount(shoppingCart.CostsSummary.TotalTax)));
}
return paymentItems;
}
}
}