微信支付

比較簡單餐济,只做一個筆記耘擂,并于以后查詢
1、將微信支付第三方庫拖到項目中

項目中微信第三方支付截圖

2絮姆、添加微信支付需要的依賴庫

微信支付需要的依賴庫.png

3醉冤、環(huán)境配置
1)、https相關(guān)配置

https-info.plist中配置.png

2)篙悯、LSApplicationQueriesSchemes白名單設(shè)置

添加微信白名單.png

3)蚁阳、URL Schemes配置,這邊涂鴉掉的數(shù)值鸽照,和項目中注冊微信支付時的appID一致

截圖

有兩種方法設(shè)置韵吨,一種是在plist文件中


URL Schemes

第二種是圖形樣式,info->URL Types


URL Types截圖

4)移宅、bitcode配置
build setting -> bitcode

項目截圖

3归粉、項目代碼
控制器中的代碼
代碼中相關(guān)appID等參數(shù)寫在頭文件中,不方便寫出來漏峰,換成自己項目中的配置參數(shù)就可以了

#import "ViewController.h"

//微信支付
#import "DataMD5.h"
#import "XMLDictionary.h"
#import "AFHTTPRequestOperationManager.h"
#import "WXApiObject.h"
#import "WXApi.h"
#import "getIPhoneIP.h"
#import "WXApi.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //微信支付-添加通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(weixinPaySuccess)
                                                 name:WeiXinPaySuccessNotification
                                               object:nil];    
}
- (void)viewDidUnload
{
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:WeiXinPaySuccessNotification object:nil];
    
    
    [super viewDidUnload];
}

//微信支付
- (IBAction)weixinPay:(id)sender {
    
    //微信最后支付的價格=真實的價格*100
    //    NSString *payCount = [NSString stringWithFormat:@"%.0f",_rechargeAmount*100];
    //        [self weixinChooseActWithGlodNo:_rechargeOrderNumber payCount:payCount];
    
    NSString *glodNo = [self generateTradeNO];//商品訂單號
    [self weixinChooseActWithGlodNo:glodNo payCount:@"1"];
}
#pragma make -  微信支付獲取訂單號糠悼、產(chǎn)品信息、簽名浅乔、認證
#pragma mark 微信支付相關(guān)方法
- (void)weixinChooseActWithGlodNo:(NSString *)glodSn payCount:(NSString *)payCount {
    NSString *appid,*mch_id,*nonce_str,*sign,*body,*out_trade_no,*total_fee,*spbill_create_ip,*notify_url,*trade_type,*partner;
    //應(yīng)用APPID
    appid = WX_appID;
    //微信支付商戶號
    mch_id = MCH_ID;
    //產(chǎn)生隨機字符串倔喂,這里最好使用和安卓端一致的生成邏輯
    nonce_str =[self generateTradeNO];
    body =@"項目名字+微信支付";
    //隨機產(chǎn)生訂單號用于測試,正式使用請換成你從自己服務(wù)器獲取的訂單號
    out_trade_no = glodSn;
    //交易價格1表示0.01元靖苇,10表示0.1元
    total_fee = payCount;
    //獲取本機IP地址席噩,請再wifi環(huán)境下測試,否則獲取的ip地址為error贤壁,正確格式應(yīng)該是8.8.8.8
    //    spbill_create_ip =[getIPhoneIP getIPAddress];
    //
    spbill_create_ip =@"192.168.1.21";
    //交易結(jié)果通知網(wǎng)站此處用于測試悼枢,隨意填寫,正式使用時填寫正確網(wǎng)站
    notify_url =@"www.cccuu.com";
    trade_type =@"APP";
    //商戶密鑰
    partner = WX_partnerKey;
    //獲取sign簽名
    DataMD5 *data = [[DataMD5 alloc] initWithAppid:appid mch_id:mch_id nonce_str:nonce_str partner_id:partner body:body out_trade_no:out_trade_no total_fee:total_fee spbill_create_ip:spbill_create_ip notify_url:notify_url trade_type:trade_type];
    sign = [data getSignForMD5];
    //設(shè)置參數(shù)并轉(zhuǎn)化成xml格式
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:appid forKey:@"appid"];//公眾賬號ID
    [dic setValue:mch_id forKey:@"mch_id"];//商戶號
    [dic setValue:nonce_str forKey:@"nonce_str"];//隨機字符串
    [dic setValue:sign forKey:@"sign"];//簽名
    [dic setValue:body forKey:@"body"];//商品描述
    [dic setValue:out_trade_no forKey:@"out_trade_no"];//訂單號
    [dic setValue:total_fee forKey:@"total_fee"];//金額
    [dic setValue:spbill_create_ip forKey:@"spbill_create_ip"];//終端IP
    [dic setValue:notify_url forKey:@"notify_url"];//通知地址
    [dic setValue:trade_type forKey:@"trade_type"];//交易類型
    // 轉(zhuǎn)換成xml字符串
    NSString *string = [dic XMLString];
    [self http:string];
}

