首先,大家10.24程序員節(jié)快樂!哈哈哈(然而還是單身,快樂個(gè)P哦) 這段時(shí)間一直在開發(fā)新的項(xiàng)目,1.0版本是和另外一個(gè)同事一個(gè)月協(xié)同開發(fā)完成的。然后修修改改什么的,今天發(fā)布了1.0.1版本。一直拖到了現(xiàn)在寫。今天記錄一下新項(xiàng)目和原來的項(xiàng)目都更新過的支付支付寶支付和微信支付,當(dāng)然想了解ApplePay的也可以在下面留言哦。好了,下面進(jìn)入正題。(支付的SDK ,環(huán)境什么的自己按照官網(wǎng)的文檔一步一步來就可以了,包括支付流程原理什么的網(wǎng)上一大堆,這里只說在哪里需要什么代碼)
一.支付寶支付
原來的那個(gè)項(xiàng)目中,支付寶支付所需的支付信息都是在項(xiàng)目里寫成常量的,但上星期收到了一封來自支付寶的郵件指出了什么安全性的問題,然后加密,拼接什么的都在后臺(tái)操作了,在客戶端這邊只需拿到后臺(tái)給的接口去請(qǐng)求下來拿到后臺(tái)處理好的字符串調(diào)起支付就行了。(至于后臺(tái)的操作我就不清楚了,尷尬)
下面就是點(diǎn)擊支付按鈕的點(diǎn)擊事件
- (void)aliPay {
//將商品信息賦予AlixPayOrder的成員變量
Order*order = [[Orderalloc]init];
order.tradeNO=self.orderId;//訂單ID(由商家自行制定)
order.productName=@"測試";//商品標(biāo)題
order.productDescription=@"商品描述";//商品描述
order.amount= [NSStringstringWithFormat:@"%.2f",self.payAmount];//商品價(jià)格
NSString*urlString = [NSStringstringWithFormat:@"%@/pays/app/alipay",host];
NSDictionary*param =@{@"orderId":self.orderId};
XSAPIManager*manager = [XSAPIManagermanager];
[managerGET:urlStringparameters:paramsuccess:^(idresponseObject) {
AliPay*model = [AliPaymj_objectWithKeyValues:responseObject];
[[AlipaySDKdefaultService]payOrder:model.data.payInfofromScheme:URL_SCHEMEScallback:^(NSDictionary*resultDic) {//調(diào)起支付并處理返還的結(jié)果
NSLog(@"reslut payOrder = %@",resultDic);
//NSLog(@"reslut = %@",resultDic);
if([resultDic[@"resultStatus"]isEqual:@"9000"]) {
[self.navigationControllerpopViewControllerAnimated:YES];
XSOrderCompletedViewController*vc = [[XSOrderCompletedViewControlleralloc]init];
vc.orderId=self.orderId;
[self.navigationControllerpushViewController:vcanimated:YES];
//支付成功;
}
elseif([resultDic[@"resultStatus"]isEqual:@"8000"]) {
//正在處理中;
}
elseif([resultDic[@"resultStatus"]isEqual:@"4000"]) {
//訂單支付失敗;
}
elseif([resultDic[@"resultStatus"]isEqual:@"6001"]) {
//[self.navigationController popViewControllerAnimated:YES];
//XSOrderCompletedViewController *vc = [[XSOrderCompletedViewController alloc]init];
//vc.orderId = self.orderId;
//[self.navigationController pushViewController:vc animated:YES];
//
}
elseif([resultDic[@"resultStatus"]isEqual:@"6002"]) {
//您的網(wǎng)絡(luò)連接出錯(cuò)
}
else{
//支付失敗
}
}];
//}
}failure:^(NSError*error) {
NSLog(@"%@",error);
} ];
}
值得注意的是,這里支付寶支付調(diào)起后就返回了結(jié)果,所以在這里就可以根據(jù)返回結(jié)果進(jìn)行操作。而微信支付的回調(diào)是在AppDelegate里面,所以我打算在最后面說一AppDelegate里的代碼。
二.微信支付
微信支付同樣,也是通過一個(gè)接口向后臺(tái)發(fā)起請(qǐng)求然后處理返回的數(shù)據(jù)調(diào)起支付就ok了。下面是點(diǎn)擊微信支付按鈕的點(diǎn)擊事件代碼。
- (void)wechatPay {
NSString*weixinBackStr = [selfwxPay];
if(![weixinBackStrisEqualToString:@""]) {
NSLog(@"微信支付返回的信息:%@",weixinBackStr);
}
}
- (NSString*)wxPay {
/**添加兩個(gè)判斷**/
//判斷是否安裝了微信
if( ![WXApiisWXAppInstalled]){
NSLog(@"沒有安裝微信");
returnnil;
}elseif(![WXApiisWXAppSupportApi]){
NSLog(@"不支持微信支付");
returnnil;
}
//向服務(wù)器端獲取支付數(shù)據(jù)(商家自定義)
NSString*urlString = [NSStringstringWithFormat:@"%@/pays/app/wxpay",host];
NSDictionary*param =@{@"orderId":self.orderId};
XSAPIManager*manager = [XSAPIManagermanager];
[manager POST:url StringrequestType:0 parameters:paramsuccess:^(idresponseObject) {
NSLog(@"responseObject%@",responseObject);
XSWXPayReq*wxPayReq = [XSWXPayReqmj_objectWithKeyValues:responseObject];
if(wxPayReq.code==1) {
//調(diào)起微信支付
PayReq* req= [[PayReqalloc]init];
req.partnerId= wxPayReq.data.partnerId;
req.prepayId= wxPayReq.data.prepayId;
req.nonceStr= wxPayReq.data.nonceStr;
req.timeStamp= wxPayReq.data.timeStamp;
req.package= wxPayReq.data.packageValue;
req.sign= wxPayReq.data.sign;
[WXApisendReq:req];
}else{
}
}failure:^(NSError*error) {
NSLog(@"%@",error);
}];
return@"";
}
三 AppDelagate里所需的代碼
- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url {
return[WXApihandleOpenURL:urldelegate:self];
}
- (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation {
BOOLresult = [UMSocialSnsServicehandleOpenURL:url];
if(result ==FALSE) {
//調(diào)用其他SDK,例如支付寶SDK等
/**
*跳轉(zhuǎn)支付寶錢包進(jìn)行支付,處理支付結(jié)果
*/
if([url.hostisEqualToString:@"safepay"]) {
[[AlipaySDKdefaultService]processOrderWithPaymentResult:urlstandbyCallback:^(NSDictionary*resultDic) {
NSLog(@"result safepay = %@",resultDic);
}];
}
if([url.hostisEqualToString:@"platformapi"]) {
[[AlipaySDKdefaultService]processOrderWithPaymentResult:urlstandbyCallback:^(NSDictionary*resultDic) {
NSLog(@"result platformapi = %@",resultDic);
}];
}
//微信的支付回調(diào)
if([url.hostisEqualToString:@"pay"]) {
return[WXApihandleOpenURL:urldelegate:self];
}
}
returnYES;
}
- (void)onResp:(BaseResp*)resp
{
NSString* strMsg = [NSStringstringWithFormat:@"errorCode: %d",resp.errCode];
NSLog(@"strMsg: %@",strMsg);
NSString* errStr= [NSStringstringWithFormat:@"errStr: %@",resp.errStr];
NSLog(@"errStr: %@",errStr);
NSString* strTitle;
//判斷是微信消息的回調(diào)
if([respisKindOfClass:[SendMessageToWXRespclass]])
{
strTitle = [NSStringstringWithFormat:@"發(fā)送媒體消息的結(jié)果"];
}
NSString* wxPayResult;
//判斷是否是微信支付回調(diào)(注意是PayResp而不是PayReq)
if([respisKindOfClass:[PayRespclass]])
{
//支付返回的結(jié)果,實(shí)際支付結(jié)果需要去微信服務(wù)器端查詢
strTitle = [NSStringstringWithFormat:@"支付結(jié)果"];
switch(resp.errCode)
{
caseWXSuccess:
{
strMsg =@"支付結(jié)果:";
NSLog(@"支付成功: %d",resp.errCode);
wxPayResult =@"success";
break;
}
caseWXErrCodeUserCancel:
{
strMsg =@"用戶取消了支付";
NSLog(@"用戶取消支付: %d",resp.errCode);
wxPayResult =@"cancle";
break;
}
default:
{
strMsg = [NSStringstringWithFormat:@"支付失敗! code: %derrorStr: %@",resp.errCode,resp.errStr];
NSLog(@":支付失敗: code: %d str: %@",resp.errCode,resp.errStr);
wxPayResult =@"faile";
break;
}
}
//發(fā)出通知
NSNotification* notification = [NSNotificationnotificationWithName:@"WXPay"object:wxPayResult];
[[NSNotificationCenterdefaultCenter]postNotification:notification];
}
}
上面的- (void)onResp:(BaseResp)resp就是調(diào)起微信支付后返回的結(jié)果,那么問題來了,支付后的操作總不能在AppDelegate里面吧,所以- (void)onResp:(BaseResp)resp最后的那個(gè)通知就是為了避免這個(gè)尷尬用的。發(fā)出通知,然后在點(diǎn)擊調(diào)起支付的controller里接收通知,代碼如下:
- (void)viewDidLoad {
[superviewDidLoad];
//默認(rèn)選擇支付寶
self.option=XSOnlinePayOptionAliPay;
//監(jiān)聽通知
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(getResult:)name:@"WXPay"object:nil];
}
- (void)dealloc {
[[NSNotificationCenterdefaultCenter]removeObserver:self];
}
#pragma mark微信支付結(jié)果回調(diào)通知操作
- (void)getResult:(NSNotification*)notification {
NSLog(@"userInfo: %@",notification.userInfo);
if([notification.objectisEqualToString:@"success"]){
XSOrderCompletedViewController*vc = [[XSOrderCompletedViewControlleralloc]init];
vc.orderId=self.orderId;
[self.navigationControllerpushViewController:vcanimated:YES];
}
elseif([notification.objectisEqualToString:@"cancle"]){
[selfalert:@"提示"msg:@"您已經(jīng)取消了支付"];
}else{
[selfalert:@"提示"msg:@"支付失敗!請(qǐng)重新支付"];
}
}
- (void)alert:(NSString*)title msg:(NSString*)msg
{
UIAlertView*alter = [[UIAlertViewalloc]initWithTitle:titlemessage:msgdelegate:nilcancelButtonTitle:@"確定"otherButtonTitles:nil];
[altershow];
}
四 補(bǔ)充
一般來說,當(dāng)同時(shí)有微信支付和支付寶支付的時(shí)候,一般頁面只有一個(gè)確認(rèn)支付按鈕,如下圖
這時(shí)只需在定義個(gè)枚舉類型,
typedefNS_ENUM(NSInteger, XSOnlinePayOption) {
XSOnlinePayOptionAliPay,
XSOnlinePayOptionWeChatPay,
XSOnlinePayOptionApplePay
};
然后在支付頁面的controller中定義個(gè)對(duì)象
@property(assign,nonatomic)XSOnlinePayOption option;
在viewDidLoad里面設(shè)置默認(rèn)支付方式為支付寶,然后上圖1按鈕的點(diǎn)擊事件代碼如下
- (IBAction)paySwitch:(UIButton*)sender {
if(sender ==self.aliButton) {
self.option=XSOnlinePayOptionAliPay;
[self.aliButtonsetImage:[UIImageimageNamed:@"selected_non"]forState:UIControlStateNormal];
[self.wechatButtonsetImage:[UIImageimageNamed:@"unselected"]forState:UIControlStateNormal];
[self.applePayButtonsetImage:[UIImageimageNamed:@"unselected"]forState:UIControlStateNormal];
}elseif(sender ==self.wechatButton) {
self.option=XSOnlinePayOptionWeChatPay;
[self.wechatButtonsetImage:[UIImageimageNamed:@"selected_non"]forState:UIControlStateNormal];
[self.aliButtonsetImage:[UIImageimageNamed:@"unselected"]forState:UIControlStateNormal];
[self.applePayButtonsetImage:[UIImageimageNamed:@"unselected"]forState:UIControlStateNormal];
}elseif(sender ==self.applePayButton) {
self.option=XSOnlinePayOptionApplePay;
[self.applePayButtonsetImage:[UIImageimageNamed:@"selected_non"]forState:UIControlStateNormal];
[self.wechatButtonsetImage:[UIImageimageNamed:@"unselected"]forState:UIControlStateNormal];
[self.aliButtonsetImage:[UIImageimageNamed:@"unselected"]forState:UIControlStateNormal];
}
}
圖中2的點(diǎn)擊事件代碼如下
- (IBAction)payNow:(UIButton*)sender {
if(self.option==XSOnlinePayOptionAliPay) {
[MBProgressHUDshowHUDAddedTo:self.viewanimated:YES];
[self.orderManagervalidatePayInfo:self.orderIdpayType:@"zhifubao"];
}elseif(self.option==XSOnlinePayOptionWeChatPay) {
[self.orderManagervalidatePayInfo:self.orderIdpayType:@"wxpay"];
}elseif(self.option==XSOnlinePayOptionApplePay) {
//[self applePay];
}
}
這樣就能自由選擇支付方式調(diào)起支付了。
微信支付和支付寶支付網(wǎng)上的資料一大堆,寫法也各不一樣,反正能調(diào)起支付完成功能就OK啦。有不足的地方歡迎指出,謝謝!