IVTMyAccountViewController.m
20.2 KB
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//
// IVTMyAccountViewController.m
// IVTMeLive
//
// Created by xrg on 16/5/6.
// Copyright © 2016年 Joky. All rights reserved.
//
#import "IVTMyAccountViewController.h"
#import "UIFont+IVTMeFont.h"
#import "UIColor+IVTMeColor.h"
#import "IVTMyAccountTableViewModel.h"
#import "IVTMyAccountTableViewCell.h"
#import "Masonry.h"
// 微信
#import "WXApi.h"
#import <CommonCrypto/CommonDigest.h>
#import <StoreKit/StoreKit.h>
//http://me.demo.bjivt.com/api/getConversionPrice.json
#define kIAP_60_ProductId @"com.cnlive.mijialiveshow.sixty"
#define kIAP_300_ProductId @"com.cnlive.mijialiveshow.threehundred"
#define kIAP_900_ProductId @"com.cnlive.mijialiveshow.ninehundred"
@interface IVTMyAccountViewController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate, SKPaymentTransactionObserver, SKProductsRequestDelegate>
{
SKPayment * payment;
}
@property (nonatomic, strong) UITableView *accountTableview;
@property (nonatomic, strong) UIImageView *goldImg;
@property (nonatomic, strong) NSMutableArray *listArr;
@property (nonatomic, strong) NSMutableArray *priceArr;
@property (nonatomic, strong) NSMutableArray *chineseCoinArr;
/*
一区一行
*/
@property (nonatomic, strong) UILabel *accountText;
@property (nonatomic, strong) UILabel *accountNumber;
@property (nonatomic, strong) NSArray *IAPProIDArray;
@property (nonatomic, strong) IVTMyAccountTableViewModel *accountModel;
@property (nonatomic, strong) NSString *out_trade_no;
@end
@implementation IVTMyAccountViewController
- (void)dealloc {
[[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self request];
// [self initNavView];
[self creatTableView];
// Do any additional setup after loading the view.
_listArr = [[NSMutableArray alloc] init];
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
self.IAPProIDArray = [NSArray arrayWithObjects:kIAP_60_ProductId, kIAP_300_ProductId, kIAP_900_ProductId, nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)initNavView{
self.navigationItem.title = @"我的账户";
//
// __unsafe_unretained typeof (self) wself = self;
// //整体背景nav view
// UIView* navBgView = [[UIView alloc] init];
// [self.view addSubview:navBgView];
// navBgView.backgroundColor = [UIColor IVTLightRedColor];
// [navBgView mas_makeConstraints:^(MASConstraintMaker* make) {
// make.left.equalTo(wself.view.mas_left);
// make.right.equalTo(wself.view.mas_right);
// make.top.equalTo(@0);
// make.height.equalTo(@58);
// }];
//
//
// UILabel *message = [[UILabel alloc]init];
// [navBgView addSubview:message];
// message.text =@"我的账户";
// message.textColor = [UIColor IVTTitleColor];
// message.font = [UIFont YXFontOfSize:19];
// [message mas_makeConstraints:^(MASConstraintMaker *make) {
// make.centerX.equalTo(navBgView.mas_centerX);
// make.top.equalTo(wself.view.mas_top).with.offset(29);
// make.size.mas_equalTo(CGSizeMake(100.0f, 19.0f));
// }];
//
//
// //背景nav 返回上级页面按钮
// UIButton* backButton = [UIButton buttonWithType:UIButtonTypeCustom];
// [navBgView addSubview:backButton];
// UIImage* navImage = [UIImage imageNamed:@"返回键"];
// [backButton mas_makeConstraints:^(MASConstraintMaker* make) {
// make.left.equalTo(wself.view);
// make.top.equalTo(wself.view.mas_top).with.offset(18);
// make.size.mas_equalTo(CGSizeMake(40, 40));
//
// }];
// [backButton setImage:navImage forState:UIControlStateNormal];
// backButton.imageEdgeInsets = UIEdgeInsetsMake(5,5,5,5);
// [backButton addTarget:self action:@selector(backToTopPage:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark - 创建tableview
- (void)creatTableView
{
_accountTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStyleGrouped];
_accountTableview.delegate = self;
_accountTableview.dataSource = self;
_accountTableview.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
[self.view addSubview:_accountTableview];
UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
headView.backgroundColor = [UIColor whiteColor];
_accountTableview.tableHeaderView = headView;
_accountText = [[UILabel alloc] initWithFrame:CGRectZero];
_accountText.text = @"中国币余额";
_accountText.textColor = [UIColor IVTMainTextColor];
_accountText.font = [UIFont IVTH3Font];
_accountText.textAlignment = NSTextAlignmentCenter;
[_accountText sizeToFit];
_accountText.center = CGPointMake(16+_accountText.frame.size.width/2, headView.frame.size.height/2);
[headView addSubview:_accountText];
_goldImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"中国币"]];
_goldImg.frame = CGRectMake(CGRectGetMaxX(_accountText.frame)+6 , 15, 20, 20);
[headView addSubview:_goldImg];
_accountNumber = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_goldImg.frame)+10, 10, 100, 30)];
_accountNumber.text = [NSString stringWithFormat:@"%.0f", [[IVTAccountTool getChineseCoinTotal] floatValue]/100];
_accountNumber.textColor = [UIColor IVTMainTextColor];
_accountNumber.font = [UIFont IVTH3Font];
_accountNumber.textAlignment = 1;
[headView addSubview:_accountNumber];
}
#pragma mark - 请求数据
- (void)request
{
__weak __typeof(self)vc = self;
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[IVTAccountTool getUserId] forKey:@"username"];
[HUDUtil showLoading];
[[IVTNetworkAPIClient sharedClient] getConversionPrice:dict success:^(NSDictionary *successData) {
[HUDUtil hide];
NSArray *listArray = [successData objectForKey:@"list"];
for (NSMutableDictionary *dict in listArray) {
IVTMyAccountTableViewModel *accountModel = [[IVTMyAccountTableViewModel alloc] initWithDictionary:dict];
[vc.listArr addObject:accountModel];
}
dispatch_async(dispatch_get_main_queue(), ^{
[vc.accountTableview reloadData];
});
} error:^(NSDictionary *successData) {
NSString *msg = successData[@"description"];
[HUDUtil showError:msg];
} failure:^(NSError *failureError) {
[HUDUtil showError:@"网络异常"];
}];
}
#pragma mark - 按钮点击事件
//返回按钮点击
-(void)backToTopPage:(id)sender
{
[self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - delegate&datasorce
// 设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 48;
}
- ( CGFloat )tableView:( UITableView *)tableView heightForHeaderInSection:( NSInteger )section
{
return 36.0 ;
}
// 设置标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
self.title = @"充值";
return self.title;
}
//1、确定tableView中的分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
//2、确定每个section中的cell数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _listArr.count;
}
//3、确定Cell中的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
IVTMyAccountTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[IVTMyAccountTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
IVTMyAccountTableViewModel *accountTableViewModel = [_listArr objectAtIndex:indexPath.row];
cell.accountModel = accountTableViewModel;
return cell;
}
//4、点击cell时
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.accountModel = _listArr[indexPath.row];
if (self.accountModel && indexPath.row < [self.IAPProIDArray count]) {
[self buyProdution:self.IAPProIDArray[indexPath.row]];
} else {
[SVProgressHUD showErrorWithStatus:@"没有获取到产品信息,请重试"];
}
}
- (void)buyProdution:(NSString *)proID{
if ([SKPaymentQueue canMakePayments]) {
[self getProductInfo:proID];
} else {
[SVProgressHUD showInfoWithStatus:@"用户禁止应用内付费购买"];
}
}
//从Apple查询用户点击购买的产品的信息
- (void)getProductInfo:(NSString *)productIdentifier {
NSArray *product = [[NSArray alloc] initWithObjects:productIdentifier, nil];
NSSet *set = [NSSet setWithArray:product];
SKProductsRequest * request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
request.delegate = self;
[request start];
[SVProgressHUD show];
}
#pragma mark -- SKProductsRequestDelegate
// 查询成功后的回调
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
NSArray *myProduct = response.products;
if (myProduct.count == 0) {
[SVProgressHUD showErrorWithStatus:@"没有获取到产品信息,请重试"];
return;
}
payment = [SKPayment paymentWithProduct:[myProduct firstObject]];
[self requestPrepay];
}
//查询失败后的回调
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
[SVProgressHUD showErrorWithStatus:@"无法获取产品信息,请重试"];
}
#pragma mark - SKPaymentTransactionObserver
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
for (SKPaymentTransaction *transaction in transactions)
{
switch (transaction.transactionState)
{
case SKPaymentTransactionStatePurchased://交易完成
[self completeTransaction:transaction];
break;
case SKPaymentTransactionStateFailed://交易失败
[self failedTransaction:transaction];
break;
case SKPaymentTransactionStateRestored://已经购买过该商品
[self restoreTransaction:transaction];
break;
case SKPaymentTransactionStatePurchasing://商品添加进列表
[SVProgressHUD showWithStatus:@"正在请求付费信息,请稍后"];
break;
default:
[SVProgressHUD showErrorWithStatus:@"交易失败"];
break;
}
}
}
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[IVTAccountTool getUserId] forKey:@"username"];
[dict setObject:[IVTAccountTool getPassword] forKey:@"captcha"];
[dict setObject:@"meRechargeSuccess" forKey:@"mark"];
[dict setObject:self.accountModel.price forKey:@"money"];
[[IVTNetworkAPIClient sharedClient] recharge:dict success:^(NSDictionary *successData) {
if ([[successData objectForKey:@"code"] integerValue] == 0) {
[SVProgressHUD showSuccessWithStatus:@"充值成功"];
NSNumber *chineseCoin = [[successData objectForKey:@"data"] objectForKey:@"chinesecoin"];
[IVTAccountTool setChineseCoinTotal:[NSString stringWithFormat:@"%.0f",[chineseCoin floatValue]]];
_accountNumber.text = [NSString stringWithFormat:@"%.0f",[chineseCoin floatValue]/100];
} else {
[SVProgressHUD showErrorWithStatus:@"充值失败"];
}
} error:^(NSDictionary *successData) {
NSString *msg = successData[@"description"];
[HUDUtil showError:msg];
} failure:^(NSError *failureError) {
[SVProgressHUD showErrorWithStatus:@"充值失败"];
}];
[self requestPayed];
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
- (void)failedTransaction:(SKPaymentTransaction *)transaction {
if(transaction.error.code != SKErrorPaymentCancelled) {
[SVProgressHUD dismiss];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"购买失败,请重试"delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alertView show];
} else {
[SVProgressHUD showInfoWithStatus:@"取消交易"];
}
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
[SVProgressHUD dismiss];
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
- (void)checkReceiptIsValid{
// AFHTTPSessionManager manager]GET:@"后台服务器地址" parameters::@"发送的参数(必须包括购买凭证)"
//success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
// if(凭证有效){
// 你要做的事
// }else{//凭证无效
// 你要做的事
// }
//
//} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"购买失败,请重试"delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"重试", nil];
// [alertView show];
//}
}
- (void)requestPrepay {
/*
*点击获取prodcut实例并初始化订单信息
*/
NSString *urlString = @"https://api.cnlive.com/open/api2/unifypay/prepay";
self.out_trade_no = [NSString stringWithFormat:@"%@%@",[IVTAccountTool getUserId],[IVTThirdFuncTool timeStamp]];
NSMutableDictionary *dictReq = [[NSMutableDictionary alloc] init];
// 开发者ID
[dictReq setObject:@"118_itdr6ijv09" forKey:@"appId"];
// 业务系统中的 订单号
[dictReq setObject:self.out_trade_no forKey:@"out_trade_no"];
// 订单信息
[dictReq setObject:@"0" forKey:@"body"];
// 订单总价
[dictReq setObject:[NSString stringWithFormat:@"%d",[self.accountModel.price intValue]*100] forKey:@"total_fee"];
// 业务回传参数
[dictReq setObject:[IVTAccountTool getUserId] forKey:@"attach.userId"];
// 用户付款通知业务系统接收地址
[dictReq setObject:[NSString stringWithFormat:@"%@user/userRechargeLog.json", kBaseURL] forKey:@"notify_url"];
// 支付平台
[dictReq setObject:@"1001" forKey:@"type"];
NSArray *elements = [dictReq allKeys];
// 按字母排序
NSMutableString *elementsString = [NSMutableString string];
NSArray *sortedElements = [elements sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
return [obj1 compare:obj2 options:NSForcedOrderingSearch];
}];
// NSLog(@"----------1----------\n:%@",sortedElements);
// 字符串拼接
for (NSString *element in sortedElements) {
if (![dictReq[element] isEqualToString:@""] && ![element isEqualToString:@"sign"] && ![element isEqualToString:@"key"]) {
[elementsString appendFormat:@"%@=%@&",element,dictReq[element] ];
}
}
// NSLog(@"----------2----------\n:%@",elementsString);
NSString *strEncode = [elementsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// NSLog(@"----------3----------\n:%@",strEncode);
NSString *stringSignTemp = [strEncode stringByAppendingString:@"key=24557a1060598e010749ec11b43ac9d62e8a765d3463cf"];
// NSLog(@"----------4----------\n:%@",stringSignTemp);
NSString *signStr = [IVTMyAccountViewController sha1:stringSignTemp];
NSString * lastStr = [signStr uppercaseString];
// NSLog(@"----------5----------lastStr:%@",lastStr);
[dictReq setObject:lastStr forKey:@"sign"];
NSLog(@"----------6----------dictReq:%@",dictReq);
// NSLog(@"http://api.cnlive.com/open/api/unifypay/prepay?account=mejia_app&body=0&out_trade_no=%@&sp_id=iowhukpd38&total_fee=1&type=1&sign=%@",orderInfo,lastStr);
[[IVTNetworkAPIClient sharedClient] sendGetRequestForPath:urlString parameters:dictReq success:^(NSDictionary *successData) {
// NSLog(@"requestPrepay-->%@", successData);
// {
// data = {
// "order_id" = 20161215951679302978;
// };
// errorCode = 0;
// errorMessage = OK;
// }
NSInteger code = [successData[@"errorCode"] integerValue];
if (code == 0) {
[[SKPaymentQueue defaultQueue] addPayment:payment];
payment = nil;
} else {
[SVProgressHUD showErrorWithStatus:@"充值失败"];
}
} error:^(NSDictionary *successData) {
[SVProgressHUD showErrorWithStatus:@"充值失败"];
} failure:^(NSError *error) {
[SVProgressHUD showErrorWithStatus:@"充值失败"];
}];
}
//预支付完成
- (void)requestPayed {
/*
*AppStore支付成功后调用预支付完成
*/
NSString *urlString = @"https://api.cnlive.com/open/api2/unifypay/payed";
NSMutableDictionary *dictReq = [[NSMutableDictionary alloc] init];
// 开发者ID
[dictReq setObject:@"118_itdr6ijv09" forKey:@"appId"];
// 业务系统中的 订单号
[dictReq setObject:self.out_trade_no forKey:@"out_trade_no"];
// 支付平台
[dictReq setObject:@"1001" forKey:@"type"];
NSArray *elements = [dictReq allKeys];
// 按字母排序
NSMutableString *elementsString = [NSMutableString string];
NSArray *sortedElements = [elements sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
return [obj1 compare:obj2 options:NSForcedOrderingSearch];
}];
// NSLog(@"----------1----------\n:%@",sortedElements);
// 字符串拼接
for (NSString *element in sortedElements) {
if (![dictReq[element] isEqualToString:@""] && ![element isEqualToString:@"sign"] && ![element isEqualToString:@"key"]) {
[elementsString appendFormat:@"%@=%@&",element,dictReq[element] ];
}
}
// NSLog(@"----------2----------\n:%@",elementsString);
NSString *strEncode = [elementsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// NSLog(@"----------3----------\n:%@",strEncode);
NSString *stringSignTemp = [strEncode stringByAppendingString:@"key=24557a1060598e010749ec11b43ac9d62e8a765d3463cf"];
// NSLog(@"----------4----------\n:%@",stringSignTemp);
NSString *signStr = [IVTMyAccountViewController sha1:stringSignTemp];
NSString * lastStr = [signStr uppercaseString];
// NSLog(@"----------5----------lastStr:%@",lastStr);
[dictReq setObject:lastStr forKey:@"sign"];
NSLog(@"----------6----------dictReq:%@",dictReq);
// NSLog(@"http://api.cnlive.com/open/api/unifypay/prepay?account=mejia_app&body=0&out_trade_no=%@&sp_id=iowhukpd38&total_fee=1&type=1&sign=%@",orderInfo,lastStr);
[[IVTNetworkAPIClient sharedClient] sendGetRequestForPath:urlString parameters:dictReq success:^(NSDictionary *successData) {
NSInteger code = [successData[@"errorCode"] integerValue];
if (code == 0) {
}
} error:^(NSDictionary *successData) {
} failure:^(NSError *error) {
}];
}
#pragma mark - sha1加密
+ (NSString*) sha1:(NSString*)input
{
const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:input.length];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
return output;
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end