#pragma mark 拿到轉(zhuǎn)換好的xml發(fā)送請求
- (void)http:(NSString *)xml {
    //    [MBProgressHUD showMessage:@"正在獲取支付訂單..."];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //這里傳入的xml字符串只是形似xml脾拆,但是不是正確是xml格式馒索,需要使用af方法進行轉(zhuǎn)義
    manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
    [manager.requestSerializer setValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"https://api.mch.weixin.qq.com/pay/unifiedorder" forHTTPHeaderField:@"SOAPAction"];
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {
        return xml;
    }];
    //發(fā)起請求
    [manager POST:@"https://api.mch.weixin.qq.com/pay/unifiedorder" parameters:xml success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
        // LXLog(@"responseString is %@",responseString);
        //將微信返回的xml數(shù)據(jù)解析轉(zhuǎn)義成字典
        NSDictionary *dic = [NSDictionary dictionaryWithXMLString:responseString];
        //判斷返回的許可
        if ([[dic objectForKey:@"result_code"] isEqualToString:@"SUCCESS"] &&[[dic objectForKey:@"return_code"] isEqualToString:@"SUCCESS"] ) {
            //發(fā)起微信支付莹妒,設(shè)置參數(shù)
            PayReq *request = [[PayReq alloc] init];
            request.openID = [dic objectForKey:@"appid"];
            request.partnerId = [dic objectForKey:@"mch_id"];
            request.prepayId= [dic objectForKey:@"prepay_id"];
            request.package = @"Sign=WXPay";
            request.nonceStr= [dic objectForKey:@"nonce_str"];
            //將當前事件轉(zhuǎn)化成時間戳
            NSDate *datenow = [NSDate date];
            NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
            UInt32 timeStamp =[timeSp intValue];
            request.timeStamp= timeStamp;
            // 簽名加密
            DataMD5 *md5 = [[DataMD5 alloc] init];
            request.sign=[md5 createMD5SingForPay:request.openID partnerid:request.partnerId prepayid:request.prepayId package:request.package noncestr:request.nonceStr timestamp:request.timeStamp];
            // 調(diào)用微信
            [WXApi sendReq:request];
            //            [MBProgressHUD hideHUD];
        }else{
            NSLog(@"參數(shù)不正確,請檢查參數(shù)");
            //            [MBProgressHUD hideHUD];
            //            [MBProgressHUD showError:@"支付錯誤绰上!"];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error is %@",error);
        //        [MBProgressHUD hideHUD];
        //                [MBProgressHUD showError:@"未完成支付"];
    }];
}

#pragma mark 產(chǎn)生隨機訂單號
- (NSString *)generateTradeNO {
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    //    srand(time(0)); // 此行代碼有警告:
    srand( (unsigned)time(0) );//上行改過之后
    
    for (int i = 0; i < kNumber; i++) {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}

#pragma make 微信支付成功之后調(diào)用的
-(void)weixinPaySuccess
{
    NSLog(@"微信支付成功,把對應(yīng)的單子消除");
    // 通知后臺充值訂單支付成功
}

@end

delegate中的代碼

#import "AppDelegate.h"
#import "WXApi.h"

@interface AppDelegate ()<WXApiDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //微信支付注冊
    [WXApi registerApp:WX_appID];
    
    return YES;
}

//微信支付-回調(diào)
//9.0之前調(diào)用的方法
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [self weiXinPayOrZhiFuBaoForUrl:url];
}
//9.0之前調(diào)用的方法
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary*)options
{
    return [self weiXinPayOrZhiFuBaoForUrl:url];
}
//9.0之后調(diào)用的方法
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return [self weiXinPayOrZhiFuBaoForUrl:url];
}

