iOS WeChat payment development (latest version)

1 Introduction

This article is a summary of the previous projects. Due to the relevant payment SDK iteration, the original text has not met the needs. The following updates are made for your reference. In addition, a summary of common problems has been added .

The payment function needs to be used in the project, which requires Alipay payment, WeChat payment, UnionPay payment, Apple_pay, so I intend to summarize it to facilitate future reference, and it is also convenient for everyone to avoid being pitted again where it is used.

Today we will mainly introduce WeChat Pay, and other payment introductions will be updated as soon as possible.

Before integration, you must first look at the documentation. The WeChat payment development documentation has detailed fields and instructions.
WeChat Pay requires a signature. Like Alipay, it can be signed on the client side or in the background (Of course, it is recommended to sign on the server for security, and the logic is better to understand)

Source code acquisition

Follow the official account " Wangluo Development " and reply " Alipay Pay " to receive

Add WeChat: FBY-fan receives 45 e-books

2. Business Process

The following is the interaction sequence diagram. The unified order API, payment result notification API, and order query API all involve the signature process, and the calls must be completed on the merchant server.

Interaction sequence diagram

Main interaction instructions between merchant system and WeChat payment system:

    1. The user selects the product in the merchant APP, submits the order, and selects WeChat payment.
    1. The merchant's backend receives the user's payment order and calls the WeChat payment unified ordering interface.
    1. The unified order interface returns the normal prepay_id, and then regenerates the signature according to the signature specification, and then transmits the data to the APP. The fields participating in the signature are appid, partnerid, prepayid, noncestr, timestamp, package.
    1. Merchant APP launched WeChat payment.
    1. The merchant background receives the payment notification.
    1. The merchant backstage inquires the payment result.

3. Download WeChat SDK

If you integrate the WeChat in Umeng Sharing, you do not need to download or configure the environment, because you have already configured the WeChat payment environment when configuring Umeng Sharing (including framework, schema jump, whitelist). If not If you have integrated Umeng sharing, please go to the WeChat open platform to download the SDK .

Download WeChat SDK

It is recommended to download both the iOS header files and payment examples

4. Import library integration SDK

4.1 Import SDK library

Import the SDK package downloaded from the iOS header file and library download above, and then you need to link to the dependent library. In Target —> BuildPhases —> Link Binary With Libraries — click the + sign -> search for the system library you need.

  • SystemConfiguration.framework
  • libz.tbd
  • libsqlite3.0.tbd
  • CoreTelephony.framework
  • QuartzCore.framework

Import SDK library

4.2 Set URL Scheme

After a merchant applies to develop an APP application on the WeChat open platform, the WeChat open platform will generate the unique identification APPID of the APP. It is clearly stated in the APP development steps , and it needs to be filled in the URL Schemes.

URL Scheme

4.3 Register APPID in Appdelegate

First, reference the header file in Appdelegate

//微信支付
#import "WXApi.h"

Then register the APPID

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

//    向微信终端注册ID

    [WXApi registerApp:@"wxd930ea5d5a258f4f"];
    
    return YES;
}

