iOS集成微信支付

news/2024/12/5 7:07:05/

一、微信支付,首先利用CocoaPods导入微信SDK

pod 'WechatOpenSDK'

二、创建微信支付管理类 WechatManager

//  WechatManager.h
#import <Foundation/Foundation.h>
#import <WXApi.h>@interface WechatManager : NSObject+ (id)shareInstance;+ (BOOL)handleOpenUrl:(NSURL *)url;+ (void)hangleWechatPayWith:(PayReq *)req;@end
// WechatManager.m
#import "WechatManager.h"@interface WechatManager()<WXApiDelegate>@end@implementation WechatManager+ (id)shareInstance {static WechatManager *weChatPayInstance = nil;static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{weChatPayInstance = [[WechatManager alloc] init];});return weChatPayInstance;
}+ (BOOL)handleOpenUrl:(NSURL *)url {return [WXApi handleOpenURL:url delegate:[WechatManager shareInstance]];
}+ (void)hangleWechatPayWith:(PayReq *)req {[WXApi sendReq:req completion:^(BOOL success) {if (success) {NSLog(@"微信支付成功");} else {NSLog(@"微信支付异常");}}];
}#pragma mark - 微信支付回调- (void)onResp:(BaseResp *)resp {if ([resp isKindOfClass:[PayResp class]]) {/*enum  WXErrCode {WXSuccess           = 0,    < 成功WXErrCodeCommon     = -1,  < 普通错误类型WXErrCodeUserCancel = -2,   < 用户点击取消并返回WXErrCodeSentFail   = -3,   < 发送失败WXErrCodeAuthDeny   = -4,   < 授权失败WXErrCodeUnsupport  = -5,   < 微信不支持};*/PayResp *response = (PayResp*)resp;switch (response.errCode) {case WXSuccess: {NSLog(@"微信回调支付成功");[[NSNotificationCenter defaultCenter] postNotificationName:UserNotificationAlipayOrWechatSuccessobject:niluserInfo:nil];break;}case WXErrCodeCommon: {NSLog(@"微信回调支付异常");break;}case WXErrCodeUserCancel: {NSLog(@"微信回调用户取消支付");break;}case WXErrCodeSentFail: {NSLog(@"微信回调发送支付信息失败");break;}case WXErrCodeAuthDeny: {NSLog(@"微信回调授权失败");break;}case WXErrCodeUnsupport: {NSLog(@"微信回调微信版本暂不支持");break;}default: {break;}}}
}
@end

三、在AppDelegate里面注册AppKey

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];self.window.backgroundColor = [UIColor whiteColor];LoginCodeViewController *mainViewController = [[LoginCodeViewController alloc] init];self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:mainViewController];[self.window makeKeyAndVisible];// 微信支付注册// WeiXinPayKey:APP在微信开发者网站上申请的Key。WeiXinLinks:微信开发者Universal Link(这个有点麻烦,后面会详细说明,先把集成过程讲完)。BOOL isSuccess = [WXApi registerApp:WeiXinPayKey universalLink:WeiXinLinks];if (isSuccess) {NSLog(@"微信支付API注册成功");} else {NSLog(@"微信支付API注册失败");}    return YES;
}

四、补充说明:WeiXinPayKey 为APP在微信开发者网站上申请的Key。WeiXinLinks 是微信开发者的Universal Link(通用链接)

1.该链接一般为以https开头的公司域名;

2.开发者中心配置AppID支持Associated Domains:

 

3.Xcode工程配置

在工程 Capabilities 里面打开Associated Domains开关,配置内容为以下格式:

applinks:www.baidu.com

 

 在工程 Info 里面新建 LSApplicationQueriesSchemes 数组,配置内容为以下格式:


 

 4.配置指定文件,这个文件名必须为 apple-app-site-association 切记没有后缀名,文件内容如下:

{"applinks": {"apps": [],"details": [{"appID": "9JA89QQLNQ.com.apple.wwdc","paths": [ "/wwdc/news/", "/videos/wwdc/2015/*"]},{"appID": "Xcode项目的Bundle Identifier","paths": [ "*" ]}]}
}

5.上传上一步新建的文件到域名根目录下:

上传该文件到你的域名所对应的根目录或者 .well-known 目录下,这是为了苹果能获取到你上传的文件。

五、AppDelegate 处理支付SDK回调

#pragma mark - 微信支付配置返回 url处理方法- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {if ([url.scheme containsString:WeiXinPayKey]) {if ([url.absoluteString containsString:[NSString stringWithFormat:@"%@://pay", WeiXinPayKey]]) {return [WechatManager handleOpenUrl:url];} else if ([url.absoluteString containsString:[NSString stringWithFormat:@"%@://oauth?", WeiXinPayKey]]) {return [WechatManager handleOpenUrl:url];}}return YES;
}
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {NSURL *continueURL = userActivity.webpageURL;NSString *relativePath = continueURL.relativePath;if ([relativePath containsString:WeiXinPayKey] && [relativePath containsString:@"pay"]) {return [WXApi handleOpenUniversalLink:userActivity delegate:[WechatManager shareInstance]];} else if ([relativePath containsString:[NSString stringWithFormat:@"%@", WeiXinPayKey]]) {return [WXApi handleOpenUniversalLink:userActivity delegate:[WechatShareManager shareInstance]];}return YES;
}

六、URL Types 配置。这个schemes就是微信开发者平台注册的AppKey

 

七、调用支付接口,处理微信支付后的通知事件

1.在支付界面控制器,添加通知

