比較簡單餐济,只做一個筆記耘擂,并于以后查詢
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
祝成功~~??