After the payment is successful, the payment result is returned, and the URL needs to be obtained, and it also needs to be completed in Appdelegate. The code is as follows:

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付,处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
    }else if ([url.host isEqualToString:@"pay"]) {
        // 处理微信的支付结果
        [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付,处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
    }else if ([url.host isEqualToString:@"pay"]) {
        // 处理微信的支付结果
        [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}

The method that comes with the WeChat SDK handles the callback method after completing the operation from the WeChat client and returning to the program, displaying the payment result:

-(void) onResp:(BaseResp*)resp
{
    //启动微信支付的response
    NSString *payResoult = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果,实际支付结果需要去微信服务器端查询
        switch (resp.errCode) {
            case 0:
                payResoult = @"支付结果:成功!";
                break;
            case -1:
                payResoult = @"支付结果:失败!";
                break;
            case -2:
                payResoult = @"用户已经退出支付!";
                break;
            default:
                payResoult = [NSString stringWithFormat:@"支付结果:失败!retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                break;
        }
    }
}

4.4 Call payment interface

In calling the WeChat payment class, first add a header file reference.

#import "WXApi.h"

In the method of invoking payment, the parameters that need to be uploaded include: appid, partid (merchant number), prepayid (prepayment order ID), noncestr (random character string participating in the signature), timestamp (time stamp participating in the signature), sign (Signature string) These six.
Use the core code in the click-to-pay controller to call up WeChat client payment. These parameters are passed to you in the background. Added comments, it should be easy to understand. code show as below:

#pragma mark 微信支付方法
- (void)WechatPay{
    
    //需要创建这个支付对象
    PayReq *req   = [[PayReq alloc] init];
    //由用户微信号和AppID组成的唯一标识,用于校验微信用户
    req.openID = appid;
    // 商家id,在注册的时候给的
    req.partnerId = partnerid;
    // 预支付订单这个是后台跟微信服务器交互后,微信服务器传给你们服务器的,你们服务器再传给你
    req.prepayId  = prepayid;
    // 根据财付通文档填写的数据和签名
    req.package  = package;
    // 随机编码,为了防止重复的,在后台生成
    req.nonceStr  = noncestr;
    // 这个是时间戳,也是在后台生成的,为了验证支付的
    NSString * stamp = timestamp;
    req.timeStamp = stamp.intValue;
    // 这个签名也是后台做的
    req.sign = sign;
    //发送请求到微信,等待微信返回onResp
    [WXApi sendReq:req];
    
}

4.5 Determine whether the mobile phone is installed with WeChat client

After calling the encapsulated class method where WeChat payment is needed, it will jump to the WeChat app. If it is not installed, there will be no response. It should be noted here that because WeChat is not installed, it is necessary to provide a webview to log in to WeChat to pay, otherwise Apple will refuse to put the application on the shelf. But WeChat does not come with a webview, (Alipay comes with it), so it is necessary to determine whether the user has installed WeChat. If WeChat is not installed, the WeChat payment button will not be displayed.

// 判断手机有没有微信
    if ([WXApi isWXAppInstalled]) {
        wechatButton.hidden = NO;
    }else{
        wechatButton.hidden = YES;
    }

At this point, WeChat payment is basically completed. If you encounter any problems during the integration process, you can leave a message to me or add qq to help you solve it online.

5. Common problem solving

5.1 Cannot return to the App after payment

If you stay on WeChat after the payment is completed, check the Scheme setting in URLType.

5.2 Parameters expired

Able to open the WeChat client, but there is only a white "OK button" in the middle after it is opened. After clicking it, it will return to the client. If this is the case, it should be a problem with the prepayid parameter, which has expired, or is not the real id.

5.3 The unit of WeChat payment is cents

5.4 The program did not find the SDK library

Project ->build setttings -> search for other linker flags and add -Objc -all_load, running the project may crash because the program does not find the SDK library.

5.5 Whitelist

The payment can be adjusted without configuring the white list. If the payment cannot be adjusted, check whether it is a white list problem.

Open the info.plist file in the project, add the LSApplicationQueriesSchemes array and add the wechat and weixin strings.

Or right-click info.plist -> source code to open and add the following code

<key>LSApplicationQueriesSchemes</key>
<array><string>wechat</string>
  <string>weixin </string>
</array>

5.6 Project error with Chinese name

The project with the Chinese name will report this error, but the English name will not. This is because the UIKit library is missing. Import the library #import <UIKit/UIKit.h> in WXApiObject.h.

5.7 Cannot find the corresponding compiled package

The problem of Wechat SDK, the corresponding compiled package could not be found, import libc++ to solve it

Get the source code method: follow " Web Development " and reply " WeChat Pay " to get the link

Guess you like

Origin blog.csdn.net/qq_36478920/article/details/113098032