Recently, I have done a new project involving Alipay and wechat Payment. Both Alipay and wechat are big brothers in the industry. I believe we all feel that the documents and SDK are all pits (pure fun).

1. Wechat merchant application procedures kf.qq.com/faq/120911V… 2. After the application is successful that the official payment account documentation: pay.weixin.qq.com/wiki/doc/ap… Account Parameters:

The official document business processes: pay.weixin.qq.com/wiki/doc/ap… 3. Wechat payment integration open.weixin.qq.com/cgi-bin/sho… 1> Add wechat Pay SDK

4. The development steps The official development steps files: pay.weixin.qq.com/wiki/doc/ap… 1> Set the APPID of the project and add the APPID of the merchant in the project

After merchants apply for APP development on the wechat open platform, the wechat open platform will generate the unique identification APPID of the APP. Open the project in Xcode and set URL Schemes in the project properties to your APPID

2> iOS 9.0 or later, if you want to enable wechat normally, you need to add the whitelist in the plist file of the project

3 > developers need to link: in the engineering. SystemConfiguration framework, libz. Dylib, libsqlite3.0. Dylib, libc++. Dylib, Security. The framework, CoreTelephony framework, CFNetwork framework.

4> Select Build Setting in your project file, add **” -objc-all_load “** in “Other Linker Flags”, add libwechatsdK. a, wxapi. h in Search Paths, Wxapiobject.h, where the file is located

5> Register APPID merchant APP project to introduce wechat lib library and header file, before calling API, you need to register your APPID with wechat, the code is as follows:

// In appdelegate.m, Registered WeChat applications - (BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions: (launchOptions NSDictionary *) { WXApi registerApp:@"Your APPID"];
}
Copy the code

6> Activate the payment merchant server to generate payment orders. First call [Unified order API] to generate prepayment orders. After obtaining prepay_id, the parameters will be signed and transmitted to the APP to initiate payment. The following is the key code to activate wechat Pay: For security, the following fields are best obtained from the server

PayReq *request = [[PayReq alloc] init]; /** APPID -> APPID */ request.partnerId = APPID; /** prepayId = @ */ request.prepayid = @"1101000000140415649af9fc314aa427"; /** Merchants fill in data and signature according to Tenpay document < temporarily fill in fixed value Sign=WXPay>*/ request.package = @"Sign=WXPay"; /** nonceStr= @"a462b76e7436e98e0ed6e13c64b4fd1c"; /** Request. TimeStamp = @ "1397527777"; */ request.sign= @" */ request.sign= @"582282D72DD2B03AD892830965F428CB16E7A256"; / / [WXApi sendReq:request];Copy the code

7> Payment result callback According to wechat SDK Sample, the onResp function is implemented in the class. After the payment is completed, wechat APP will return to the merchant APP and call back the onResp function. The developer needs to receive notification in this function and return error code. Note: it must not be returned by the client as the result of the user’s payment, but by the payment notification received by the server or the result returned by the query API. A code example is as follows:

-(void)onResp:(BaseResp *)resp {if([resp isKindOfClass:[PayResp class]]){
      switch (resp.errCode) {
          case WXSuccess:{
             NSlog(@"Payment successful"); / / notice issued out of the payment successful outcome [[NSNotificationCenter defaultCenter] postNotificationName: QTXWXReturnSucceedPayNotification object:resp]; }break;
        default:{
            NSlog(@ "payment failed :%d", resp.errcode); / / notice issued out of the pay fail result [[NSNotificationCenter defaultCenter] postNotificationName: QTXWXReturnFailedPayNotification object: resp];  }break; }}}Copy the code

For specific use, let’s first put some of my code:

  1. Generally, wechat payment and Alipay payment will be integrated together, and we will organize and judge the callback together in appdelegate. m
