关闭

iOS集成微信支付

标签: iossdk微信支付
206人阅读 评论(0) 收藏 举报

1,SDK导入

  1. 下载官方SDK:下载地址
  2. 将SDK文件中包含的 libWeChatSDK.a,WXApi.h,WXApiObject.h,WechatAuthSDK 三个文件添加到你所建的工程中,这里要注意别下错了,之前试过下载的SDK名字都一样,但是就是不能够支付,因为那个SDK只能够支持分享和登录。
  3. 添加依赖:
    • SystemConfiguration.framework
    • libz.tbd
    • libsqlite3.tbd
    • CoreTelephony.framework
    • libc++.tbd
  4. TARGETS-BuildSettings-Build Options: Enable Bitcode 设置为NO
  5. 建立PrefixHeader文件,TARGETS-BuildSettings-Apple LLVM7.1-Language :Prefix Headerd, 将建立的pch文件路径填写进去(Xcode右键Show in finder,直接把文件拖到上面,把头路径删除,只留项目名那一级,开头没有/)
  6. PrefixHeader内导入头文件:
     #import <UIKit/UIKit.h>
     #import "WXApi.h"
  7. TARGETS-Info-URL types添加一项,URL scheme为你注册的应用程序id(例如:wx40xxxxxxxxxxxxxx),其它为空不填。
  8. AppDelegate中注册
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
        [WXApi registerApp:@"wx40xxxxxxxxxxxxxx" withDescription:@"demo 2.0"];
        return YES;
    }
  9. AppDelegate中设置微信SDK的代理
    - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
        return  [WXApi handleOpenURL:url delegate:self]; //这里设置任何一个实现了WXApiDelegate协议的对象
    }
    
    - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
        return [WXApi handleOpenURL:url delegate:self]; //这里设置任何一个实现了WXApiDelegate协议的对象
    }
  10. 在微信SDK的代理中处理支付结果
    - (void)onResp:(BaseResp *)resp
    {
        if([resp isKindOfClass:[PayResp class]]){
    
            //支付返回结果,实际支付结果需要去微信服务器端查询
            NSString *strMsg;
    
            switch (resp.errCode) {
                case WXSuccess:
                    strMsg = @"支付结果:成功!";
                    NSLog(@"支付成功-PaySuccess,retcode = %d", resp.errCode);
                    break;
    
                default:
                    strMsg = [NSString stringWithFormat:@"支付结果:失败!retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                    NSLog(@"错误,retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                    break;
            }
        }
    }

以上的配置都做完,SDK环境就正式搭好了,其它的在ShareSDK中需要配的诸如白名单什么的,我试了下只导入官方的SDK是不用配的。

2,通过服务器获取订单信息调取支付

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];  // 向服务器请求订单信息的参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = @"app登录帐户的token";
    parameters[@"order_id"] = @"要下单的商品id";
    [manager POST:@"向服务器获取订单信息的url" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject[@"data"];    // 服务器返回的订单数据
        // 通过服务器返回的订单数据创建请求参数
        PayReq *request = [[PayReq alloc] init];
        request.openID = [dic objectForKey:@"appid"];
        request.partnerId = [dic objectForKey:@"partenerId"];
        request.prepayId = [dic objectForKey:@"prepayId"];
        request.package = [dic objectForKey:@"packageValue"];
        request.nonceStr = [dic objectForKey:@"nonceStr"];
        request.timeStamp = (UInt32)[[dic objectForKey:@"timeStamp"] integerValue];
        request.sign = [dic objectForKey:@"sign"];
        // 调起微信客户端发起支付
        [WXApi sendReq:request];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];

3,本地生成订单信息支付

    NSString *tradeNO = [self generateTradeNO];
    NSString *addressIP = [self getIPAddress:YES];
    NSString *orderno = [NSString stringWithFormat:@"%ld",time(0)];
    DataMD5 *data = [[DataMD5 alloc] initWithAppid:WX_APPID mch_id:MCH_ID nonce_str:tradeNO partner_id:WX_PartnerKey body:@"充值" out_trade_no:orderno total_fee:PRICE spbill_create_ip:addressIP notify_url:NOTIFY_URL trade_type:TRADE_TYPE];
    NSString *string = [[data dic] XMLString];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
    [manager.requestSerializer setValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:WXUNIFIEDORDERURL forHTTPHeaderField:@"SOAPAction"];
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        return string;
    }];
    [manager POST:WXUNIFIEDORDERURL parameters:string progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSDictionary dictionaryWithXMLString:responseString];
        if ([[dic objectForKey:@"result_code"] isEqualToString:@"SUCCESS"] && [[dic objectForKey:@"return_code"] isEqualToString:@"SUCCESS"]) {
            PayReq *request = [[PayReq alloc] init];
            request.openID = [dic objectForKey:WXAPPID];
            request.partnerId = [dic objectForKey:WXMCHID];
            request.prepayId = [dic objectForKey:WXPREPAYID];
            request.package = @"Sign=WXPay";
            request.nonceStr = [dic objectForKey:WXNONCESTR];
            NSDate *datenow = [NSDate date];
            NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
            UInt32 timeStamp = [timeSp intValue];
            request.timeStamp = timeStamp;
            DataMD5 *md5 = [[DataMD5 alloc] init];
            request.sign = [md5 createMD5SingForPay:request.openID partnerid:request.partnerId prepayid:request.prepayId package:request.package noncestr:request.nonceStr timestamp:request.timeStamp];
            [WXApi sendReq:request];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];

本地生成订单支付的处理比较麻烦,具体代码详见Demo

4,Demo下载

Gitgub: https://github.com/Joker-388/WechatDemo.git

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:5053次
    • 积分:124
    • 等级:
    • 排名:千里之外
    • 原创:8篇
    • 转载:0篇
    • 译文:0篇
    • 评论:1条
    文章存档
    最新评论