微信支付:https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_2_4.shtml
支付宝支付:https://opendocs.alipay.com/open/203/105288
#import "LYPayRequest.h"
#import <AFNetworking.h>
@implementation LYPayRequest
//商城订单请求加密字符串
+(void)postShoppayrequestWithUrl:(NSString *)url
params:(NSDictionary *)params
successBlock:(SuccessBlock)successBlock
failureBlock:(FailureBlock)failureBlock{
AFHTTPSessionManager *manager = [AFHTTPSessionManagermanager];
// //待超时时间
// NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
// config.timeoutIntervalForRequest = 5.0;
// AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:config];
manager.securityPolicy = [AFSecurityPolicypolicyWithPinningMode:AFSSLPinningModeNone];//安全策略
manager.securityPolicy.allowInvalidCertificates =YES;
manager.responseSerializer.acceptableContentTypes=[NSSetsetWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"text/xml",@"text/plain; charset=utf-8",nil];
manager.responseSerializer = [AFHTTPResponseSerializerserializer];
manager.requestSerializer=[AFHTTPRequestSerializerserializer];
//***************
//构建公共请求参数
if (!params) {
params = [NSMutableDictionarydictionary];
}else{
params = [NSMutableDictionarydictionaryWithDictionary:params];
}
if([SPMobileApplicationsharedInstance].isLogined)//登录状态
{
SPUser *loginUser = [SPMobileApplicationsharedInstance].loginUser;
[params setValue:loginUser.userIDforKey:@"user_id"];//用户ID
NSLog(@"--token---%@",loginUser.token);
// if (loginUser.token) {
// [params setValue:loginUser.token forKey:@"token"];
// NSLog(@"-最终参数parama-001-%@-",params);
// }
}
// if ([[SPMobileApplication sharedInstance] getPhoneDeviceID]) {
// [params setValue:[[SPMobileApplication sharedInstance] getPhoneDeviceID] forKey:@"unique_id"];
// // NSLog(@"-最终参数没签名前--%@",params);
// }
[manager POST:urlparameters:paramsprogress:^(NSProgress *_Nonnull uploadProgress) {
NSLog(@"请求商城签名字符串");
// 上传图片,以文件流的格式
} success:^(NSURLSessionDataTask *_Nonnull task,id _Nullable responseObject) {
NSDictionary *dict=[NSJSONSerializationJSONObjectWithData:responseObjectoptions:NSJSONReadingAllowFragmentserror:nil];
NSLog(@"-请求商城签名字符串-%@",dict);
NSInteger status=[dict[@"status"]integerValue];
NSLog(@"status请求商城签名字符串%tu",status);
if ((status ==RESPONSE_CODE_TOKENN_LOST || status ==RESPONSE_CODE_TOKENN_INALIDE || status ==RESPONSE_CODE_TOKENN_EXPIRE) ) {
//发送通知//token过期,失效通知
[[NSNotificationCenterdefaultCenter]postNotificationName:NotificationTokenExpireobject:nil];
}
if(dict){
NSString *result=dict[@"result"];
successBlock(task,result);
}
} failure:^(NSURLSessionDataTask *_Nullable task,NSError * _Nonnull error) {
NSLog(@"请求商城签名字符串----%@",error);
}];
}
服务器返回的数据模型:
#import <Foundation/Foundation.h>
@interface SPWxPayInfo : NSObject
/*"appid": null,
"partnerid": null,
"prepayid": null,
"noncestr": null,
"package": "Sign=WXPay",
"timestamp": 1499847401,
"sign": "D400F4B33525F5F8C3BC9D3EB99EB45E"
*/
@property(nonatomic ,copy)NSString* appid;
@property(nonatomic ,copy)NSString* partnerid;
@property(nonatomic ,copy)NSString* prepayid;
@property(nonatomic ,copy)NSString* noncestr;
@property(nonatomic ,copy)NSString* timestamp;
@property(nonatomic ,copy)NSString* packageValue ;
@property(nonatomic ,copy)NSString* sign;
@property(nonatomic ,copy)NSString* extData;
@end
========
#import "SPWxPayInfo.h"
@implementation SPWxPayInfo
MJCodingImplementation
+(NSDictionary*)replacedKeyFromPropertyName{
return @{@"packageValue":@"package"};
}
@end
*****************
#import <AlipaySDK/AlipaySDK.h>
#import "AlipayOrder.h"
#import "WXApiManager.h"
static NSString* cellMoneyIdentifier =@"cellMoneyIdentifier";
static NSString *identifier=@"normalcell";
@interface SPPayListViewController ()<WXApiDelegate>{
SPOrder* _order;
PayCompletedBlock _payCompletedBlock ;
PayStatus curPayStatus ;//支付的状态----支付完成,支付失败,取消支付
}
@property(nonatomic,strong)NSArray *imageArr;
@property(nonatomic,strong)NSArray *titleArr;
@end
@implementation SPPayListViewController
-(id)initWithOrder:(SPOrder*)order completedBlock:(PayCompletedBlock)block{
self = [superinit];
if (self) {
self.hidesBottomBarWhenPushed =YES;
_order = order;/订单
//设置支付代理
[WXApiManagersharedManager].payDelegate =self;
_payCompletedBlock = block;
}
returnself;
}
-(NSArray *)imageArr{
if(nil==_imageArr){
_imageArr=@[@"pay_alipay",@"pay_weixin"];
}
return_imageArr;
}
-(NSArray *)titleArr{
if(nil==_titleArr){
_titleArr=@[@"支付宝支付",@"微信支付"];
}
return_titleArr;
}
- (void)viewDidLoad {
[superviewDidLoad];
[selfinitNavigationBar];
[selfinitSubViews];
// [self initData];//--------原来的商城的支付宝微信等选项的数据
}
-(void)initSubViews{
[superinitSubViews];
self.tableView.tintColor = [UIColorcolorWithHexString:@"#EC661A"alpha:1];
self.tableView.tableFooterView = [[UIViewalloc]init];
self.view.backgroundColor = [UIColorcolorWithRGB:0x000000alpha:1];
//数据表格
self.tableView.frame =CGRectMake(0, 0, winWidth,winHeight);
self.tableView.backgroundColor = [UIColorcolorWithRGB:0xe7e7e7alpha:1];
self.tableView.separatorStyle =UITableViewCellSeparatorStyleNone ;
self.tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
//注册cell
[self.tableViewregisterClass:[UITableViewCellclass]forCellReuseIdentifier:identifier];
//下拉刷新
self.tableView.header=[MJRefreshNormalHeaderheaderWithRefreshingTarget:selfrefreshingAction:@selector(refresh)];
}
-(void)refresh{
// [self initData];
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
[self.tableView.headerendRefreshing];
}
//-(void)initData{///支付设置
//
// self.dataArray = [[NSMutableArray alloc]init];
//
// //支付宝支付
// SPPlugin* alipayPlugin = [SPPluginUtils getPluginWithCode:PLUGIN_ALIPAY_CODE];//@"alipay"-----获取支付宝的配置信息
// if (alipayPlugin && ![SPMobileApplication sharedInstance].isAudit) {
// alipayPlugin.icon = @"pay_alipay";//支付宝的图标
// [self.dataArray addObject:alipayPlugin];//支付方式的数组
// }
//
//
// //微信支付
// SPPlugin* wixinPlugin = [SPPluginUtils getPluginWithCode:PLUGIN_WIXINPAY_CODE];//@"appWeixinPay"----获取微信的配置信息
// if (wixinPlugin && ![SPMobileApplication sharedInstance].isAudit) {
// wixinPlugin.icon = @"pay_weixin";//微信图标
// [self.dataArray addObject:wixinPlugin];
// }
//
// //货到付款
// /*SPPlugin* codPayPlugin = [SPPluginUtils getPluginWithCode:PLUGIN_CODPAY_CODE];
// if (codPayPlugin && ![SPMobileApplication sharedInstance].isAudit) {
// codPayPlugin.icon = @"pay_cod";
// [self.dataArray addObject:codPayPlugin];
// }*/
//
// //银联支付
SPPlugin* unionPayPlugin = [SPPluginUtils getPluginWithCode:PLUGIN_UNIONPAY_CODE];
if (unionPayPlugin && [SPMobileApplication sharedInstance].extraShow) {
[self.dataArray addObject:unionPayPlugin];
}
//
// if (self.dataArray) {
// [self.tableView reloadData];
// }
//}
-(void)initNavigationBar{
[superinitNavigationBar];
UIButton* orderBtn = [UIButtonbuttonWithType:UIButtonTypeCustom];
orderBtn.frame =CGRectMake(0,0,60, 20);
[orderBtn addTarget:selfaction:@selector(gotoOrder:)forControlEvents:UIControlEventTouchDown];
orderBtn.titleLabel.font = [UIFontsystemFontOfSize:13];
orderBtn.titleLabel.textColor =ColorBlack;
[orderBtn setTitle:@"查看订单"forState:UIControlStateNormal];
[orderBtn setTitleColor:ColorSubTitleforState:UIControlStateNormal];
[orderBtn setTitleColor:ColorBlackforState:UIControlStateSelected];
UIBarButtonItem *navRight = [[UIBarButtonItemalloc]initWithCustomView:orderBtn];
self.navigationItem.rightBarButtonItem = navRight;
self.navigationItem.title =@"支付";
}
#pragma mark - 返回购物车
-(void)backAction
{
UIViewController* popVC =nil;
for (UIViewController* historyVCinself.navigationController.viewControllers) {
if ([historyVCisKindOfClass:[SPConfirmOrderViewControllerclass]] || [historyVC isKindOfClass:[SPPayListViewControllerclass]] ) {
break;
}else{
popVC = historyVC ;
}
}
if (popVC) {
[self.navigationControllerpopToViewController:popVCanimated:YES];
}
}
#pragma mark - Table view data source
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 0) {//显示的是支付金额
return 1;
}else{//第二组显示的是支付方式****************
return 2;
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
if (section == 1) {
return 5;
}else{
return 0;
}
}
//构建单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0) {
//支付金额
UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:cellMoneyIdentifier];
if (!cell) {
cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleValue1reuseIdentifier:cellMoneyIdentifier];
cell.selectionStyle =UITableViewCellSelectionStyleNone;
cell.detailTextLabel.textColor =ColorSubTitle;
cell.textLabel.font = [UIFontsystemFontOfSize:13];
cell.detailTextLabel.font = [UIFontsystemFontOfSize:13];
cell.detailTextLabel.textColor =ColorLightRed;
}
if (_order) {
cell.textLabel.text =@"支付金额";
cell.detailTextLabel.text = [NSStringstringWithFormat:@"%@元" , _order.orderAmount];
}
return cell;
}else{
//****************lambo*************
UITableViewCell *cell=[tableViewdequeueReusableCellWithIdentifier:identifier];
cell.imageView.image=[UIImageimageNamed:self.imageArr[indexPath.row]];
cell.textLabel.text=self.titleArr[indexPath.row];
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
return cell;
//****************lambo*************
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 50;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.tableViewdeselectRowAtIndexPath:indexPathanimated:YES];
//**************lambo*************
if(indexPath.section==1){
if(indexPath.row==0){//支付宝支付
[selfaliZhifu];
}elseif(indexPath.row==1){//微信支付
[selfgetWXSignStr];//微信支付
}
}
//**************lambo*************
}
***************************支付宝支付*******************
//获取alipay签名订单字符串
-(void)aliZhifu{
NSLog(@"支付宝");
NSString * orderSN;
__blockNSString *aliSignStr;
orderSN=[_ordergetCurrOrderSn];//根据前面设置的类型0或1,来判断得到是主订单号还是订单编号,从商品性情和购物车来的是主订单号,从订单列表来的是订单编号,
NSLog(@"-支付宝-mainorder--%@--%@",orderSN,_order.master_order_sn);
NSString *url=[TESTBASEURLstringByAppendingString:@"api/Alipay/dopay"];
NSDictionary *parama=@{@"sn":orderSN};
//获取签名的字符串
[LYPayRequestpostShoppayrequestWithUrl:urlparams:paramasuccessBlock:^(NSURLSessionDataTask *task,id responseObject) {
if(responseObject){
aliSignStr=responseObject;
[selfsetAlipayWith:aliSignStr];//吊起支付宝支付
}
} failureBlock:^(NSURLSessionDataTask *task,NSError *error) {
}];
}
//启动支付宝
-(void)setAlipayWith:(NSString *)signStr{
WS(weakSelf);
//启动支付宝客户端支付----支付接口---Scheme是在info中的url Type中设置
[[AlipaySDKdefaultService]payOrder:signStrfromScheme:@"awofubao"callback:^(NSDictionary *resultDic) {
NSString* resultStatus = [resultDicobjectForKey:@"resultStatus"];
NSLog(@"--支付结果---%@",resultDic);
if (resultStatus && [resultStatusisEqualToString:@"9000"]) {
curPayStatus =statusSccess ;
//支付成功
[weakSelf onPayFinish];
}else{//支付失败提示
NSString* memo = [resultDicobjectForKey:@"memo"];
curPayStatus =statusFailed;
[weakSelf showTextOnly:memo];
}
}];
}
********************获取微信签名订单信息,吊起支付*********
//获取微信签名订单字符串------并且吊起支付
-(void)getWXSignStr{
WS(weakSelf);
NSLog(@"微信");
NSString * orderSN;
orderSN=[_ordergetCurrOrderSn];//根据前面设置的类型0或1,来判断得到是主订单号还是订单编号,从商品性情和购物车来的是主订单号,从订单列表来的是订单编号,
NSLog(@"--微信mainorder--%@--%@",orderSN,_order.master_order_sn);
NSString *url=[TESTBASEURLstringByAppendingString:@"api/Wxpay/dopay"];
NSDictionary *parama=@{@"sn":orderSN};
[LYPayRequestpostShoppayrequestWithUrl:urlparams:paramasuccessBlock:^(NSURLSessionDataTask *task,id responseObject) {
if (responseObject) {
SPWxPayInfo* payInfo =[SPWxPayInfoobjectWithKeyValues:responseObject];//字典转模型
//服务器需要传递参数
PayReq* req = [[PayReqalloc]init];
req.openID = payInfo.appid;//由用户微信号和AppID组成的唯一标识,发送请求时第三方程序必须填写,用于校验微信用户是否换号登录*/ appid = wxfba5a9c20a82864d;
req.partnerId = payInfo.partnerid;//商家向财付通申请的商家id
req.prepayId = payInfo.prepayid;//预支付订单
req.nonceStr = payInfo.noncestr;//随机串,防重发
req.timeStamp = [payInfo.timestampintValue];//时间戳,防重发
req.package = payInfo.packageValue;//商家根据财付通文档填写的数据和签名
req.sign = payInfo.sign ;//商家根据微信开放平台文档对数据做的签名
if (![WXApiisWXAppInstalled] || ![WXApiisWXAppSupportApi]) {//判断用户是否安装微信
[selfalert:@"提示信息"msg:@"未安装微信客户端"];
return ;
}else {
[WXApisendReq:req];//发送请求到微信,等待微信返回onResp
}
}else{
[weakSelf showTextOnly:@"无数据返回!"];
}
} failureBlock:^(NSURLSessionDataTask *task,NSError *error) {
[weakSelf hideLoading];
[weakSelf showTextOnly:@"请检查网络"];
}];
}
#pragma mark WXApiDelegate
/**
回调微信请求结果----发送一个sendReq后,收到微信的回应
*/
-(void)onResp:(BaseResp *)resp{
NSLog(@"---resp---%@",resp);
NSInteger type = resp.type ;//响应类型
NSString* errStr = resp.errStr ;//错误提示字符串
if ([respisKindOfClass:[PayRespclass]]) {
switch (resp.errCode) {
caseWXSuccess:
//支付成功,查询后台支付结果
[selfonPayFinish];
curPayStatus =statusSccess;
break;
default:
[selfshowTextOnly:resp.errStr];
curPayStatus =statusFailed ;
break;
}
}
}
++++++++++++++++++
// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*,id> *)options
{
NSLog(@"openURL url : %@" , url);
//友盟第三方登录
/*
if (result) {
return result;
}else*/
if ([url.hostisEqualToString:@"safepay"]) {
//跳转支付宝钱包进行支付,处理支付结果
[[AlipaySDKdefaultService]processOrderWithPaymentResult:urlstandbyCallback:^(NSDictionary *resultDic) {
NSLog(@"result = %@",resultDic);
}];
}elseif([url.schemeisEqualToString:WX_APPID]&&[url.hostisEqualToString:@"pay"]) {
//跳转微信进行支付,处理支付结果
return [WXApihandleOpenURL:urldelegate:[WXApiManagersharedManager].payDelegate];
}else{
//第三方登录------友盟第三方登录的回调
[[UMSocialManagerdefaultManager]handleOpenURL:url];
}
returnYES;
}