Go to: https://cainluo.github.io/14735762460993.html


The author testimonials

As apps become more and more commercialized, many companies will integrate third-party payment SDK with their apps, which will cost less. However, many friends still don’t know how to integrate and don’t like to see integrated documents (I am also ~). Or write an article about payment, now write is ** wechat payment, over a period of time to Pay alipay, Unionpay, **Apple Pay** also make up.

Finally: If you have better suggestions or dissatisfaction with this article, please contact me, I will refer to your opinions and then modify, when contacting me, please note WeChat payment if you feel good, I hope you can also give a reward ~ hee hee ~ WISH you a happy learning ~ thank you ~


Introduction to the

Wechat SDK, an SDK that integrates social sharing and Tenpay payment functions, requires merchants to register on the wechat open platform first, and then obtain the merchant ID after approval. In this way, they can use the payment function. Let’s take a look below.


The preparatory work

First, let’s prepare:

  • 1. Apply for a merchant ID
  • 2. Apply for an App ID
  • 3. Download and integrate the SDK package
  • 4. Add a dependency package
  • 5. Finally, tune up payments

Do the above work, wechat SDK integration will come to an end ~


Apply for merchant ID

Here is not to do a detailed introduction, after all, what we are talking about here is how to integrate SDK, if you want to know about children’s shoes, you can go to ** wechat public platform ** by yourself check ha ~


To apply for the App ID

Application for **App ID here is not introduced, this step is also very simple, go directly to wechat open platform, according to the corresponding guidance information, step by step to fill in the OK, wechat App ID** is required to review time, fast a few minutes, slow, slowly wait for it ~~


Download the SDK package

Download the SDK package, this is more simple, go directly to the ** resource center to see the iOS development kit 64-bit ** immediately click download directly,

Once the download is complete, let’s take a look at what’s in the SDK package

I looked at the Demo version 2.0, but there was no relevant code for wechat payment in it, which was quite painful, if it was the first integration of children’s feet, they would cry… But the good news is that we can solve these problems with the huge Internet search engines, Google, Baidu,


One more paragraph

We will create a **WorkSpace file called PayProject, and then we will create our first project wechatPay-Objective-C. Why there is no Swift version? In fact, it is not because I want to write Swift version, but because its grammar has not been finalized until now. It is painful to change every version. Then you can modify it according to your own programming experience and Xcode** tips


The configuration of engineering

Open the ** wechatPay-Objective-C project we created and drag the SDK package in. I changed the name of the folder here, you can change it to your own preference

After adding the **SDK package, we still have some things to do, because after iOS 9, Apple restricted normal HTTP requests, so if we want to continue using it, we have to configure it first. There is also a statement in the SDK folder of wechat

Open the project, find the ** info.plist ** file of the project, and add it directly. Sometimes Xcode will not prompt you, so you need to fill it manually

  • Application requires iPhone environment
  • LSApplicationQueriesSchemes
  • App Transport Security Settings
    • Allow Arbitrary Loads

We need to add **URL Schemes. Here I provide App ID of wXB4ba3c02AA476eA1 which is copied from the official wechat Demo. Please copy and paste it automatically. We are going to go to project configuration and add wechat URL access Schemes**

At this point, basically this stage has come to an end, continue to the next stage ~~~


Adding a dependency package

One of the most painful things about using third-party SDK is that you need to add a lot of dependency packages, because the third party needs to do data collection, or other operations, so that you can query your App traffic in their background list. There are several dependency packages for wechat.

  • UIKit.framework
  • Foundation.framework
  • SystemConfiguration.framework
  • CoreTelephony.framework
  • Security.framework
  • libz.tbd
  • libc++.tbd
  • libsqlite3.tbd



Now let’s add these dependency packages. How do I add them? 0.0


Registered AppID

First of all, we must register wechat **App ID first, otherwise, let alone pay, you can not even share what function, open appdelegate. m, import wxapi.h file, Register your App ID, and this App ID is the one THAT I just provided.


The UI layout

