1. 程式人生 > >iOS之微信支付開發

iOS之微信支付開發

因為專案需求,支付方式添加了微信支付。之前做過銀聯的支付,所以,感覺不會太難。
使用的SDK為1.7.是13年12月份的,還是手動管理記憶體。
實際支付的程式碼不難,就是幾個配置,因為專案之前做過微信分享,所以配置這步就省略了。
具體支付程式碼:
//調起微信支付
            PayReq* req = [[[PayReq alloc] init]autorelease];
            req.openID      = APPI_ID;
            req.partnerId   = PARTNER_ID;
            req.prepayId
= prePayid; req.nonceStr = nonce_str; req.timeStamp = now; req.package = package; req.sign = sign; [WXApi safeSendReq:req];

不得不吐槽,微信支付的SDK,這裡連個代理都沒有,所以,你想獲取支付後的結果的返回資訊,需要去AppDelegate裡,新增如下程式碼,新增微信的代理:

- (BOOL)application:(UIApplication
*)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { return [WXApi handleOpenURL:url delegate:self]; }

然後,再實現這個方法:

-(void) onResp:(BaseResp*)resp

通過這個方法,你就可以獲取微信支付後的資訊了。但是如果這樣,所有的支付程式碼都在AppDelegate裡,不好,至少微信給的例子就是這樣。我的方法是新增通知,程式碼如下:

-(void) onResp:(BaseResp*)resp
{
    if ([resp isKindOfClass:[PayResp class]])
    {
        PayResp *response = (PayResp *)resp;

//        NSString *strTitle = [NSString stringWithFormat:@"支付結果"];
//        NSString *strMsg = [NSString stringWithFormat:@"errcode:%d", response.errCode];
//        
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle
//                                                        message:strMsg
//                                                       delegate:self
//                                              cancelButtonTitle:@"OK"
//                                              otherButtonTitles:nil, nil];
//        [alert show];

        switch (response.errCode) {
            case WXSuccess: {
                NSNotification *notification = [NSNotification notificationWithName:ORDER_PAY_NOTIFICATION object:@"success"];
                [[NSNotificationCenter defaultCenter] postNotification:notification];
                break;
            }

            default: {
                NSNotification *notification = [NSNotification notificationWithName:ORDER_PAY_NOTIFICATION object:@"fail"];
                [[NSNotificationCenter defaultCenter] postNotification:notification];
                break;
            }
        }
    }
}

然後,在支付那個VC,新增通知

#pragma mark - tabBar隱藏
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if([WXApi isWXAppInstalled]) // 判斷 使用者是否安裝微信
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderPayResult:) name:ORDER_PAY_NOTIFICATION object:nil];//監聽一個通知
    }
}

#pragma mark - tabbar還原
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];//移除通知
}

相關引數的獲取,從我們自己的伺服器獲取