天天看點

iOS開發支付那些事(一)微信支付

很多網友面試的時候 都會被問到你的APP使用什麼支付,說下支付的流程,什麼,不知道!!!!!!那就回家等通知吧 如何 就沒有然後了

接入支付寶開流程 點選這裡 iOS支付那些事(二)支付寶

-一、 微信支付業務流程

商戶APP調用微信提供的SDK調用微信支付子產品,商戶APP會跳轉到微信中完成支付,支付完後跳回到商戶APP内,最後展示支付結果。下面是一個完整的支付發起到結束的流程,

  • 步驟1

    使用者進入商戶APP,選擇商品下單、确認購買,進入支付環節。商戶服務背景生成支付訂單,簽名後将資料傳輸到APP端。

  • 步驟2

    使用者點選後發起支付操作,進入到微信界面,調起微信支付,出現确認支付界面。

  • 步驟3

    使用者确認收款方和金額,點選立即支付後出現輸入密碼界面,可選擇零錢或銀行卡支付。

  • 步驟4

    輸入正确密碼後,支付完成,使用者端微信出現支付詳情頁面。見圖。

  • 步驟5

    回跳到商戶APP中,商戶APP根據支付結果個性化展示訂單處理結果。

  • 二、微信支付開發流程

    1、項目設定APPID

    商戶在微信開放平台申請開發APP應用後,微信開放平台會生成APP的唯一辨別APPID。在Xcode中打開項目,設定項目屬性中的URL Schemes為您的APPID。如圖示紅位置所示。

    iOS開發支付那些事(一)微信支付

    2、注冊APPID

    商戶APP工程中引入微信lib庫和頭檔案,調用API前,需要先向微信注冊您的APPID,代碼如下:

    [WXApi registerApp:@”wxd930ea5d5a258f4f” withDescription:@”demo 2.0”];

    3、調起支付

    商戶伺服器生成支付訂單,先調用【統一下單API】生成預付單,擷取到prepay_id後将參數再次簽名傳輸給APP發起支付。以下是調起微信支付的關鍵代碼:

PayReq *request = [[[PayReq alloc] init] autorelease];
request.partnerId = @"10000100";
request.prepayId= @"1101000000140415649af9fc314aa427";
request.package = @"Sign=WXPay";
request.nonceStr= @"a462b76e7436e98e0ed6e13c64b4fd1c";
request.timeStamp= @"1397527777";
request.sign= @"582282D72DD2B03AD892830965F428CB16E7A256";
[WXApi sendReq:request];
           

注意:該sign生成字段名清單見調起支付API

4、支付結果回調

照微信SDK Sample,在類實作onResp函數,支付完成後,微信APP會傳回到商戶APP并回調onResp函數,開發者需要在該函數中接收通知,判斷傳回錯誤碼,如果支付成功則去背景查詢支付結果再展示使用者實際支付結果。注意 一定不能以用戶端傳回作為使用者支付的結果,應以伺服器端的接收的支付通知或查詢API傳回的結果為準。代碼示例如下:

-(void)onResp:(BaseResp*)resp{
              if ([respisKindOfClass:[PayRespclass]]){
                  PayResp*response=(PayResp*)resp;
                  switch(response.errCode){
                      caseWXSuccess:
                                //伺服器端查詢支付通知或查詢API傳回的結果再提示成功
                                NSlog(@"支付成功");
                        break;
                        default:
                        NSlog(@"支付失敗,retcode=%d",resp.errCode);
                        break;
                  }
                    }
                } 
           

回調中errCode值清單:

0 成功 展示成功頁面

-1 錯誤 可能的原因:簽名錯誤、未注冊APPID、項目設定APPID不正确、注冊的APPID與設定的不比對、其他異常等。

-2 使用者取消 無需處理。發生場景:使用者不支付了,點選取消,傳回APP。

  • 三、現在我們來建立第一個微信支付
    1. 導入微信支付庫

    微信開放平台新增了微信子產品使用者統計功能,便于開發者統計微信功能子產品的使用者使用和活躍情況。開發者需要在工程中連結上:SystemConfiguration.framework,libz.dylib,libsqlite3.0.dylib。

    最重要的時這個庫:libc++.dylib

  • 2.在AppDelegate中導入
  • (1)AppDelegate中導入
#import "WXApi.h"
#import "WXApiObject.h"
           

(2)注冊

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[WXApi registerApp:WXAppId withDescription:@"yishuPayDes"];

}
           

(3)跳轉處理

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    NSLog(@"跳轉到URL schema中配置的位址-->%@",url);//跳轉到URL schema中配置的位址 
    if ([UMSocialSnsService handleOpenURL:url]) {
        return  [UMSocialSnsService handleOpenURL:url];
    }else{
        return [WXApi handleOpenURL:url delegate:self];
    }
}
           

(3)回調方法

