iOS開發(fā)微信支付詳解(一)

網(wǎng)上看了好多博客文章囊扳,與關(guān)于微信支付的我攏了攏主要的,可以看看
這是導(dǎo)入的庫和配置的URLType

1869333-5a26a95263fc5956.png

一锥咸、首先在AppDelegate.m 里

#import "AppDelegate.h"
#import "WXApi.h"
#import "ViewController.h"
@interface AppDelegate ()
@end
@implementation AppDelegate

這里就兩行代碼注冊微信:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
ViewController *viewVC = [[ViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:viewVC];
self.window.backgroundColor = [UIColor whiteColor];
[self.window setRootViewController:nav];
// 向微信注冊
BOOL isOk = [WXApi registerApp:@""];
if (isOk){NSLog(@"注冊微信成功");
}else{NSLog(@"注冊微信失敗");
}return YES;
}

這里的代碼就是吊起微信客戶端的微信支付功能

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary*)options
{
// 跳轉(zhuǎn)到URL scheme中配置的地址
NSLog(@"跳轉(zhuǎn)到URL scheme中配置的地址-->%@",url);
return [WXApi handleOpenURL:url delegate:self];  //WXApiDelegate協(xié)議
}

微信支付結(jié)果回調(diào)

- (void)onResp:(BaseResp *)resp
{
NSString *strMsg = [NSString stringWithFormat:@"-errcode:%d", resp.errCode];
NSString *strTitle;
if([resp isKindOfClass:[SendMessageToWXResp class]])
{
strTitle = [NSString stringWithFormat:@"發(fā)送媒體消息結(jié)果"];
}

if([resp isKindOfClass:[PayResp class]]){
#warning 4.支付返回結(jié)果,實際支付結(jié)果需要去自己的服務(wù)器端查詢  由于demo的局限性這里直接使用返回的結(jié)果
strTitle = [NSString stringWithFormat:@"支付結(jié)果"];
// 返回碼參考:https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=9_12
switch (resp.errCode) {
case WXSuccess:{
strMsg = @"支付結(jié)果:成功搏予!";
NSLog(@"支付成功-PaySuccess熊锭,retcode = %d", resp.errCode);
NSNotification *notification = [NSNotification notificationWithName:@"ORDER_PAY_NOTIFICATION" object:@"success"];
[[NSNotificationCenter defaultCenter] postNotification:notification];
break;
}

default:{
strMsg = [NSString stringWithFormat:@"支付結(jié)果:失數奚病!retcode = %d, retstr = %@", resp.errCode,resp.errStr];
NSLog(@"錯誤校镐,retcode = %d, retstr = %@", resp.errCode,resp.errStr);
NSNotification *notification = [NSNotification notificationWithName:@"ORDER_PAY_NOTIFICATION"object:@"fail"];
[[NSNotificationCenter defaultCenter] postNotification:notification];
break;
}

}

}

UIAlertController *alert = [UIAlertController alertControllerWithTitle:strTitle message:strMsg preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"知道了");
}];
[alert addAction:action];
[self.window.rootViewController presentViewController:alert animated:YES completion:nil];
NSLog(@"title = %@ message = %@", strTitle, strMsg);
}

二亿扁、在ViewController.m里面