- (void)viewDidLoad {[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(ailyPayOrWechatSuccessAction)name:UserNotificationAlipayOrWechatSuccessobject:nil];[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(ailyPayOrWechatFailAction)name:UserNotificationAlipayOrWechatFailobject:nil];
}

2.实现支付结果通知回调方法,然后对通知的函数进行处理

#pragma mark - 利用通知处理支付结果// 支付成功
- (void)ailyPayOrWechatSuccessAction {// 处理支付结果NSLog(@"处理支付成功结果");
}// 支付失败
- (void)ailyPayOrWechatFailAction {NSLog(@"处理支付失败结果");}- (void)dealloc {[[NSNotificationCenter defaultCenter] removeObserver:self];
}

3.创建订单,拿到后台返回的信息,然后调用微信支付

#pragma mark - 确认支付- (void)userBuyGoodsAction {//  @param address_id 地址ID//  @param count 商品数量//  @param refer_id 商品ID//  @param refer_type 商品类型 0课程 1直播//  @param type 支付类型 0微信 1支付宝//  @param coupon_id 优惠券ID//  @param handle 返回签名int type = self.isWeixinPay ? 0 : 1;[HttpManager createOrderWithAddressId:self.locationModel.location_id count:@(1) refer_id:self.lessonModel.ID refer_type:@(0) type:@(type) coupon_id:nil andHandle:^(NSString *error, NSDictionary *result) {if (error == nil) {NSLog(@"微信支付创建订单回执-%@",result);NSDictionary *dict = [self jsonToDictionary:result[@"data"][@"data"]];PayReq *req   = [[PayReq alloc] init];req.nonceStr  = [dict objectForKey:@"noncestr"];req.timeStamp = [[dict objectForKey:@"timestamp"] intValue];req.package   = [dict objectForKey:@"package"];req.partnerId = [dict objectForKey:@"partnerid"];req.prepayId  = [dict objectForKey:@"prepayid"];req.sign      = [dict objectForKey:@"sign"];[WechatManager hangleWechatPayWith:req];} else {NSLog(@"订单创建失败,失败原因-%@",result);}}];
}

http://www.ppmy.cn/news/556223.html

相关文章

iOS6和iOS7环境下微信登录未显示问题微信IOS的SDK:isWXAppInstalled总是返回NO和nil...

iOS6和iOS7环境下微信登录未显示问题&微信IOS的SDK&#xff1a;isWXAppInstalled总是返回NO和nil 一、问题描述&#xff1a; iOS6和iOS7 环境下未显示微信登录界面&#xff0c;在其他环境下显示正常。 二、问题解决&#xff1a; iOS6和7未出现微信登录按钮, 原因 [WXApi is…

微信iOS7.0.9更新!除了朋友圈可以评论表情包,还有这些你可能不知道的功能!

微信又㕛叒叕更新了~这次是iOS更新~ 本次更新版本号为7.0.9&#xff0c;官方更新日志只是简单提及“发消息时&#xff0c;可引用之前的内容”&#xff0c;并未说明其他的更新&#xff01; 接下来&#xff0c;我们一起看看有哪些重大更新&#xff1f;&#xff01; 一、引用功能…

7-59 哈夫曼编码译码

编写一个哈夫曼编码译码程序。 按词频从小到大的顺序给出各个字符&#xff08;不超过30个&#xff09;的词频&#xff0c;根据词频构造哈夫曼树&#xff0c;给出每个字符的哈夫曼编码&#xff0c;并对给出的语句进行译码。 为确保构建的哈夫曼树唯一&#xff0c;本题做如下限…

团体程序设计天梯赛-练习集L2篇②

&#x1f680;欢迎来到本文&#x1f680; &#x1f349;个人简介&#xff1a;Hello大家好呀&#xff0c;我是陈童学&#xff0c;一个与你一样正在慢慢前行的普通人。 &#x1f3c0;个人主页&#xff1a;陈童学哦CSDN &#x1f4a1;所属专栏&#xff1a;PTA &#x1f381;希望各…

【C++】AVL树的插入实现

目录 AVL树的概念AVL树节点的定义AVL树的插入AVL树的旋转左单旋(parent->_bf 2 && cur->_bf 1)a,b,c当高度为0a,b,c当高度为1a,b,c当高度为2a,b,c当高度为...... 右单旋(parent->_bf -2 && cur->_bf -1)a,b,c当高度为0a,b,c当高度为1a,b,c当高…

华为路由器eNSPAR1220路由器Ethernet口不能添加IP地址

华为路由器eNSPAR1220路由器Ethernet口不能添加IP地址 [R1-Ethernet0/0/0]ip add tab补全不能用&#xff0c;那就不要用Ethernet口&#xff0c;换GigabitEthernet [R1-GigabitEthernet0/0/0]ip address 10.0.12.1 24 转载于:https://blog.51cto.com/alibaby/1920390

路由器连上网线不能访问网络

怀疑是对Mac地址做了限制&#xff0c;我们把可以正常联网的路由器的MAC复制一下&#xff0c;然后在路由器MAC地址克隆粘贴一下。搞定

通过墙上网口连接路由器无法上网问题

大家好&#xff0c;最近遇到一个在组网上面的问题&#xff0c;希望大家能够给予帮助: 我在客厅有一个路由器&#xff0c;然后通过网线将网连至卧室的墙上网口&#xff0c;我希望通过墙上网口再连一个路由器&#xff0c;这样的话卧室的信号就会比较好&#xff0c;但是怎么设置都…