-
Notifications
You must be signed in to change notification settings - Fork 17
/
Demo.cs
449 lines (368 loc) · 17.1 KB
/
Demo.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace IapDemo
{
public class DemoConfig
{
public String clientSecret { get; set; }
public String clientId { get; set; }
public String tokenUrl { get; set; }
public String orderUrl { get; set; }
public String subscriptionUrl { get; set; }
public String applicationPublicKey { get; set; }
public static DemoConfig getDefaultConfig()
{
DemoConfig demoConfig = new DemoConfig();
// your client secret
demoConfig.clientSecret = "appsecret";
// your app id
demoConfig.clientId = "1234567";
// application public key, base64 encode
demoConfig.applicationPublicKey = "public key, base64 encode";
// product token url
// demoConfig.tokenUrl = "https://oauth-login.cloud.huawei.com/oauth2/v3/token";
demoConfig.tokenUrl = "http://exampleserver/_mockserver_/oauth2/v3/token";
return demoConfig;
}
}
public class AtResponse
{
public string access_token { get; set; }
}
public class AtDemo
{
public static String getAppAt()
{
var demoConfig = DemoConfig.getDefaultConfig();
String grant_type = "client_credentials";
String msgBody = String.Format("grant_type={0}&client_secret={1}&client_id={2}", WebUtility.UrlEncode(grant_type),
WebUtility.UrlEncode(demoConfig.clientSecret), WebUtility.UrlEncode(demoConfig.clientId));
String retString = httpPost(demoConfig.tokenUrl, "application/x-www-form-urlencoded", msgBody, 5, null);
if (retString.IndexOf("access_token") != -1)
{
var atResponse = JsonSerializer.Deserialize<AtResponse>(retString);
return atResponse.access_token;
}
else
{
System.Console.Error.WriteLine("Get token fail, " + retString);
throw new System.ArgumentException("Get token fail", retString);
}
}
public static String httpPost(String httpUrl, String contentType, String requestBody, int timeOut, HttpRequestHeaders headers)
{
var client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(timeOut);
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
var httpContent = new StringContent(requestBody, Encoding.UTF8, contentType);
var repTask = client.PostAsync(httpUrl, httpContent);
repTask.Wait();
var resContent = repTask.Result.Content;
var strTask = resContent.ReadAsStringAsync();
strTask.Wait();
var retString = strTask.Result;
return retString;
}
public static HttpRequestHeaders buildAuthorization()
{
var appAt = AtDemo.getAppAt();
var oriString = String.Format("APPAT:{0}", appAt);
var authString = Convert.ToBase64String(Encoding.UTF8.GetBytes(oriString));
var authHeaderString = String.Format("Basic {0}", authString);
HttpRequestHeaders headers = new HttpClient().DefaultRequestHeaders;
headers.Add(HttpRequestHeader.Authorization.ToString(), authHeaderString);
return headers;
}
public static Boolean verifyRsaSign(String content, String sign, String publicKey)
{
bool checkRet = false;
using (var rsaProv = new RSACryptoServiceProvider())
{
byte[] contentBytes = Encoding.UTF8.GetBytes(content);
byte[] signBytes = Convert.FromBase64String(sign);
byte[] publicKeyBytes = Convert.FromBase64String(publicKey);
try
{
int readBytes = 0;
rsaProv.ImportSubjectPublicKeyInfo(publicKeyBytes, out readBytes);
checkRet = rsaProv.VerifyData(contentBytes, signBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
finally
{
rsaProv.PersistKeyInCsp = false;
}
}
return checkRet;
}
}
public class OrderDemo
{
public static String getRootUrl(int accountFlag) {
if (accountFlag == 1) {
// site for telecom carrier
return "https://orders-at-dre.iap.dbankcloud.com";
}
// TODO: replace the (ip:port) to the real one,
return "http://ip:port";
}
public static void verifyToken(String purchaseToken, String productId,int accountFlag)
{
var requestHeaders = AtDemo.buildAuthorization();
Dictionary<string, string> bodyMap = new Dictionary<string, string>();
bodyMap.Add("purchaseToken", purchaseToken);
bodyMap.Add("productId", productId);
var bodyString = JsonSerializer.Serialize(bodyMap);
String responseString = AtDemo.httpPost(getRootUrl(accountFlag) + "/applications/purchases/tokens/verify", "application/json", bodyString, 5, requestHeaders);
// TODO: display the response as string in console, you can replace it with your business logic.
Console.WriteLine(responseString);
}
public static void cancelledListPurchase(long endAt, long startAt, int maxRows, int type, string continuationToken,int accountFlag)
{
var requestHeaders = AtDemo.buildAuthorization();
// pack the request body
Dictionary<string, string> bodyMap = new Dictionary<string, string>();
bodyMap.Add("endAt", endAt.ToString());
bodyMap.Add("startAt", startAt.ToString());
bodyMap.Add("maxRows", maxRows.ToString());
bodyMap.Add("type", type.ToString());
bodyMap.Add("continuationToken", continuationToken.ToString());
var bodyString = JsonSerializer.Serialize(bodyMap);
String responseString = AtDemo.httpPost(getRootUrl(accountFlag) + "/applications/v2/purchases/cancelledList", "application/json", bodyString, 5, requestHeaders);
// TODO: display the response as string in console, you can replace it with your business logic.
Console.WriteLine(responseString);
}
public static void confirmPurchase(String purchaseToken, String productId,int accountFlag)
{
var requestHeaders = AtDemo.buildAuthorization();
// pack the request body
Dictionary<string, string> bodyMap = new Dictionary<string, string>();
bodyMap.Add("purchaseToken", purchaseToken);
bodyMap.Add("productId", productId);
var bodyString = JsonSerializer.Serialize(bodyMap);
String responseString = AtDemo.httpPost(getRootUrl(accountFlag) + "/applications/v2/purchases/confirm", "application/json", bodyString, 5, requestHeaders);
// TODO: display the response as string in console, you can replace it with your business logic.
Console.WriteLine(responseString);
}
}
public class SubscriptionDemo
{
public static String getRootUrl(int accountFlag) {
if ( accountFlag == 1) {
// site for telecom carrier
return "https://subscr-at-dre.iap.dbankcloud.com";
}
// TODO: replace the (ip:port) to the real one,
return "http://ip:port";
}
public static void getSubscription(string subscriptionId, string purchaseToken,int accountFlag)
{
var headers = AtDemo.buildAuthorization();
// pack the request body
Dictionary<string, string> bodyMap = new Dictionary<string, string>();
bodyMap.Add("subscriptionId", subscriptionId);
bodyMap.Add("purchaseToken", purchaseToken);
var bodyString = JsonSerializer.Serialize(bodyMap);
var config = DemoConfig.getDefaultConfig();
String responseString = AtDemo.httpPost(getRootUrl(accountFlag) + "/sub/applications/v2/purchases/get",
"application/json", bodyString, 5, headers);
// TODO: display the response as string in console, you can replace it with your business logic.
Console.WriteLine(responseString);
}
public static void stopSubscription(string subscriptionId, string purchaseToken,int accountFlag)
{
var headers = AtDemo.buildAuthorization();
// pack the request body
Dictionary<string, string> bodyMap = new Dictionary<string, string>();
bodyMap.Add("subscriptionId", subscriptionId);
bodyMap.Add("purchaseToken", purchaseToken);
var bodyString = JsonSerializer.Serialize(bodyMap);
String responseString = AtDemo.httpPost(getRootUrl(accountFlag) + "/sub/applications/v2/purchases/stop",
"application/json", bodyString, 5, headers);
// TODO: display the response as string in console, you can replace it with your business logic.
Console.WriteLine(responseString);
}
public static void delaySubscription(string subscriptionId, string purchaseToken, long currentExpirationTime,
long desiredExpirationTime,int accountFlag)
{
var headers = AtDemo.buildAuthorization();
// pack the request body
Dictionary<string, string> bodyMap = new Dictionary<string, string>();
bodyMap.Add("subscriptionId", subscriptionId);
bodyMap.Add("purchaseToken", purchaseToken);
bodyMap.Add("currentExpirationTime", currentExpirationTime + "");
bodyMap.Add("desiredExpirationTime", desiredExpirationTime + "");
var bodyString = JsonSerializer.Serialize(bodyMap);
String responseString = AtDemo.httpPost(getRootUrl(accountFlag) + "/sub/applications/v2/purchases/delay",
"application/json", bodyString, 5, headers);
// TODO: display the response as string in console, you can replace it with your business logic.
Console.WriteLine(responseString);
}
public static void returnFeeSubscription(string subscriptionId, string purchaseToken,int accountFlag)
{
var headers = AtDemo.buildAuthorization();
// pack the request body
Dictionary<string, string> bodyMap = new Dictionary<string, string>();
bodyMap.Add("subscriptionId", subscriptionId);
bodyMap.Add("purchaseToken", purchaseToken);
var bodyString = JsonSerializer.Serialize(bodyMap);
String responseString = AtDemo.httpPost(getRootUrl(accountFlag) + "/sub/applications/v2/purchases/returnFee",
"application/json", bodyString, 5, headers);
// TODO: display the response as string in console, you can replace it with your business logic.
Console.WriteLine(responseString);
}
public static void withdrawalSubscription(string subscriptionId, string purchaseToken,int accountFlag)
{
var headers = AtDemo.buildAuthorization();
// pack the request body
Dictionary<string, string> bodyMap = new Dictionary<string, string>();
bodyMap.Add("subscriptionId", subscriptionId);
bodyMap.Add("purchaseToken", purchaseToken);
var bodyString = JsonSerializer.Serialize(bodyMap);
String responseString = AtDemo.httpPost(getRootUrl(accountFlag) + "/sub/applications/v2/purchases/withdrawal",
"application/json", bodyString, 5, headers);
// TODO: display the response as string in console, you can replace it with your business logic.
Console.WriteLine(responseString);
}
}
public class NotificationRequest
{
public string statusUpdateNotification { get; set; }
public string notifycationSignature { get; set; }
}
public class NotificationResponse
{
public string ErrorCode { get; set; }
public string ErrorMsg { get; set; }
}
public class StatusUpdateNotification
{
public string environment { get; set; }
public int notificationType { get; set; }
public string subscriptionId { get; set; }
public long cancellationDate { get; set; }
public string orderId { get; set; }
public string latestReceipt { get; set; }
public string latestReceiptInfo { get; set; }
public string latestReceiptInfoSignature { get; set; }
public string latestExpiredReceipt { get; set; }
public string latestExpiredReceiptInfo { get; set; }
public string latestExpiredReceiptInfoSignature { get; set; }
public long autoRenewStatus { get; set; }
public string refundPayOrderId { get; set; }
public string productId { get; set; }
public string applicationId { get; set; }
public int expirationIntent { get; set; }
}
enum NotificationType : int
{
INITIAL_BUY = 0,
CANCEL = 1,
RENEWAL = 2,
INTERACTIVE_RENEWAL = 3,
NEW_RENEWAL_PREF = 4,
RENEWAL_STOPPED = 5,
RENEWAL_RESTORED = 6,
RENEWAL_RECURRING = 7,
ON_HOLD = 9,
PAUSED = 10,
PAUSE_PLAN_CHANGED = 11,
PRICE_CHANGE_CONFIRMED = 12,
DEFERRED = 13,
}
public class NotificationDemo
{
public static void dealNotification(String information)
{
var request = JsonSerializer.Deserialize<NotificationRequest>(information);
var checkRet = AtDemo.verifyRsaSign(request.statusUpdateNotification, request.notifycationSignature, DemoConfig.getDefaultConfig().applicationPublicKey);
if (!checkRet)
{
Console.WriteLine("rsa sign check fail");
return;
}
var info = JsonSerializer.Deserialize<StatusUpdateNotification>(request.statusUpdateNotification);
var notificationType = (NotificationType)info.notificationType;
switch (notificationType)
{
case NotificationType.INITIAL_BUY:
break;
case NotificationType.CANCEL:
break;
case NotificationType.RENEWAL:
break;
case NotificationType.INTERACTIVE_RENEWAL:
break;
case NotificationType.NEW_RENEWAL_PREF:
break;
case NotificationType.RENEWAL_STOPPED:
break;
case NotificationType.RENEWAL_RESTORED:
break;
case NotificationType.RENEWAL_RECURRING:
break;
case NotificationType.ON_HOLD:
break;
case NotificationType.PAUSED:
break;
case NotificationType.PAUSE_PLAN_CHANGED:
break;
case NotificationType.PRICE_CHANGE_CONFIRMED:
break;
case NotificationType.DEFERRED:
break;
default:
break;
}
}
}
public class Demo
{
static void Main(string[] args)
{
var at = AtDemo.getAppAt();
Console.Out.WriteLine(at);
OrderDemo.verifyToken("demoToken", "demoProductId", 0);
OrderDemo.cancelledListPurchase(123, 456, 100, 0, "demoToken", 0);
OrderDemo.confirmPurchase("demoToken", "demoProductId", 0);
SubscriptionDemo.getSubscription("demoId", "demoToken", 0);
SubscriptionDemo.stopSubscription("demoId", "demoToken", 0);
SubscriptionDemo.delaySubscription("demoId", "demoToken", 123, 456, 0);
SubscriptionDemo.returnFeeSubscription("demoId", "demoToken", 0);
SubscriptionDemo.withdrawalSubscription("demoId", "demoToken", 0);
}
}
}