//微信支付回調(diào)方法處理
-(BOOL)weiXinPayOrZhiFuBaoForUrl:(NSURL *)url
{
    if ([url.host isEqualToString:@"safepay"]) {//支付寶支付相關(guān)操作
        
    }else if ([url.host isEqualToString:@"pay"]){//微信支付相關(guān)操作
        return  [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}
//WXApiDelegate
-(void)onResp:(BaseResp *)resp {
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp*response=(PayResp*)resp;  // 微信終端返回給第三方的關(guān)于支付結(jié)果的結(jié)構(gòu)體
        switch (response.errCode) {
            case WXSuccess:
            {// 支付成功旨怠,向后臺發(fā)送消息
                NSLog(@"支付成功~~~");
                [[NSNotificationCenter defaultCenter] postNotificationName:WeiXinPaySuccessNotification object:nil];
            }
                break;
            case WXErrCodeCommon:
            { //簽名錯誤航唆、未注冊APPID被饿、項目設(shè)置APPID不正確贮预、注冊的APPID與設(shè)置的不匹配薯酝、其他異常等
                //                [MBProgressHUD showError:@"支付失敗"];
                NSLog(@"支付失敗~~~");
            }
                break;
            case WXErrCodeUserCancel:
            { //用戶點擊取消并返回
                NSLog(@"取消支付~~~");
                //                [MBProgressHUD showError:@"取消支付"];
            }
                break;
            case WXErrCodeSentFail:
            { //發(fā)送失敗
                NSLog(@"發(fā)送失敗~~~");
                //                [MBProgressHUD showError:@"發(fā)送失敗"];
            }
                break;
            case WXErrCodeUnsupport:
            { //微信不支持
                NSLog(@"微信不支持~~~");
                //                [MBProgressHUD showError:@"微信不支持"];
            }
                break;
            case WXErrCodeAuthDeny:
            { //授權(quán)失敗
                NSLog(@"授權(quán)失敗~~~");
                //                [MBProgressHUD showError:@"授權(quán)失敗"];
            }
                break;
            default:
                break;
        }
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end

祝成功~~??

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末困鸥,一起剝皮案震驚了整個濱河市聋迎,隨后出現(xiàn)的幾起案子疤苹,更是在濱河造成了極大的恐慌赶舆,老刑警劉巖信峻,帶你破解...
    沈念sama閱讀 221,430評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件倦青,死亡現(xiàn)場離奇詭異,居然都是意外死亡盹舞,警方通過查閱死者的電腦和手機产镐,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,406評論 3 398
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來踢步,“玉大人癣亚,你說我怎么就攤上這事』裼。” “怎么了述雾?”我有些...
    開封第一講書人閱讀 167,834評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長兼丰。 經(jīng)常有香客問我玻孟,道長,這世上最難降的妖魔是什么鳍征? 我笑而不...
    開封第一講書人閱讀 59,543評論 1 296
  • 正文 為了忘掉前任黍翎,我火速辦了婚禮,結(jié)果婚禮上艳丛,老公的妹妹穿的比我還像新娘匣掸。我一直安慰自己,他們只是感情好氮双,可當我...
    茶點故事閱讀 68,547評論 6 397
  • 文/花漫 我一把揭開白布碰酝。 她就那樣靜靜地躺著,像睡著了一般戴差。 火紅的嫁衣襯著肌膚如雪送爸。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,196評論 1 308
  • 那天,我揣著相機與錄音碱璃,去河邊找鬼弄痹。 笑死饭入,一個胖子當著我的面吹牛嵌器,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播谐丢,決...
    沈念sama閱讀 40,776評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼爽航,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了乾忱?” 一聲冷哼從身側(cè)響起讥珍,我...
    開封第一講書人閱讀 39,671評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎窄瘟,沒想到半個月后衷佃,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,221評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡蹄葱,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,303評論 3 340
  • 正文 我和宋清朗相戀三年氏义,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片图云。...
    茶點故事閱讀 40,444評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡惯悠,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出竣况,到底是詐尸還是另有隱情克婶,我是刑警寧澤,帶...
    沈念sama閱讀 36,134評論 5 350
  • 正文 年R本政府宣布丹泉,位于F島的核電站情萤,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏摹恨。R本人自食惡果不足惜紫岩,卻給世界環(huán)境...
    茶點故事閱讀 41,810評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望睬塌。 院中可真熱鬧泉蝌,春花似錦、人聲如沸揩晴。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,285評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽硫兰。三九已至诅愚,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背违孝。 一陣腳步聲響...
    開封第一講書人閱讀 33,399評論 1 272
  • 我被黑心中介騙來泰國打工刹前, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人雌桑。 一個月前我還...
    沈念sama閱讀 48,837評論 3 376
  • 正文 我出身青樓喇喉,卻偏偏與公主長得像,于是被迫代替她去往敵國和親校坑。 傳聞我的和親對象是個殘疾皇子拣技,可洞房花燭夜當晚...
    茶點故事閱讀 45,455評論 2 359

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

  • 前言:本篇文章目的在于梳理知識,鞏固思想耍目,學(xué)習(xí)總結(jié)膏斤。有什么好的建議,都可以留言邪驮∧妫互相促進!總觀毅访,微信支付沮榜,也沒心思...
    麥穗0615閱讀 10,052評論 8 70
  • 一、背景介紹 作為一名Android開發(fā)俺抽,從最初的跌跌撞撞到現(xiàn)在小有所悟敞映,這其中經(jīng)歷過的辛酸苦辣也是一種痛并快樂著...
    freecats08閱讀 4,845評論 7 54
  • 引言 秋高氣爽振愿,天氣轉(zhuǎn)涼,正是學(xué)習(xí)工作做的好時候弛饭。(~ ̄▽ ̄)~~(~ ̄▽ ̄)~ 我是個phper最近在寫微信支付...
    恩就是這個名閱讀 7,974評論 2 15
  • 實現(xiàn)支付寶支付的準備工作: 1.向支付寶簽約冕末,成為支付寶的商戶 簽約完成后,支付寶會提供一些必要的數(shù)據(jù)給我們 商戶...
    Anson楊春安閱讀 8,213評論 0 6
  • 題記――我想記錄這段如火的青春侣颂,記錄這一段段屬于我記憶的小故事档桃。我不擅長寫文章,但我想用我的真情抒寫我的Z同學(xué)憔晒。 ...
    不問傾城色閱讀 197評論 0 0