-(void) onResp:(BaseResp*)resp
{
    NSString *strMsg = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    NSString *strTitle;

    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        strTitle = [NSString stringWithFormat:@"發送媒體消息結果"];
    }
    if([resp isKindOfClass:[PayResp class]]){
        //支付傳回結果,實際支付結果需要去微信伺服器端查詢
        strTitle = [NSString stringWithFormat:@"支付結果"];

        switch (resp.errCode) {
            case WXSuccess:{
                strMsg = @"支付結果:成功!";
                NSLog(@"支付成功-PaySuccess,retcode = %d", resp.errCode);
                NSNotification *notification = [NSNotification notificationWithName:ORDER_PAY_NOTIFICATION object:@"success"];
                [[NSNotificationCenter defaultCenter] postNotification:notification];
                break;
            }
            default:{
                strMsg = [NSString stringWithFormat:@"支付結果:失敗!retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                NSLog(@"錯誤,retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                NSNotification *notification = [NSNotification notificationWithName:ORDER_PAY_NOTIFICATION object:@"fail"];
                [[NSNotificationCenter defaultCenter] postNotification:notification];
                break;
            }
        }
    }
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//    [alert show];
           

3.接下來在需要支付的界面做這些事:

//監聽通知
- (void)viewWillAppear:(BOOL)animated{
    [self requestDownloadData];
    if([WXApi isWXAppInstalled]) // 判斷 使用者是否安裝微信
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderPayResult:) name:ORDER_PAY_NOTIFICATION object:nil];//監聽一個通知
    }
    [super viewWillAppear:animated];
}
/*ORDER_PAY_NOTIFICATION*/這個寫個宏,全局裡寫,怎麼寫?建.h檔案!
//移除通知
- (void)viewWillDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter]removeObserver:self]; 
}
           

開始支付

1. 預備工作

(1)我這裡封裝了下載下傳類AF(自己感覺比較友善,親們自己寫下載下傳就好了,因為我們公司的網絡資料就那麼幾種)主要用于請求背景伺服器已經做好的資料,請求下來的參數給微信,用于支付!(2)擷取每台裝置的IP位址,(3)HUD是啥,大家都用過,不說了(ps:HUD特效,自己定義看看那種效果好!)(4)背景做了什麼:http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php這個位址給背景參考下,需要的參數都在上面移動端不需要寫,如果你要寫,我不攔你…哈哈,當練手吧!

2.代碼
           
#pragma mark - 微信支付
- (void)WeiXinPay{


    if([WXApi isWXAppInstalled]) // 判斷 使用者是否安裝微信
    {

        HUD.delegate = self;
        HUD.labelText = @"正在為您支付...";
        [HUD show:YES];


        NSString *userID = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
        NSString *ipAdress = [MyHttpDownload GetIPAddress:YES];
        NSLog(@"ipAdress%@",ipAdress);
        NSLog(@"self.order_orderinfoid%@",self.order_orderinfoid);
        NSLog(@"送出位址%@",[NSString stringWithFormat:TESTWXPayUrl,userID,self.order_orderinfoid,_WXPayStyleStr,ipAdress]);
        NSDictionary *dict = @{@"uid":userID,@"orderinfo_id":self.order_orderinfoid,@"type":_WXPayStyleStr,@"ip":ipAdress};
        [MyHttpDownload GetDownload:WXPayUrl param:dict finish:^(NSData *data, NSDictionary *obj, NSError *error) {
            if ([obj[@"data"] isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dataDict = obj[@"data"];
                NSLog(@"respose資訊--》%@",dataDict);
                if (obj != nil) {
                    [self WXPayRequest:dataDict[@"appid"] nonceStr:dataDict[@"noncestr"] package:dataDict[@"package"] partnerId:dataDict[@"partnerid"] prepayId:dataDict[@"prepayid"] timeStamp:dataDict[@"timestamp"] sign:dataDict[@"sign"]];
                }else{
                    [HUD hide:YES];
                    FlyAlertView *alert = [[FlyAlertView alloc] initWithTitle:@"提示" contentText:@"網絡有誤" leftButtonTitle:nil rightButtonTitle:@"确定"];
                    [alert show];
                }
            }else{
                [HUD hide:YES];
                NSString *mess = [NSString stringWithFormat:@"%@,退出重試!",obj[@"data"]];
                [self alert:@"提示" msg:mess];
            }
        }];
    }else{
        [HUD hide:YES];
        [self alert:@"提示" msg:@"您未安裝微信!"];
    }

}
#pragma mark - 發起支付請求
- (void)WXPayRequest:(NSString *)appId nonceStr:(NSString *)nonceStr package:(NSString *)package partnerId:(NSString *)partnerId prepayId:(NSString *)prepayId timeStamp:(NSString *)timeStamp sign:(NSString *)sign{
       //調起微信支付
    PayReq* wxreq             = [[PayReq alloc] init];
    wxreq.openID              = WXAppId;
    wxreq.partnerId           = partnerId;
    wxreq.prepayId            = prepayId;
    wxreq.nonceStr            = nonceStr;
    wxreq.timeStamp           = [timeStamp intValue];
    wxreq.package             = package;
    wxreq.sign                = sign;
    [WXApi sendReq:wxreq];
}

#pragma mark - 通知資訊
- (void)getOrderPayResult:(NSNotification *)notification{
    if ([notification.object isEqualToString:@"success"])
    {
        [HUD hide:YES];
        [self alert:@"恭喜" msg:@"您已成功支付啦!"];
        payStatusStr           = @"YES";
        _successPayView.hidden = NO;
        _toPayView.hidden      = YES;
        [self creatPaySuccess];

    }
    else
    {
        [HUD hide:YES];
        [self alert:@"提示" msg:@"支付失敗"];

    }
}

//用戶端提示資訊
- (void)alert:(NSString *)title msg:(NSString *)msg
{
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alter show];
}