#import "ViewController.h"
#import "WXApi.h"
@interface ViewController ()
@end
@implementation ViewController
```
/**
*  微信支付需要后臺做大量的工作鸟廓。
*  SDK及官方Demo下載:https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=11_1
*  官方的開發(fā)步驟參考這里:https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=8_5
*  這篇文檔說的也挺詳細(xì):http://wenku.baidu.com/link?url=II3oeAaiH9NXWqdoO5HwXWCGcEermreHGBAqKvYfyKz_JVQ2n4NlA56e0H1HJWTNFfUsrTAgjegHBeUpMRzN0S318qcVklep7VCq0wBkpv7
*  還有這篇:http://www.cocoachina.com/bbs/read.php?tid=303132

** 移除通知**
```
- (void)dealloc
{
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
```
** 監(jiān)聽通知**
```
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
if([WXApi isWXAppInstalled]) // 判斷 用戶是否安裝微信
{
// 監(jiān)聽一個通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderPayResult:) name:@"ORDER_PAY_NOTIFICATION" object:nil];
}

}
```
```
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.title = @"微信支付";
UIButton *payButton = [UIButton buttonWithType:UIButtonTypeCustom];
payButton.frame = CGRectMake(50, 100, self.view.frame.size.width - 100, 60);
payButton.backgroundColor = [UIColor lightGrayColor];
[payButton setTitle:@"微信支付" forState:UIControlStateNormal];
[payButton setImage:[UIImage imageNamed:@"payNow_weixin"] forState:UIControlStateNormal];
[payButton setImageEdgeInsets:UIEdgeInsetsMake(5, -20, 0, 0)];
payButton.layer.cornerRadius = 5;
[payButton addTarget:self action:@selector(weChatPay) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:payButton];
}
```
**#pragma mark - 微信支付**
```
- (void)weChatPay
{
#warning 1.向自己的服務(wù)器請求訂單生成預(yù)支付訂單信息
NSString *string = [NSString stringWithFormat:@""];
[ZqNetWork getRequestWithURLString:string Parameters:nil RequestHead:nil DataReturnType:DataReturnTypeData SuccessBlock:^(NSData *data) {
NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
// 具體參數(shù)根據(jù)自己后臺來,這里不做示范
// 后臺可以參考:https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=9_12
NSDictionary *dict = [resultDic objectForKey:@""];
if (dict != nil) {
NSMutableString *stamp  = [dict objectForKey:@""];
// 生成預(yù)支付訂單信息
PayReq *req            = [[PayReq alloc] init];
req.openID              = [dict objectForKey:@""];
req.partnerId          = @"";
req.prepayId            = [dict objectForKey:@""];
req.nonceStr            = [dict objectForKey:@""];
req.timeStamp          = stamp.intValue;
req.package            = [dict objectForKey:@""];
req.sign                = [dict objectForKey:@""];
#warning 2.調(diào)起微信支付
if ([WXApi sendReq:req])
{
NSLog(@"調(diào)起成功!!!!");
}

else
{
NSLog(@"調(diào)起失敗!!!");
}

}

} FailureBlock:^(NSError *error) {
NSLog(@"%@", error);
}];
}
```
**#pragma mark - 收到支付成功的消息后作相應(yīng)的處理**
```
- (void)getOrderPayResult:(NSNotification *)notification
{
if ([notification.object isEqualToString:@"success"])
{
NSLog(@"支付成功!");
}

else
{
NSLog(@"支付失旊鼓啊!");
}

}
```
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末员咽,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子贝室,更是在濱河造成了極大的恐慌契讲,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,744評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件捡偏,死亡現(xiàn)場離奇詭異,居然都是意外死亡峡迷,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,505評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來彤避,“玉大人,你說我怎么就攤上這事忠藤⌒铮” “怎么了?”我有些...
    開封第一講書人閱讀 163,105評論 0 353
  • 文/不壞的土叔 我叫張陵尖阔,是天一觀的道長。 經(jīng)常有香客問我榨咐,道長,這世上最難降的妖魔是什么块茁? 我笑而不...
    開封第一講書人閱讀 58,242評論 1 292
  • 正文 為了忘掉前任齿坷,我火速辦了婚禮数焊,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘佩耳。我一直安慰自己遂蛀,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,269評論 6 389
  • 文/花漫 我一把揭開白布李滴。 她就那樣靜靜地躺著,像睡著了一般蛮瞄。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上挂捅,一...
    開封第一講書人閱讀 51,215評論 1 299
  • 那天芹助,我揣著相機(jī)與錄音闲先,去河邊找鬼周瞎。 笑死饵蒂,一個胖子當(dāng)著我的面吹牛酱讶,可吹牛的內(nèi)容都是我干的退盯。 我是一名探鬼主播,決...
    沈念sama閱讀 40,096評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼慰照,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了琉朽?” 一聲冷哼從身側(cè)響起毒租,我...
    開封第一講書人閱讀 38,939評論 0 274
  • 序言:老撾萬榮一對情侶失蹤箱叁,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后耕漱,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體算色,經(jīng)...
    沈念sama閱讀 45,354評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡螟够,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,573評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了妓笙。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片若河。...
    茶點故事閱讀 39,745評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡寞宫,死狀恐怖萧福,靈堂內(nèi)的尸體忽然破棺而出淆九,到底是詐尸還是另有隱情统锤,我是刑警寧澤炭庙,帶...
    沈念sama閱讀 35,448評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站焕蹄,受9級特大地震影響逾雄,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜鸦泳,卻給世界環(huán)境...
    茶點故事閱讀 41,048評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望永品。 院中可真熱鬧,春花似錦鼎姐、人聲如沸钾麸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,683評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽肯腕。三九已至,卻和暖如春钥平,著一層夾襖步出監(jiān)牢的瞬間实撒,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,838評論 1 269
  • 我被黑心中介騙來泰國打工涉瘾, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留知态,地道東北人。 一個月前我還...
    沈念sama閱讀 47,776評論 2 369
  • 正文 我出身青樓睡汹,卻偏偏與公主長得像肴甸,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子囚巴,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,652評論 2 354

推薦閱讀更多精彩內(nèi)容