iOS开发微信支付
第一步:
在微信-开放平台官网(https://open.weixin.qq.com) 申请AppID和AppSecret;
申请步骤:管理中心-->移动应用-->创建移动应用(图1.)-->通过审核后,把appKey和appSecret用.txt保存起来,平台后期不显示appSecret,查看需重置;
图1:
第二步:
在微信支付平台(https://pay.weixin.qq.com)下载SDK;
下载步骤:首页,开发文档(图2)-->app支付,查看文档(图3)-->SDK与DEMO下载(图4,图5.).
图2:
图3:
图4:
图5:
第三步:
集成SDK;
步骤:打开下载的SDK(图6.)-->拉进项目.
图6:
第四步:
根据开发文档(图7.),设置Schemes,配置AppDelegate;
步骤:
1.设置Schemes(URL Schemes,图8.);
2.在AppDelegate.m引入 #import "WXApi.h"头文件,
添加代理 @interface AppDelegate ()<WXApiDelegate>
然后实现以下方法,如下:
//方法1--
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
//设置微信的AppID,向微信注册.
[WXApi registerApp:@"wx820e05c62d04449c"];
return YES;
}
//方法2--
- (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation {
//6.3的新的API调用,是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
BOOLresult = [[UMSocialManagerdefaultManager]handleOpenURL:urlsourceApplication:sourceApplicationannotation:annotation];
if(!result) {
// 其他如支付等SDK的回调
if([url.hostisEqualToString:@"safepay"]) {
//跳转支付宝钱包进行支付,处理支付结果
// [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
// NSLog(@"result = %@",resultDic);
// }];
}elseif([url.hostisEqualToString:@"pay"]) {
// 处理微信的支付结果
[WXApihandleOpenURL:urldelegate:self];
}
}
returnresult;
}
//方法3--
- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url {
BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
if(!result) {
// 其他如支付等SDK的回调
}
returnresult;
}
//方法4--
- (BOOL)application:(UIApplication*)app openURL:(NSURL*)url options:(NSDictionary *)options {
//6.3的新的API调用,是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
BOOLresult = [[UMSocialManagerdefaultManager] handleOpenURL:urloptions:options];
if(!result) {
// 其他如支付等SDK的回调
if([url.hostisEqualToString:@"safepay"]) {
//跳转支付宝钱包进行支付,处理支付结果
// [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
// NSLog(@"result = %@",resultDic);
// }];
}elseif([url.hostisEqualToString:@"pay"]) {
// 处理微信的支付结果
[WXApihandleOpenURL:urldelegate:self];
}
}
returnresult;
}
//方法5--
//微信支付后点击返回商户,结果回调方法.(注:如果支付成功则去后台查询支付结果再展示用户实际支付结果。注意 一定不能以客户端返回作为用户支付的结果,应以服务器端的接收的支付通知或查询API返回的结果为准。)
-(void) onResp:(BaseResp*)resp {
//启动微信支付的response
NSString*payResoult = [NSStringstringWithFormat:@"errcode:%d", resp.errCode];
if([resp isKindOfClass:[PayResp class]]){
//支付返回结果,实际支付结果需要去微信服务器端查询
switch(resp.errCode) {
case0:
payResoult =@"支付结果:成功!";
break;
case-1:
payResoult =@"支付结果:失败!";
break;
case-2:
payResoult =@"用户已经退出支付!";
break;
default:
payResoult = [NSStringstringWithFormat:@"支付结果:失败!retcode = %d, retstr = %@", resp.errCode,resp.errStr];
break;
}
}
}
图7:
图8:
第五步:
实现支付页面方法;
1.
// 判断手机有没有微信
if ([WXApi isWXAppInstalled]) {
// wechatButton.hidden = NO;
NSLog(@"you Wechat");
[selfWechatPay];
}else{
// wechatButton.hidden = YES;
NSLog(@"mei Wechat");
}
2.
#pragma mark - 微信统一下单接口
- (void) req3_WechatPay {
//Uid
NSUserDefaults *appUserDefaults = [NSUserDefaults standardUserDefaults];
NSString*str_Uid = [appUserDefaultsobjectForKey:@"Uid"];
//金额
NSString*str_total_fee =@"1";
//用户端实际IP
NSString*str_spbill_create_ip = [selfgetIPAddress:YES];
//商品描述
NSString*str_Subject =@"xxxbbb";
NSString *urlStr = [NSString stringWithFormat:@"%@WechatPayment/pay?user_id=%@&total_fee=%@&spbill_create_ip=%@&Subject=%@",API_IP,str_Uid,str_total_fee,str_spbill_create_ip,str_Subject];
[NetworkRequestManager requestWithType:GET urlString:urlStr headerDic:nil ParDic:nil finish:^(NSData *data) {
NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"-www1-> %@ ",dataDic);
_appid= [dataDicvalueForKey:@"appid"];
_partnerid= [dataDicvalueForKey:@"partnerid"];
_prepayid= [dataDicvalueForKey:@"prepayid"];
_package= [dataDicvalueForKey:@"package"];
_noncestr= [dataDicvalueForKey:@"noncestr"];
_timestamp= [dataDicvalueForKey:@"timestamp"];
_sign= [dataDicvalueForKey:@"sign"];
[self performSelectorOnMainThread:@selector(blackToMain) withObject:nil waitUntilDone:YES];
}error:^(NSError*error) {
}];
}
3.
#pragma mark 微信支付方法
- (void)WechatPay {
//需要创建这个支付对象
PayReq*req = [[PayReqalloc]init];
//由用户微信号和AppID组成的唯一标识,用于校验微信用户
req.openID = _appid;
// 商家id,在注册的时候给的
req.partnerId = _partnerid;
// 预支付订单这个是后台跟微信服务器交互后,微信服务器传给你们服务器的,你们服务器再传给你
req.prepayId = _prepayid;
// 根据财付通文档填写的数据和签名
req.package = _package;
// 随机编码,为了防止重复的,在后台生成
req.nonceStr = _noncestr;
// 这个是时间戳,也是在后台生成的,为了验证支付的
NSString* stamp =_timestamp;
req.timeStamp= stamp.intValue;
// 这个签名也是后台做的
req.sign=_sign;
//发送请求到微信,等待微信返回onResp
[WXApisendReq:req];
}
4.
#pragma mark - 获取 手机IP地址
- (NSString*)getIPAddress:(BOOL)preferIPv4 {
NSArray*searchArray = preferIPv4 ?
@[ /*IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6,*/ IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
@[ /*IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4,*/ IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
NSDictionary*addresses = [selfgetIPAddresses];
// NSLog(@"addresses: %@", addresses);
__blockNSString*address;
[searchArrayenumerateObjectsUsingBlock:^(NSString*key,NSUIntegeridx,BOOL*stop){
address = addresses[key];
if(address) *stop =YES;
}];
returnaddress ? address :@"0.0.0.0";
}
- (NSDictionary*)getIPAddresses {
NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
// retrieve the current interfaces - returns 0 on success
structifaddrs*interfaces;
if(!getifaddrs(&interfaces)) {
// Loop through linked list of interfaces
structifaddrs*interface;
for(interface=interfaces; interface; interface=interface->ifa_next) {
if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
continue; // deeply nested code harder to read
}
conststructsockaddr_in*addr = (conststructsockaddr_in*)interface->ifa_addr;
char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
if(addr && (addr->sin_family==AF_INET|| addr->sin_family==AF_INET6)) {
NSString*name = [NSStringstringWithUTF8String:interface->ifa_name];
NSString*type;
if(addr->sin_family==AF_INET) {
if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf,INET_ADDRSTRLEN)) {
type =IP_ADDR_IPv4;
}
}else{
conststructsockaddr_in6*addr6 = (conststructsockaddr_in6*)interface->ifa_addr;
if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf,INET6_ADDRSTRLEN)) {
type =IP_ADDR_IPv6;
}
}
if(type) {
NSString*key = [NSStringstringWithFormat:@"%@/%@", name, type];
addresses[key] = [NSStringstringWithUTF8String:addrBuf];
}
}
}
// Free memory
freeifaddrs(interfaces);
}
return[addressescount] ? addresses :nil;
}
完成.......(可以试试微信支付了.)