1. 注冊WX_AppID
微信開放平臺 -- 注冊WX_AppID
2. 下載WX_PaySDK
下載完成之后,拖入工程中。
微信支付SDK.png
3. 添加SDK依賴的系統(tǒng)庫文件
1. 需要在Link Binary With Libraries中添加的庫文件
添加庫文件.png
庫文件.png
2. 配置URL Schemes
配置URL Schemes.png
4. 需在 AppDelegate.h 中實現(xiàn)的方法
1. 需要重寫兩個方法
#pragma mark - ----- 重寫這兩個的方法
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
{
// 跳轉(zhuǎn)到URL scheme中配置的地址
//NSLog(@"跳轉(zhuǎn)到URL scheme中配置的地址-->%@",url);
return [WXApi handleOpenURL:url delegate:self];
}
//支付成功時調(diào)用,回到第三方應(yīng)用中
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
// NSLog(@"****************url.host -- %@",url.host);
if ([url.scheme isEqualToString:WX_APP_ID])
{
return [WXApi handleOpenURL:url delegate:self];
}
return NO;
}
2. 添加微信的支付結(jié)果回調(diào)方法
- (void)onResp:(BaseResp *)resp {
// 支付結(jié)果回調(diào)
if([resp isKindOfClass:[PayResp class]]){
switch (resp.errCode) {
case WXSuccess:{
//支付返回結(jié)果,實際支付結(jié)果需要去自己的服務(wù)器端查詢
[[NSNotificationCenter defaultCenter] postNotificationName:@"WX_PaySuccess" object:nil];
}
break;
case WXErrCodeCommon:
{ //簽名錯誤、未注冊APPID、項目設(shè)置APPID不正確、注冊的APPID與設(shè)置的不匹配、其他異常等
// [MBProgressHUD showError:@"支付失敗"];
NSLog(@"支付失敗");
[[NSNotificationCenter defaultCenter]
postNotificationName:@"WX_PayFail" object:nil];
}
break;
case WXErrCodeUserCancel:
{ //用戶點擊取消并返回
NSLog(@"取消支付");
[[NSNotificationCenter defaultCenter]
postNotificationName:@"WX_PayCancle" object:nil];
// [MBProgressHUD showError:@"取消支付"];
}
break;
case WXErrCodeSentFail:
{ //發(fā)送失敗
NSLog(@"發(fā)送失敗");
[[NSNotificationCenter defaultCenter]
postNotificationName:@"WX_PayFail" object:nil];
// [MBProgressHUD showError:@"發(fā)送失敗"];
}
break;
case WXErrCodeUnsupport:
{ //微信不支持
NSLog(@"微信不支持");
[[NSNotificationCenter defaultCenter]
postNotificationName:@"WX_PayFail" object:nil];
// [MBProgressHUD showError:@"微信不支持"];
}
break;
case WXErrCodeAuthDeny:
{ //授權(quán)失敗
NSLog(@"授權(quán)失敗");
[[NSNotificationCenter defaultCenter]
postNotificationName:@"WX_PayFail" object:nil];
// [MBProgressHUD showError:@"授權(quán)失敗"];
}
break;
default:
break;
}
}
}
5. 微信支付
#pragma mark - ----- 微信支付
- (IBAction)wx_pay:(id)sender {
/**
應(yīng)用ID,商戶號,隨機字符串,簽名,商品描述,商品訂單號,總金額,
用戶端實際ip,通知地址,交易類型,商戶密鑰
*/
NSString *appid,*mch_id,*nonce_str,*sign,*body,*out_trade_no,*total_fee,
*spbill_create_ip,*notify_url,*trade_type,*partner;
// 需要自己填寫
appid = WX_AppId;
mch_id = MCH_ID;
partner = WX_PartnerKey;
//產(chǎn)生隨機字符串,這里最好使用和安卓端一致的生成邏輯
nonce_str = [self generateTradeNO];
body = @"Mac Book Pro 15寸 256G";
//隨機產(chǎn)生訂單號用于測試,正式使用請換成你從自己服務(wù)器獲取的訂單號
out_trade_no = [self getOrderNumber];
//交易價格1表示0.01元,10表示0.1元
total_fee = @"1";
//獲取本機IP地址,請再wifi環(huán)境下測試,否則獲取的ip地址為error,正確格式應(yīng)該是8.8.8.8
spbill_create_ip =[getIPhoneIP getIPAddress];
//交易結(jié)果通知網(wǎng)站此處用于測試,隨意填寫,正式使用時填寫正確網(wǎng)站
notify_url = @"www.baidu.com";
trade_type = @"App";
// 獲取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 *dict = [NSMutableDictionary dictionary];
[dict setValue:appid forKey:@"appid"];//公眾賬號ID
[dict setValue:mch_id forKey:@"mch_id"];//商戶號
[dict setValue:nonce_str forKey:@"nonce_str"];//隨機字符串
[dict setValue:sign forKey:@"sign"];//簽名
[dict setValue:body forKey:@"body"];//商品描述
[dict setValue:out_trade_no forKey:@"out_trade_no"];//訂單號
[dict setValue:total_fee forKey:@"total_fee"];//金額
[dict setValue:spbill_create_ip forKey:@"spbill_create_ip"];//終端IP
[dict setValue:notify_url forKey:@"notify_url"];//通知地址
[dict setValue:trade_type forKey:@"trade_type"];//交易類型
NSString *xmlString = [dict XMLString];
[self http:xmlString];
}
- (void)http:(NSString *)xml {
//這里傳入的xml字符串只是形似xml,但是不是正確是xml格式,需要使用af方法進(jìn)行轉(zhuǎn)義
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
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:WX_PAY_URL parameters:xml success:^(NSURLSessionDataTask *task, id responseObject) {
NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"\n\nresponseString is %@\n\n",responseString);
NSDictionary *dict = [NSDictionary dictionaryWithXMLString:responseString];
//判斷返回的許可
if ([[dict objectForKey:@"result_code"] isEqualToString:@"SUCCESS"] && [[dict objectForKey:@"return_code"] isEqualToString:@"SUCCESS"] ) {
//配置調(diào)起微信支付所需要的參數(shù)
PayReq *request = [[PayReq alloc] init];
request.openID = [dict objectForKey:@"appid"];
// NSLog(@"-%@-",request.openID);
request.partnerId = [dict objectForKey:@"mch_id"];
// NSLog(@"--%@--",request.partnerId);
request.prepayId= [dict objectForKey:@"prepay_id"];
// NSLog(@"---%@---",request.prepayId);
request.package = @"Sign=WXPay";
// NSLog(@"----%@----",request.package);
request.nonceStr= [dict objectForKey:@"nonce_str"];
// NSLog(@"-----%@-----",request.nonceStr);
//將當(dāng)前事件轉(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];
}else{
NSLog(@"參數(shù)不正確,請檢查參數(shù)");
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"error is %@",error);
}];
}