zoukankan      html  css  js  c++  java
  • 微信支付SDK集成

       拖了很久的微信支付,记下来就是为了以后再用的时候不用很晕。自己感觉微信支付相对于支付宝简单多了。也有可能是先做的支付宝支付所以遇到的困难多,之后熟悉流程就简单了。直接了当来---

       SDK集成流程都一样:

         

      (1)SDK下载、导入,framework框架导入:

          SDK下载地址:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=11_1   

          在Target —> BuildPhases —> Link Binary With Libraries 路径下导入需要的库:

          

      • SystemConfiguration.framework
      • libz.tbd
      • libsqlite3.0.tbd
      • CoreTelephony.framework
      • QuartzCore.framework

      (2)设置白名单、回调URL Scheme(target--info里面,两个都有了,这里的是假的,不能暴露信息!)

       (3)完成项目中代码的实现。

           1.在APPDelegate.m文件中。完成以下方法中代码的迁移。

          - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;

          - (BOOL) application:(UIApplication *)application handleOpenURL:(NSURL *)url;

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

          (下面的方法中,有我的支付宝支付的代码,前边已经写了支付宝支付!就没有删,懂就行了!银联支付的已经删了--)

           

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
         //appkey(这里是假的)
        [WXApi registerApp:@"wx5d64383823d57a11" withDescription:@"demo 2.0"];
    
        return YES;
    }
    
    - (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:@"safepay"]) {
            // 支付跳转支付宝钱包进行支付,处理支付结果
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                
            }];
            
            // 授权跳转支付宝钱包进行支付,处理支付结果
            [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
                
                // 解析 auth code
                NSString *result = resultDic[@"result"];
                NSString *authCode = nil;
                if (result.length>0) {
                    NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                    for (NSString *subResult in resultArr) {
                        if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                            authCode = [subResult substringFromIndex:10];
                            break;
                        }
                    }
                }
                NSLog(@"授权结果 authCode = %@", authCode?:@"");
            }];
            
            return [WXApi handleOpenURL:url delegate:self];
        }
        
        return YES;
    
    }

        

        2.在APPDelegate.m中。处理微信的回调,这里边就是支付的结果。(微信很多功能都是通过onResp这个方法回调结果,可以好好看看WXApiObject.h这个文件,里面注释写得挺清楚的)

        

    -(void)onResp:(BaseResp*)resp{
        if ([resp isKindOfClass:[PayResp class]]){
            PayResp*response=(PayResp*)resp;
            switch(response.errCode){
                case WXSuccess:
                    //服务器端查询支付通知或查询API返回的结果再提示成功
                    LOG(@"支付成功");
                    break;
                default:
                    LOG(@"支付失败,retcode=%d",resp.errCode);
                    break;
            }
        }
    }

      (4)当我们支付的时候,微信需要我们的商品信息。跟支付宝支付一样,需要的MD5加密、签名操作都要在服务器做,我们只需要跟服务器交互拿到要传的参数就好了。(涉及到钱,关键信息一定一定在不能放在客户端中!!!)

        这里把支付封装到一个单例类中,直接调用就好了。(这里已经跟服务器对接好,请求到了订单信息)

        

    - (void)wxPrepay:(int)payid charge:(float)paymoney
    {
        [NetworkingHelper Networking:NetworkingTypePay param:^(NSMutableDictionary *parames) {
            [parames setObject:@(1) forKey:@"pcid"];
            [parames setObject:@(paymoney) forKey:@"paymoney"];
            [parames setObject:[BWUser currentUser].channelid forKey:@"userID"];
            [parames setObject:@(payid) forKey:@"payid"];
        } completion:^(NSError *error, id obj) {
            if ([[obj objectForKey:@"result"] intValue] == 0) {
                NSDictionary* prepayInfo = [obj objectForKey:@"info"];
    
                NSDate * datenow = [NSDate date];
    
                NSString* timestam = [NSString stringWithFormat:@"%u",(unsigned int)[datenow timeIntervalSince1970]];
                NSDictionary* dic = @{
                                      //随机码
                                      @"noncestr":[prepayInfo objectForKey:@"nonce_str"],
                                      //预下单编号
                                      @"prepayid":[prepayInfo objectForKey:@"prepay_id"],
                                      //密钥
                                      @"key":[prepayInfo objectForKey:@"key"],
                                      //商铺号
                                      @"partnerid":[prepayInfo objectForKey:@"mch_id"],
                                      //appid
                                      @"appid":[prepayInfo objectForKey:@"appid"],
                                      //时间戳
                                      @"timestamp":timestam,
                                      //
                                      @"package":@"Sign=WXPay"
                                      };
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self wxPay:dic];
                });
                
            }
        }];
    }
    
    - (BOOL)wxPay:(NSDictionary*)payParams
    {
        NSString * temp = [self sortetWithKey:payParams];
        PayReq *request = [[PayReq alloc] init];
        request.partnerId = [payParams objectForKey:@"partnerid"];
        request.prepayId= [payParams objectForKey:@"prepayid"];
        request.package = [payParams objectForKey:@"package"];
        request.nonceStr= [payParams objectForKey:@"noncestr"];
        request.timeStamp = [[payParams objectForKey:@"timestamp"] intValue];
        request.sign= [[temp MD5HexEncode] uppercaseString];
        
        return [WXApi sendReq:request];
    }
    
    
    - (NSString*)sortetWithKey:(NSDictionary*)params
    {
        NSMutableString* paramStr = [[NSMutableString alloc] init];
        NSArray* keys = [params allKeys];
        
        //按字母顺序排序
        NSArray* sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            return [obj1 compare:obj2 options:NSNumericSearch];
        }];
        
        for(NSString* categoryId in sortedArray)
        {
            if (![categoryId isEqualToString:@"key"]) {
                [paramStr appendFormat:@"%@=%@&", categoryId, [params objectForKey:categoryId]];
            }
            
        }
        
        [paramStr appendFormat:@"key=%@", [params objectForKey:@"key"]];
        
        return paramStr;
    }

      

      到这里就算完成了,最后处理一下支付成功、失败就可以了。

     

        

  • 相关阅读:
    Alpha 冲刺 (1/10)
    项目需求分析答辩总结
    项目UML设计(团队)
    第七次作业--项目需求分析(团队)
    第六次作业--结对编程第二次
    第四次作业--项目选题报告(团队)
    第二次结对作业
    第一次结对编程作业
    第7组 团队展示
    js学习笔记
  • 原文地址:https://www.cnblogs.com/yeschenbaby/p/6632466.html
Copyright © 2011-2022 走看看