iOS-不同應(yīng)用使用同一個微信支付

之前我寫過一篇關(guān)于微信支付的文章
http://www.itdecent.cn/p/259b9285dae0

這篇文章是大家常用的方法,一般都是一個appid對應(yīng)一個應(yīng)用。
接下來我們解決一個appid對應(yīng)不同應(yīng)用的場景。
一個appid對應(yīng)不同應(yīng)用的時候會有一個問題,在微信中點(diǎn)擊返回的時候,無法返回app,你可以通過點(diǎn)擊左上角返回或者從后臺重新進(jìn)入到應(yīng)用

直接看代碼
在Applegate中代碼如下

#import "AppDelegate.h"

//微信支付
#import "WXApi.h"

@interface AppDelegate ()<WXApiDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    //注冊微信支付
    [WXApi registerApp:APP_id withDescription:@"demo"];

    return YES;
}

//iOS9 之后使用這個回調(diào)方法。
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
{
    if ([url.host isEqualToString:@"pay"]) {

        return [WXApi handleOpenURL:url delegate:self];
    }

    return YES;
}


#pragma mark - 微信支付的代理方法
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{

    if ([url.host isEqualToString:@"pay"]) {

        return [WXApi handleOpenURL:url delegate:self];
    }

    return YES;

}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"wxPayNotification" object:nil];

}

上面有兩個系統(tǒng)回調(diào)的方法,第一個是針對ios9.0以后,第二個是針對ios9.0之前的
在帶有微信支付的頁面我們做如下處理

#import "ViewController.h"
//微信支付
#import "WXApi.h"
#import "payRequsestHandler.h"
#import "WXUtil.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(60, 100, 180, 100)];
    button.backgroundColor = [UIColor redColor];
    [button setTitle:@"微信支付" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(test) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];

    //接受成功的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(succeed) name:@"wxPayNotification" object:nil];
}

#pragma mark - ASction Methods
- (void)test
{

    payRequsestHandler *handle = [[payRequsestHandler alloc]init];

    if ( [handle  init:APP_id mch_id:MCH_id]) {

        NSLog(@"初始化成功");

    }

    //設(shè)置商戶密鑰
    [handle setKey:PARTNER_id];

    //提交預(yù)支付,獲得prepape_id
    NSString *order_name = @"測試";   //訂單標(biāo)題
    NSString *order_price = @"1";//測試價(jià)格 分為單位
    NSString *nocify_URL = nocify_url;    //回調(diào)借口
    NSString *noncestr  = [NSString stringWithFormat:@"%d", rand()]; //隨機(jī)串
    NSString *orderno   = [NSString stringWithFormat:@"%ld",time(0)];
    NSMutableDictionary *params = [@{@"appid":APP_id,
                                     @"mch_id":MCH_id,
                                     @"device_info":[[[UIDevice currentDevice] identifierForVendor] UUIDString],
                                     @"nonce_str":noncestr,
                                     @"trade_type":@"APP",
                                     @"body":order_name,
                                     @"notify_url":nocify_URL,
                                     @"out_trade_no":orderno,//商戶訂單號:這個必須用后臺的訂單號
                                     @"spbill_create_ip":@"8.8.8.8",
                                     @"total_fee":order_price}mutableCopy];

    //提交預(yù)支付兩次簽名得到預(yù)支付訂單的id(每次的請求得到的預(yù)支付訂單id都不同)
    NSString *prepate_id = [handle sendPrepay:params];

    //提交預(yù)訂單成功
    if (prepate_id != nil) {

        PayReq *request = [[PayReq alloc]init];

        //商家id
        request.partnerId = MCH_id;

        //訂單id
        request.prepayId = prepate_id;

        //擴(kuò)展字段(官方文檔:暫時填寫固定值)
        request.package = @"Sign=WXPay";

        //隨機(jī)字符串
        request.nonceStr = noncestr;

        //時間戳
        request.timeStamp = (UInt32)[[NSDate date] timeIntervalSince1970];

        //sign參數(shù)(很經(jīng)常出現(xiàn)的問題:就是調(diào)起支付到微信那邊只出現(xiàn)一個確定按鈕,單擊確認(rèn)按鈕直接返回到app,出現(xiàn)這個問題100%是sign參數(shù)的問題)
        /*
         參數(shù)依次是: appid_key、partnerid_key、prepayid_key、固定值Sign=WXPay、預(yù)支付的隨機(jī)數(shù)(跟上面得到預(yù)支付訂單的隨機(jī)數(shù)要一致)、支付時間(秒)

         */
        request.sign = [self createMD5SingForPay:APP_id partnerid:MCH_id prepayid:prepate_id package:@"Sign=WXPay" noncestr:noncestr timestamp:(UInt32)[[NSDate date] timeIntervalSince1970]];



         //生成URLscheme
         NSString *str = [NSString stringWithFormat:@"weixin://app/%@/pay/?nonceStr=%@&package=Sign%%3DWXPay&partnerId=%@&prepayId=%@&timeStamp=%@&sign=%@&signType=SHA1",APP_id,request.nonceStr,request.partnerId,request.prepayId,[NSString stringWithFormat:@"%d",request.timeStamp],request.sign];
            
         [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];

    }

}//點(diǎn)擊微信支付


#pragma mark - Private Methods
-(NSString *)createMD5SingForPay:(NSString *)appid_key partnerid:(NSString *)partnerid_key prepayid:(NSString *)prepayid_key package:(NSString *)package_key noncestr:(NSString *)noncestr_key timestamp:(UInt32)timestamp_key
{
    NSMutableDictionary *signParams = [NSMutableDictionary dictionary];
    [signParams setObject:appid_key forKey:@"appid"];
    [signParams setObject:noncestr_key forKey:@"noncestr"];
    [signParams setObject:package_key forKey:@"package"];
    [signParams setObject:partnerid_key forKey:@"partnerid"];
    [signParams setObject:prepayid_key forKey:@"prepayid"];
    [signParams setObject:[NSString stringWithFormat:@"%u",(unsigned int)timestamp_key] forKey:@"timestamp"];
    NSMutableString *contentString  =[NSMutableString string];
    NSArray *keys = [signParams allKeys];
    //按字母順序排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //拼接字符串
    for (NSString *categoryId in sortedArray) {
        if (   ![[signParams objectForKey:categoryId] isEqualToString:@""]
            && ![[signParams objectForKey:categoryId] isEqualToString:@"sign"]
            && ![[signParams objectForKey:categoryId] isEqualToString:@"key"]
            )
        {
            [contentString appendFormat:@"%@=%@&", categoryId, [signParams objectForKey:categoryId]];
        }
    }
    //添加商戶密鑰key字段
    [contentString appendFormat:@"key=%@",PARTNER_id];
    NSString *result = [self md5:contentString];
    return result;

}//創(chuàng)建發(fā)起支付時的sige簽名


-(NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16]= "0123456789abcdef";
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    //這里的x是小寫則產(chǎn)生的md5也是小寫,x是大寫則md5是大寫,這里只能用大寫,微信的大小寫驗(yàn)證很逗
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}//MD5 加密


- (void)succeed
{
//在這里調(diào)用一個接口,讓服務(wù)器端寫一個查詢訂單的接口,然后返回訂單的狀態(tài),成功或者失敗,然后你就可以通過訂單狀態(tài)進(jìn)行下一步操作
    NSLog(@"支付成功");


}//支付成功的監(jiān)聽方法


#pragma mark - OverRide Methods
- (void)dealloc
{

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"wxPayNotification" object:nil];


}//移除通知


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容