*/ - (BOOL) Application (UIApplication *) Application openURL (NSURL *) URLsourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL result = [UMSocialSnsService handleOpenURL:url wxApiDelegate:nil];
    if(result == NO) {// Call other SDK Alipay // If the minimalist SDK is not available, alipay wallet will be redirected for payment, and the payment result of Alipay wallet needs to be sent back to SDKif ([url.host isEqualToString:@"safepay"] {// Jump to alipay wallet for payment, Handle payment results [[AlipaySDK defaultService] processOrderWithPaymentResult: url standbyCallback: ^ (NSDictionary * resultDic) { QTXLog(@"Alipay client payment result = %@",resultDic);
                if (resultDic && [resultDic objectForKey:@"resultStatus"] && ([[resultDic objectForKey:@"resultStatus"] intValue] = = 9000)) {/ / pay notice issued out of the successful results [QTXNotificationCenter postNotificationName: QTXAliReturnSucceedPayNotification object:resultDic]; }else{/ / notice issued out of the pay fail result [QTXNotificationCenter postNotificationName: QTXAliReturnFailedPayNotification object: resultDic]; }}]; }if ([url.host isEqualToString:@"platformapi"[[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {  QTXLog(@"Result = %@",resultDic);
                if (resultDic && [resultDic objectForKey:@"resultStatus"] && ([[resultDic objectForKey:@"resultStatus"] intValue] = = 9000)) {/ / pay notice issued out of the successful results [QTXNotificationCenter postNotificationName: QTXAliReturnSucceedPayNotification object:resultDic]; }else{/ / notice issued out of the pay fail result [QTXNotificationCenter postNotificationName: QTXAliReturnFailedPayNotification object: resultDic]; }}]; } // Wechat payment callbackif ([url.host isEqualToString:@"pay"]) {
            return[WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]]; }}return result;
}
Copy the code
// NOTE: - (BOOL)application (UIApplication *)app openURL (NSURL *)url options:(NSDictionary<NSString*, id> *)options { BOOL result = [UMSocialSnsService handleOpenURL:url];if(result == NO) {// Call other SDK Alipay // If the minimalist SDK is not available, alipay wallet will be redirected for payment, and the payment result of Alipay wallet needs to be sent back to SDKif ([url.host isEqualToString:@"safepay"] {// Jump to alipay wallet for payment, Handle payment results [[AlipaySDK defaultService] processOrderWithPaymentResult: url standbyCallback: ^ (NSDictionary * resultDic) { QTXLog(@"Alipay client payment result = %@",resultDic);
                if (resultDic && [resultDic objectForKey:@"resultStatus"] && ([[resultDic objectForKey:@"resultStatus"] intValue] = = 9000)) {/ / pay notice issued out of the successful results [QTXNotificationCenter postNotificationName: QTXAliReturnSucceedPayNotification object:resultDic]; }else{/ / notice issued out of the pay fail result [QTXNotificationCenter postNotificationName: QTXAliReturnFailedPayNotification object: resultDic]; }}]; }if ([url.host isEqualToString:@"platformapi"[[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {  QTXLog(@"Result = %@",resultDic);
                if (resultDic && [resultDic objectForKey:@"resultStatus"] && ([[resultDic objectForKey:@"resultStatus"] intValue] = = 9000)) {/ / pay notice issued out of the successful results [QTXNotificationCenter postNotificationName: QTXAliReturnSucceedPayNotification object:resultDic]; }else{/ / notice issued out of the pay fail result [QTXNotificationCenter postNotificationName: QTXAliReturnFailedPayNotification object: resultDic]; }}]; } // Wechat payment callbackif ([url.host isEqualToString:@"pay"]) {
            return[WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]]; }}return result;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return  [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}

Copy the code
  1. In the current controller using wechat Pay:
// Activate weChatPay, receive notifications, and determine whether weChatPay is installed on the phone. NSMutableDictionary *params = [NSMutableDictionary dictionary]; params[@"orderid"] = self.order;
    params[@"userIp"] = [QTXGetIPTool deviceIPAdress]; WeakSelf = self; __weak __typeof(self) weakSelf = self; [QTXHttpTool post:QTX_weChatPay_url params:params success:^(id json) { QTXLog(@"Wechat Pay return parameter interface request successful -%@", json);
        
        if ([json[@"success"] isEqual:@(YES)]) {
            
            NSMutableDictionary *wechatDic = json[@"data"];
            
          [WXApi registerApp:[wechatDic objectForKey:@"appid"]];
            PayReq *request = [[PayReq alloc] init];
            request.partnerId = [wechatDic objectForKey:@"mch_id"]; Request. PrepayId = [wechatDic objectForKey:@"prepay_id"]; // Pay the order request.package = @"Sign=WXPay"; Request. NonceStr = [wechatDic objectForKey:@"nonce_str"]; Request. TimeStamp = [[wechatDic objectForKey:@"timestamp"] intValue]; Request. Sign = [wechatDic objectForKey:@"sign2"]; // The merchants sign the data according to the wechat open platform documentif([WXApi sendReq:request]) { [QTXNotificationCenter addObserver:self selector:@selector(paySucceed) name:QTXWXReturnSucceedPayNotification object:nil]; [QTXNotificationCenter addObserver:self selector:@selector(payFailed) name:QTXWXReturnFailedPayNotification object:nil];  }elseQTXAlterView * ALTER = [[QTXAlterView alloc] initWithMessage:[NSString stringWithFormat:@"Wechat client is not installed, please use another payment method"] delegate:self rightButtonTitle:@"Sure"otherButtonTitles:nil]; [alter show]; }}else {
            [MBProgressHUD showError:[NSString stringWithFormat:@"% @", json[@"errorMessage"]]];
        }
        
        [weakSelf.tableView reloadData];
    } failure:^(NSError *error) {
        
        [MBProgressHUD showError:@"No network. Try again later."];
        QTXLog(@"Wechat pay return parameter interface request failed -%@", error);
    }];

}
Copy the code

Now the SDK of wechat Payment has been updated to 1.7.5, and I will update it at the same time. In fact, on the basis of the original version, only the following three points need to be added:

  1. Update iOS Enable ATS(App Transport Security)
  2. CFNetwork. Framework needs to be linked in the project
  3. – added “-objc-all_load” to “Other Linker Flags” in project configuration

If you need alipay payment integration, please go to iOS Alipay payment integration