To activate wechat pay, we must have a click event. For the **UI, we just give a UIButton and an Action event.


Turn on wechat Pay

The highlight comes, the front to do so much work, write so much nonsense, just for now the real tune up wechat pay to pay ~~

The implementation code is posted for you ~ I copied it from the previous official Demo ~

PS: This is Demo, so what signature ah, merchant ID, payment link and so on, are written in the client, but in the actual development, this is strongly not recommended to generate in the client, must be returned by the server, otherwise you will have a very deep understanding of the meaning of the word “egg pain” ~~

    NSString *urlString = @"http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=ios";
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:queue
                           completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
                               
                               if(data ! =nil) {
                                   
                                   NSError *error;
                                   NSMutableDictionary *dictionart = NULL;
                                   
                                   dictionart = [NSJSONSerialization JSONObjectWithData:data
                                                                          options:NSJSONReadingMutableLeaves
                                                                            error:&error];
                                   
                                   NSLog(@"URL: %@", urlString);
                                   
                                   if(dictionart ! =nil) {
                                       
                                       NSMutableString *retCode = [dictionart objectForKey:@"retcode"];
                                       
                                       if (retCode.integerValue == 0) {
                                           
                                           NSMutableString *stamp = [dictionart objectForKey:@"timestamp"];
                                           
                                           // Activate wechat Pay
                                           PayReq *req   = [[PayReq alloc] init];
                                           req.partnerId = [dictionart objectForKey:@"partnerid"];
                                           req.prepayId  = [dictionart objectForKey:@"prepayid"];
                                           req.nonceStr  = [dictionart objectForKey:@"noncestr"];
                                           req.timeStamp = stamp.intValue;
                                           req.package   = [dictionart objectForKey:@"package"];
                                           req.sign      = [dictionart objectForKey:@"sign"];
                                           
                                           [WXApi sendReq:req];
                                           
                                           // Log output
                                           NSLog(@"appid = %@", [dictionart objectForKey:@"appid"]);
                                           NSLog(@"partnerId = %@", req.partnerId);
                                           NSLog(@"prepayId = %@", req.prepayId);
                                           NSLog(@"nonceStr = %@", req.nonceStr);
                                           NSLog(@"timeStamp = %d", req.timeStamp);
                                           NSLog(@"package = %@", req.package);
                                           NSLog(@"sign = %@", req.sign);
                                           
                                       } else {
                                           
                                           NSLog(@"retmsg: %@", [dictionart objectForKey:@"retmsg"]); }}else {
                                       
                                       NSLog(@" Server returned error, did not get JSON object"); }}else {
                                   
                                   NSLog(@" Server returned error"); }}];Copy the code

Process callback results

Now we need to deal with the result of wechat callback. Whether you pay successfully or fail, or wechat server explosion, we need to obtain this result, and the corresponding **errCode. To open appDelegate. m, we’ll add wechat’s delegate protocol, implement a wechat delegate method, and two methods of AppDelegate**

Concrete implementation of the code

- (void)onResp:(BaseResp *)resp {
    
    if ([resp isKindOfClass:[PayResp class]]) {
        
        NSString *stringMessage = @" Payment result";
        NSString *stringTitle  = @" Payment result";
        
        switch (resp.errCode) {
            case WXSuccess:
                
                stringMessage = "Payment result: success!";
                
                NSLog(RetCode = %d", resp.errCode);
                
                break;
            default:
                
                stringMessage = [NSString stringWithFormat:Payment result: failed! , retcode = %d, retstr = %@", resp.errCode, resp.errStr];
                
                break;
        }
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:stringTitle
                                                            message:stringMessage
                                                           delegate:nil
                                                  cancelButtonTitle:@ "good"
                                                  otherButtonTitles:nil.nil]; [alertView show]; }} - (BOOL)application:(UIApplication *)application
      handleOpenURL:(NSURL *)url {
    
    return [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    return [WXApi handleOpenURL:url delegate:self];
}
Copy the code

The final result


The project address

The address of the project: https://github.com/CainRun/PayProject


The last