微信

作者: edison0428 | 来源:发表于2018-03-28 18:15 被阅读50次

    微信支付demo

    微信支付demo下载地址

    但是现在下来,运行报错


    7A6E5B4D93DEE06188BCDC4F60BBBD5C.jpg

    解决方案:添加库 CFNetwork.framework libc++.tbd

    然后运行,进入app就奔溃

    Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM enqueue:]: unrecognized selector sent to instance 0x60000024ef40'
    

    在buddle Seeting 里面的Other Linker Flags 中添加-ObjC就可以了。

    但是点击发起微信支付返回的是支付失败,不管它了,主要看代码就行

    微信支付业务流程

    chapter8_3_1.png

    商户系统和微信支付系统主要交互说明:

    步骤1:用户在商户APP中选择商品,提交订单,选择微信支付。

    步骤2:商户后台收到用户支付单,调用微信支付统一下单接口。参见【统一下单API】。

    步骤3:统一下单接口返回正常的prepay_id,再按签名规范重新生成签名后,将数据传输给APP。参与签名的字段名为appid,partnerid,prepayid,noncestr,timestamp,package。注意:package的值格式为Sign=WXPay

    步骤4:商户APP调起微信支付。api参见本章节【app端开发步骤说明

    步骤5:商户后台接收支付通知。api参见【支付结果通知API

    步骤6:商户后台查询支付结果。,api参见【查询订单API

    开始操作

    前期准备
    1 pod 接入
    pod 'WechatOpenSDK'
    

    sdk里包含了微信登陆,微信分享,微信支付

    2 设置URL type 添加 URL schme
    image.png
    3 添加白名单
    image.png
    4重写AppDelegate 的handleOpenURL 和openURL方法
    image.png
    // NOTE: 9.0以前使用新API接口
    - (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) {
                NSLog(@"result = %@",resultDic);
                [self.window makeToast:@"订单支付成功"];
                [self updateVIPAccess];
            }];
            return YES;
            
        }else if ([url.host isEqualToString:@"pay"] || [url.host isEqualToString:@"oauth"] || [sourceApplication isEqualToString:@"com.apple.MobileSMS"]) {
            //微信支付,登陆
            return [WXApi handleOpenURL:url delegate:[EYWXLogin sharedManager]];
        }else if ([url.host isEqualToString:@"platformId=wechat"]) {
            //微信分享
            return [WXApi handleOpenURL:url delegate:[EYWXLogin sharedManager]];
        }
        else if([url.host isEqualToString:@"qzapp"]){
            //QQ登录
            return [TencentOAuth HandleOpenURL:url];
        }else if ([url.host isEqualToString:@"response_from_qq"]) {
            //QQ分享
            [QQApiInterface handleOpenURL:url delegate:self];
            return [TencentOAuth HandleOpenURL:url];
        }
        return YES;
    }
    
    // NOTE: 9.0以后使用新API接口
    - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
    {
        if ([url.host isEqualToString:@"safepay"]) {
            //跳转支付宝钱包进行支付,处理支付结果
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                
                if ([resultDic[@"resultStatus"] intValue] == 9000) {
                    NSLog(@"%@",resultDic);
                    [self.window makeToast:@"订单支付成功"];
                    [self updateVIPAccess];
                }else{
                    NSLog(@"%@",resultDic);
                    [self.window makeToast:resultDic[@"memo"]];
                }
            }];
            
            return YES;
        }else if ([url.host isEqualToString:@"pay"] || [url.host isEqualToString:@"oauth"] || [[options objectForKey:UIApplicationOpenURLOptionsSourceApplicationKey] isEqualToString:@"com.apple.MobileSMS"]) {
            
            //微信支付,登陆
            return [WXApi handleOpenURL:url delegate:[EYWXLogin sharedManager]];
        }else if ([url.host isEqualToString:@"platformId=wechat"]) {
            //微信分享
            return [WXApi handleOpenURL:url delegate:[EYWXLogin sharedManager]];
        }
        else if([url.host isEqualToString:@"qzapp"]){
            //QQ登录
            return [TencentOAuth HandleOpenURL:url];
        }else if ([url.host isEqualToString:@"response_from_qq"]) {
            //QQ分享
            [QQApiInterface handleOpenURL:url delegate:self];
            return [TencentOAuth HandleOpenURL:url];
        }
        return YES;
    }
    
    - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
        if ([url.host isEqualToString:@"response_from_qq"]) {
            //QQ分享
            [QQApiInterface handleOpenURL:url delegate:self];
            return [TencentOAuth HandleOpenURL:url];
        }else if([url.host isEqualToString:@"qzapp"]){
            //QQ登录
            return [TencentOAuth HandleOpenURL:url];
        }
        else {
            //return NO;
            return [WXApi handleOpenURL:url delegate:[EYWXLogin sharedManager]];
        }
    }
    

    功能代码

    1注册微信
    BOOL res = [WXApi registerApp:kWXAppConfigWeChatAppId];
    
    2实现WXApiDelegate协议两个方法

    -(void) onReq:(BaseReq*)req
    -(void) onResp:(BaseResp*)resp

    如果你的程序要发消息给微信,那么需要调用WXApi里的sendReq函数

    2先实现上述回调方法,包含微信登陆 微信分享 微信支付所有功能的回调
    #pragma mark - WXApiDelegate
    
    -(void) onReq:(BaseReq*)req{
        
        
    }
    
    -(void) onResp:(BaseResp*)resp{
        
        if([resp isKindOfClass:[SendAuthResp class]]) {
            SendAuthResp* authResp = (SendAuthResp*)resp;
            /* Prevent Cross Site Request Forgery */
            NSLog(@"autoResp state:%@  errcode:%d",authResp.state,resp.errCode);
            
            switch (resp.errCode) {
                case WXSuccess:{
                    NSLog(@"RESP:code:%@,state:%@\n", authResp.code, authResp.state);
    
                    !_resultBlock?:_resultBlock(WXLoginResultTypeSuccess);
                    NSLog(@"微信登陆成功");
    #pragma mark 可获取用户信息 ,但是secret我拿不到 官网文档有详细的介绍
                   
                    }
                    break;
                case WXErrCodeAuthDeny:
    
                    !_resultBlock?:_resultBlock(WXLoginResultTypeAuthDeny);
                    NSLog(@"微信登录授权失败");
                    break;
                case WXErrCodeUserCancel:
                    NSLog(@"微信登录用户取消");
                    !_resultBlock?:_resultBlock(WXLoginResultTypeCancel);
    
                default:
                    break;
            }
        }
        else if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
            
            NSLog(@"分享后 --- %d %@ %d", resp.errCode, resp.errStr, resp.type);
            if(resp.errCode==0){  // 分享成功
                NSLog(@"分享成功");
                //[[NSNotificationCenter defaultCenter] postNotificationName:@"thirdShare" object:nil userInfo:@{@"isSuccess":@"1"}];
            }else {
                NSLog(@"分享失败");
                //[[NSNotificationCenter defaultCenter] postNotificationName:@"thirdShare" object:nil userInfo:@{@"isSuccess":@"0"}];
            }
        }
        else if([resp isKindOfClass:[PayResp class]]){
            
            switch (resp.errCode) {
                    case WXSuccess:
                    //当这里收到支付成功时,一定要请求服务器查询是否支付成功,不要以客户端的返回作为结果判定
                    
                    NSLog(@"支付成功");
                    !_payResultBlock?:_payResultBlock(WXPayResultTypeSuccess);
                    break;
                    
                    case WXErrCodeUserCancel:
                    NSLog(@"支付前用户手动取消");
                    !_payResultBlock?:_payResultBlock(WXPayResultTypeCancel);
                    break;
                    
            
                    
                default:
                    !_payResultBlock?:_payResultBlock(WXPayResultTypeFailure);
                    break;
            }
        }
    }
    
    微信支付
    /**
     微信支付
     
     @param params 参数 商品id 商品数量
     */
    -(void)weChatPay:(NSDictionary *)params result:(WXPayResultBlock)payResBlock{
        
        
        _payResultBlock = payResBlock;
        if (![WXApi isWXAppInstalled]) {
            !_payResultBlock?:_payResultBlock(WXPayResultTypeUnstalled);
            return;
        }
        //第一步 用户已经选好商品并且选择的是微信支付
        //第二部 app将用户选择的信息发送给后台 后台收到用户支付单,调用微信支付统一下单接口
        [ILNetworking postEncryptAndDecryptResponse:@"WeChatPayOrderURL" params:params success:^(ILApiResult *apiResult) {
            //第三部 后台统一下单接口返回正常的prepay_id  按照签名规范重新生成签名 ,将数据传输给app
            NSLog(@"后台统一下单后返回的信息:%@",(NSDictionary *)apiResult.result);
            if(apiResult.isSuccess){
                if(apiResult.result){
                    NSDictionary * result = (NSDictionary *)apiResult.result;
                    PayReq * req =[[PayReq alloc] init];
                    req.openID = [result objectForKey:@"appid"];
                    req.nonceStr = [result objectForKey:@"noncestr"];
                    req.package = [result objectForKey:@"package"];
                    req.partnerId = [result objectForKey:@"partnerid"];
                    req.prepayId = [result objectForKey:@"prepayid"];
                    req.sign = [result objectForKey:@"sign"];
                    req.timeStamp = [[result objectForKey:@"timestamp"] intValue];
                    [WXApi sendReq:req];
                }
                else{
                    NSLog(@"获取订单失败");
                    !_payResultBlock?:_payResultBlock(WXPayResultTypeFailure);
                }
            }
            else{
                NSLog(@"获取订单错误信息;%@",apiResult.msg);
                !_payResultBlock?:_payResultBlock(WXPayResultTypeFailure);
            }
            
        } failure:^(NSError *error) {
            NSLog(@"微信支付网络出现问题");
            !_payResultBlock?:_payResultBlock(WXPayResultTypeFailure);
        }];
    }
    
    
    微信登陆
    /**
     微信登陆
     
     @param viewController 登陆界面的控制器
     @param resultBlock 登陆结果的回调
     */
    -(void)loginWithViewController:(UIViewController*)viewController  resultCallBack:(WXLoginResultBlock) resultBlock{
        
        _resultBlock = resultBlock;
        if (![WXApi isWXAppInstalled]) {
            !_resultBlock?:_resultBlock(WXLoginResultTypeUnstalled);
            return;
        }
        SendAuthReq *req = [[SendAuthReq alloc] init];
        req.scope = wxScope;
        req.state = wxState;
        
        
        [WXApi sendAuthReq:req viewController:viewController delegate:self];
       
    }
    
    微信分享 没有封装 可分享至好友 朋友圈 收藏
    /**
     分享纯文字
    
     @param textString 文字
     */
    +(void)wxSharetextMessage:(NSString*)textString{
        
        SendMessageToWXReq * req = [[SendMessageToWXReq alloc] init];
        req.text = textString;
        req.bText = YES;
        req.scene = WXSceneSession;
        [WXApi sendReq:req];
    }
    
    
    
    
    /**
     分享图片
     
     @param image 图片
     @param thumbImage 缩略图
     */
    +(void)wxShareImageMessage:(UIImage *)image thumbImage:(UIImage *)thumbImage{
        WXMediaMessage *message = [WXMediaMessage message];
        // 设置消息缩略图的方法
        [message setThumbImage:thumbImage];
        // 多媒体消息中包含的图片数据对象
        WXImageObject *imageObject = [WXImageObject object];
        
        //UIImage *image = [UIImage imageNamed:@"要分享的图片名"];
        
        // 图片真实数据内容
        
        NSData *data = UIImagePNGRepresentation(image);
        imageObject.imageData = data;
        // 多媒体数据对象,可以为WXImageObject,WXMusicObject,WXVideoObject,WXWebpageObject等。
        message.mediaObject = imageObject;
        
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        req.scene = WXSceneSession;// 分享到朋友圈
        [WXApi sendReq:req];
    
    }
    
    
    
    /**
     分享音乐
     
     @param musicUrl 音乐的路径
     @param thumbImage 缩略图
     */
    +(void)wxShareMusicMessage:(NSString *)musicUrl thumbImage:(UIImage *)thumbImage{
        
        SendMessageToWXReq *req1 = [[SendMessageToWXReq alloc]init];
        
        // 是否是文档
        req1.bText =  NO;
        
        //    WXSceneSession  = 0,        /**< 聊天界面    */
        //    WXSceneTimeline = 1,        /**< 朋友圈      */
        //    WXSceneFavorite = 2,
        
        
        req1.scene = WXSceneSession;
        
        //创建分享内容对象
        WXMediaMessage *urlMessage = [WXMediaMessage message];
        urlMessage.title = @"分享一首歌";//分享标题
        urlMessage.description = @"一首小歌,放松一下";//分享描述
        
        [urlMessage setThumbImage:thumbImage];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
        
        //创建多媒体对象
        
         NSString *kLinkURL = musicUrl;//@"http://bd.kuwo.cn/yinyue/718535?from=baidu";
        
        WXMusicObject *music = [WXMusicObject object];
        music.musicUrl = kLinkURL;//分享链接
        
        //完成发送对象实例
        urlMessage.mediaObject = music;
        req1.message = urlMessage;
        
        //发送分享信息
        [WXApi sendReq:req1];
        
        
    }
    
    
    
    /**
     分享视频
    
     @param videoUrl 视频的路径
     @param thumbImage 缩略图
     */
    +(void)wxShareVideoMessage:(NSString *)videoUrl thumbImage:(UIImage *)thumbImage{
        
        SendMessageToWXReq *req1 = [[SendMessageToWXReq alloc]init];
        
        // 是否是文档
        req1.bText =  NO;
        
        //    WXSceneSession  = 0,        /**< 聊天界面    */
        //    WXSceneTimeline = 1,        /**< 朋友圈      */
        //    WXSceneFavorite = 2,
        
        
        req1.scene = 0;
        
        //创建分享内容对象
        WXMediaMessage *urlMessage = [WXMediaMessage message];
        urlMessage.title = @"分享视频";//分享标题
        urlMessage.description = @"小视频";//分享描述
        
        [urlMessage setThumbImage:thumbImage];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
        
        //创建多媒体对象
        
        NSString *kLinkURL = videoUrl;
        
        WXVideoObject *video = [WXVideoObject object];
        video.videoUrl = kLinkURL;//分享链接
        
        //完成发送对象实例
        urlMessage.mediaObject = video;
        req1.message = urlMessage;
        
        //发送分享信息
        [WXApi sendReq:req1];
        
        
    }
    
    
    
    /**
     分享链接
    
     @param linkUrl 链接
     @param thumbImage 缩略图
     */
    +(void)wxShareLinkMessage:(NSString *)linkUrl thumbImage:(UIImage *)thumbImage{
        
        NSString *kLinkURL = linkUrl;//
        
        static NSString *kLinkTitle = @"我简书的主页";
        static NSString *kLinkDescription = @"里面是一些自己总结的小知识点";
        
        SendMessageToWXReq *req1 = [[SendMessageToWXReq alloc]init];
        
        // 是否是文档
        req1.bText =  NO;
        
        //    WXSceneSession  = 0,        /**< 聊天界面    */
        //    WXSceneTimeline = 1,        /**< 朋友圈      */
        //    WXSceneFavorite = 2,
        
        
        req1.scene = WXSceneSession;
        
        //创建分享内容对象
        WXMediaMessage *urlMessage = [WXMediaMessage message];
        urlMessage.title = kLinkTitle;//分享标题
        urlMessage.description = kLinkDescription;//分享描述
        [urlMessage setThumbImage:thumbImage];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
        
        //创建多媒体对象
        WXWebpageObject *webObj = [WXWebpageObject object];
        webObj.webpageUrl = kLinkURL;//分享链接
        
        //完成发送对象实例
        urlMessage.mediaObject = webObj;
        req1.message = urlMessage;
        
        //发送分享信息
        [WXApi sendReq:req1];
        
       
    }
    
    

    相关文章

      网友评论

          本文标题:微信

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