iOS开发---微信支付

作者: PPAbner | 来源:发表于2015-10-21 18:03 被阅读3839次

    在最前面,还是先感谢开发过程中一下两个帖子对自己的帮助,分享!!!

    1. 使用微信支付SDK1.5版本的支付demo
    2. 微信支付如果遇到跳转只有一个确定请看这里

    为了公司的安全,这个版本的微信信息我没配置,不过,刚在网上找到个可以使用的,还是分享下,如下:

    1. 木有微信信息配置的demo
    2. 有微信信息配置的demo

    1.向微信注册你的应用程序信息

    我们的App由我们的项目经理搞定,具体我也不清楚

    官方接入指南如下:

    请到 开发者应用登记页面 进行登记,登记并选择移动应用进行设置后,将获得AppID,可立即用于开发。但应用登记完成后还需要提交审核,只有审核通过的应用才能正式发布使用。
    

    2.下载微信终端SDK文件,项目中导入lib,SDKExport两个文件

    下载路径(点iOS第二个)

    下载iOS第二个

    2.1导进去SDK后需要完善一些配置,要不会报错

    1. 导入必要的库
      导入必要类库
    2. ARC和MRC配置,在后面添加-fno-objc-arc
      ARC和MRC配置
    3. bitCode和HTTPS配置,iOS9后必须配置的
      bitCode和HTTPS配置指导

    3.上代码,胜过千言万语

    AppDelegate.m

    #import "AppDelegate.h"
    #import "ViewController.h"
    #import "WXApi.h"
    @interface AppDelegate ()<WXApiDelegate>
    
    @end
    
    @implementation AppDelegate
    
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        // Override point for customization after application launch.
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        self.window.backgroundColor = [UIColor whiteColor];
        ViewController * vc = [[ViewController alloc]init];
        UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:vc];
        self.window.rootViewController = nav;
        [self.window makeKeyAndVisible];
    
        //向微信注册
        [WXApi registerApp:@"。。。。。。"];
        
        return YES;
    }
    #pragma mark 微信支付相关方法
    -(void)onResp:(BaseResp *)resp{
        //如果第三方程序向微信发送了sendReq的请求,那么onResp会被回调。sendReq请求调用后,会切到微信终端程序界面
        NSString *strMsg=[NSString stringWithFormat:@"errcode:%d",resp.errCode];
        NSString *strTitle;
        if ([resp isKindOfClass:[PayResp class]]) {
            //支付返回结果,实际支付结果需要去微信服务器端查询
            strTitle=[NSString stringWithFormat:@"支付结果"];
            switch (resp.errCode) {
                case WXSuccess:
                    strMsg=@"支付结果:成功!";
                    break;
                    
                default:
                    strMsg = [NSString stringWithFormat:@"支付结果:失败!retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                    break;
            }
        }
        //支付成功后回调
        // http://210.22.129.138:8080/link/public/notifywechatcallback
        
        //下边先注释掉,以后会用得上
        //    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        //    [alert show];
    }
    -(void)onReq:(BaseReq *)req{
        //onReq是微信终端向第三方程序发起请求,要求第三方程序响应。第三方程序响应完后必须调用sendRsp返回。在调用sendRsp返回时,会切回到微信终端程序界面
    }
    

    ViewController.h

    
    #import <UIKit/UIKit.h>
    
    @interface ViewController : UIViewController
    
    @property (nonatomic,assign) int totalPrice;
    
    @property (nonatomic,strong) NSString * orderName;
    
    @end
    
    
    

    ViewController.m

    #import "ViewController.h"
    #import "payRequsestHandler.h"
    #import "WXApi.h"
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        UIButton * bt = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
        bt.backgroundColor = [UIColor redColor];
        [bt addTarget:self action:@selector(ButtonClicked) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:bt];
        
        self.totalPrice = 1;
        self.orderName = @"请叫我雷锋,哈哈";
    }
    -(void)ButtonClicked{
        [self pay];
    }
    - (void)pay
    {
        payRequsestHandler *req = [payRequsestHandler alloc];
        //初始化支付签名对象
        [req init:APP_ID mch_id:MCH_ID];
        //设置密钥
        [req setKey:PARTNER_ID];
        
        
        //获取到实际调起微信支付的参数后,在app端调起支付
        int lastPrice=self.totalPrice*100;
        NSMutableDictionary *dict = [req sendPay_demo:self.orderName price:[NSString stringWithFormat:@"%d",lastPrice]];
        
        if(dict != nil){
            NSMutableString *retcode = [dict objectForKey:@"retcode"];
            if (retcode.intValue == 0){
                NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
                
                //调起微信支付
                PayReq* req             = [[PayReq alloc] init];
                req.openID              = [dict objectForKey:@"appid"];
                req.partnerId           = [dict objectForKey:@"partnerid"];
                req.prepayId            = [dict objectForKey:@"prepayid"];
                req.nonceStr            = [dict objectForKey:@"noncestr"];
                req.timeStamp           = stamp.intValue;
                req.package             = [dict objectForKey:@"package"];
                req.sign                = [dict objectForKey:@"sign"];
                [WXApi sendReq:req];
                //日志输出
                NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",req.openID,req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
            }else{
                NSLog(@"提示信息:=%@",[dict objectForKey:@"retmsg"]);
                //            [self alert:@"提示信息" msg:[dict objectForKey:@"retmsg"]];
            }
        }else{
            NSLog(@"提示信息:-%@",@"服务器返回错误,未获取到json对象");
            //        [self alert:@"提示信息" msg:@"服务器返回错误,未获取到json对象"];
            //        }
            //    }else{
            //        [self alert:@"提示信息" msg:@"服务器返回错误"];
        }
    }
    
    

    payRequsestHandler.h

    配置相关信息

    // 账号帐户资料
    //更改商户把相关参数后可测试
    
    #define APP_ID          @"。。。。。。"               //APPID
    #define APP_SECRET      @"。。。。。。" //appsecret
    //商户号,填写商户对应参数
    #define MCH_ID          @"。。。。。。"
    //商户API密钥,填写相应参数
    #define PARTNER_ID      @"。。。。。。"
    //支付结果回调页面
    #define NOTIFY_URL      @"http://wxpay.weixin.qq.com/pub_v2/pay/notify.v2.php"
    //获取服务器端支付数据地址(商户自定义)
    #define SP_URL          @"http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php"
    
    

    修改下面的方法,后面有参数的一种是项目需要的

    //签名实例测试(demo中的)
    - ( NSMutableDictionary *)sendPay_demo;
    
    //签名实例(实际需要的)
    - ( NSMutableDictionary *)sendPay_demo:(NSString *)orderName price:(NSString *)price;
    
    

    payRequsestHandler.m

    - ( NSMutableDictionary *)sendPay_demo:(NSString *)orderName price:(NSString *)price{
    
        //订单标题,展示给用户
        NSString *order_name    = orderName;
        //订单金额,单位(分)
        NSString *order_price   = price;//1分钱测试
        
        //================================
        //预付单参数订单设置
        //================================
        srand( (unsigned)time(0) );
        NSString *noncestr  = [NSString stringWithFormat:@"%d", rand()];
        NSString *orderno   = [NSString stringWithFormat:@"%ld",time(0)];
        NSLog(@"%@",orderno);
        NSMutableDictionary *packageParams = [NSMutableDictionary dictionary];
        
        [packageParams setObject: appid             forKey:@"appid"];       //开放平台appid
        [packageParams setObject: mchid             forKey:@"mch_id"];      //商户号
        [packageParams setObject: @"APP-001"        forKey:@"device_info"]; //支付设备号或门店号
        [packageParams setObject: noncestr          forKey:@"nonce_str"];   //随机串
        [packageParams setObject: @"APP"            forKey:@"trade_type"];  //支付类型,固定为APP
        [packageParams setObject: order_name        forKey:@"body"];        //订单描述,展示给用户
        [packageParams setObject: NOTIFY_URL        forKey:@"notify_url"];  //支付结果异步通知
        [packageParams setObject: orderno           forKey:@"out_trade_no"];//商户订单号
        [packageParams setObject: @"196.168.1.1"    forKey:@"spbill_create_ip"];//发器支付的机器ip
        [packageParams setObject: order_price       forKey:@"total_fee"];       //订单金额,单位为分
        
        //获取prepayId(预支付交易会话标识)
        NSString *prePayid;
        prePayid            = [self sendPrepay:packageParams];
        
        if ( prePayid != nil) {
            //获取到prepayid后进行第二次签名
            
            NSString    *package, *time_stamp, *nonce_str;
            //设置支付参数
            time_t now;
            time(&now);
            time_stamp  = [NSString stringWithFormat:@"%ld", now];
            nonce_str   = [WXUtil md5:time_stamp];
            //重新按提交格式组包,微信客户端暂只支持package=Sign=WXPay格式,须考虑升级后支持携带package具体参数的情况
            //package       = [NSString stringWithFormat:@"Sign=%@",package];
            package         = @"Sign=WXPay";
            //第二次签名参数列表
            NSMutableDictionary *signParams = [NSMutableDictionary dictionary];
            [signParams setObject: appid        forKey:@"appid"];
            [signParams setObject: nonce_str    forKey:@"noncestr"];
            [signParams setObject: package      forKey:@"package"];
            [signParams setObject: mchid        forKey:@"partnerid"];
            [signParams setObject: time_stamp   forKey:@"timestamp"];
            [signParams setObject: prePayid     forKey:@"prepayid"];
            //[signParams setObject: @"MD5"       forKey:@"signType"];
            //生成签名
            NSString *sign  = [self createMd5Sign:signParams];
            
            //添加签名
            [signParams setObject: sign         forKey:@"sign"];
            
            [debugInfo appendFormat:@"第二步签名成功,sign=%@\n",sign];
            
            //返回参数列表
            return signParams;
            
        }else{
            [debugInfo appendFormat:@"获取prepayid失败!\n"];
        }
        return nil;
    }
    
    

    相关文章

      网友评论

      • 岁月如歌的季节:你好,我微信支付做好了,就是对未支付的订单进行再次支付时报个商户订单号重复的错误,发不起微信支付. 订单号还是用以前的未支付成功的那个,其他的都和以前的一样,接口还是https://api.mch.weixin.qq.com/pay/unifiedorder就是不行,不知道怎么做了求大神指点
      • CoderChou:@PP_Abner 看到了,第一步,我先将参数全部换掉,第二步,运行,真机测试,只会有一个确定按钮,楼主知道什么情况吗
        PPAbner:@菜鸟的尊严 没事!谢谢!
        CoderChou:@PP_Abner 谢谢你的回复,可能是demo的不完善我没有细看,从网上下载了其他的试了下,填了参数就可行了。你的博客给了我很大的帮助,good job!
        PPAbner:@菜鸟的尊严 你百度下微信支付只有一个确定按钮,看看!会有一大堆回复!一个原因,微信配置信息错误
      • CoderChou:@PP_Abner ,楼主,按照文档来第一步不是应该统一下单,获取prepay_id才对,为什么你没有这一样,好像和微信官方demo一样,很奇怪,求解惑。
        PPAbner:@菜鸟的尊严 用payRequsestHandler调用!我现在项目代码说明一切!
        #pragma mark - 微信支付
        - (void)weixinPay {
        //本实例只是演示签名过程, 请将该过程在商户服务器上实现
        BOOL isAnzhuagnwx = [WXApi isWXAppInstalled];
        if (isAnzhuagnwx) {
        //安装了微信
        BOOL isCurrenSupport = [WXApi isWXAppSupportApi];
        if (isCurrenSupport) {
        //当前手机安装的微信支持支付
        }else{
        [[MessShowView share]showWithMess:@"当前微信版本支持支付哟!"];
        return;
        }
        }else{
        //没有安装微信
        [[MessShowView share]showWithMess:@"亲还没有安装微信哟!"];
        return;
        }

        //创建支付签名对象
        payRequsestHandler *req = [[payRequsestHandler alloc] init];
        //初始化支付签名对象
        [req init:APP_ID mch_id:MCH_ID];
        //设置密钥
        [req setKey:PARTNER_ID];

        self.money = [NSString stringWithFormat:@"%.2f",[self.totalMoney floatValue]];
        //获取到实际调起微信支付的参数后,在app端调起支付
        NSMutableDictionary *dict = [req sendPay_demo:self.money jyID:self.jyID];

        if(dict == nil){
        //错误提示
        NSString *debug = [req getDebugifo];
        NSLog(@"%@\n\n",debug);
        }else{
        NSLog(@"%@\n\n",[req getDebugifo]);
        NSMutableString *stamp = [dict objectForKey:@"timestamp"];
        //调起微信支付
        PayReq* req = [[PayReq alloc] init];
        req.openID = [dict objectForKey:@"appid"];
        req.partnerId = [dict objectForKey:@"partnerid"];
        req.prepayId = [dict objectForKey:@"prepayid"];
        req.nonceStr = [dict objectForKey:@"noncestr"];
        req.timeStamp = stamp.intValue;
        req.package = [dict objectForKey:@"package"];
        req.sign = [dict objectForKey:@"sign"];
        [WXApi sendReq:req];
        }
        }
      • 316e78f2d43d:下载你的demo 支付界面调不起啦,提示信息:-服务器返回错误,未获取到json对象 这个是什么情况呢
        316e78f2d43d:@PP_Abner 嗯,我是用你的demo直接跑的,发现支付界面调用不起来,会不会跟APP_ID有关系
        PPAbner:@请叫我柯大大 http://www.jianshu.com/p/af8cbc9d51b0 你先看下这个对你有帮助没,我现在时间紧,没时间去看!!抱歉
        PPAbner:@请叫我柯大大 好久没看了,暂时不清楚,有空我看看。
      • f13aea0632ac:payRequsestHandler.m
        这个类是自己写的还是也可以下载过来直接改的!
        PPAbner:@mininana http://yun.baidu.com/s/1gf4mdMz 你看看
        f13aea0632ac:@PP_Abner 大神,没有找到这个类的文件,能不能分享一下呢! :heart_eyes:
        PPAbner:@mininana 不是自己写的
      • 6af1773f283f:。。老板 我收藏了你这份文章 需要授权吗?
        PPAbner:@带着梦想飞 不用。

      本文标题:iOS开发---微信支付

      本文链接:https://www.haomeiwen.com/subject/jththttx.html