reactNative Integrated Alipay Payment

1. android Integration

1. Download Alipay sdk, create a new libs folder under android/app, put SDK in this directory
sdk download address

2. Import alipaySDK-20180403.aar from the libs directory and add the following code in android/app/build.gradle:

dependencies {
     ......
     compile (name: 'alipaySdk-15.6.8-20191021122514', ext: 'aar') 
     .....
}

3. Add a declaration to the android/app/src/AndroidManifest.xml file:

<!-- Alipay Rights Statement -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

4. Add confusion rules in android/app/proguard-rules.pro

-keep class com.alipay.android.app.IAlixPay{*;}
-keep class com.alipay.android.app.IAlixPay$Stub{*;}
-keep class com.alipay.android.app.IRemoteServiceCallback{*;}
-keep class com.alipay.android.app.IRemoteServiceCallback$Stub{*;}
-keep class com.alipay.sdk.app.PayTask{ public *;}
-keep class com.alipay.sdk.app.AuthTask{ public *;}
-keep class com.alipay.sdk.app.H5PayCallback {
 <fields>;
 <methods>;
}
-keep class com.alipay.android.phone.mrpc.core.** { *; }
-keep class com.alipay.apmobilesecuritysdk.** { *; }
-keep class com.alipay.mobile.framework.service.annotation.** { *; }
-keep class com.alipay.mobilesecuritysdk.face.** { *; }
-keep class com.alipay.tscenter.biz.rpc.** { *; }
-keep class org.json.alipay.** { *; }
-keep class com.alipay.tscenter.** { *; }
-keep class com.ta.utdid2.** { *;}
-keep class com.ut.device.** { *;}

5. Create an alipay folder in the android/app/src/main/java/com/project file to handle callbacks just like WeChat payment

6. Write a Module and create AlipayModule.java under the alipay package with the following code:

package com.test.alipay;                     //test is the package name, modified according to different projects

import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.H5PayCallback;
import com.alipay.sdk.util.H5PayResultModel;
import com.alipay.sdk.app.AuthTask;
import com.alipay.sdk.app.PayTask;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;

import java.util.Map;

public class AlipayModule extends ReactContextBaseJavaModule {

  private final ReactApplicationContext reactContext;

  public AlipayModule(ReactApplicationContext reactContext) {
    super(reactContext);
    this.reactContext = reactContext;
  }

  @Override
  public String getName() {
    return "RCTAlipay";
  }

  @ReactMethod
  public void authWithInfo(final String infoStr, final Promise promise) {
    Runnable runnable = new Runnable() {
      @Override
      public void run() {
        AuthTask authTask = new AuthTask(getCurrentActivity());
        Map<String, String> map = authTask.authV2(infoStr, true);
        promise.resolve(getWritableMap(map));
      }
    };
    Thread thread = new Thread(runnable);
    thread.start();
  }

  // Add Sandbox Mode
  @ReactMethod
  public void setAlipaySandbox(Boolean isSandbox) {
    if(isSandbox){
      EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
    }else {
      EnvUtils.setEnv(EnvUtils.EnvEnum.ONLINE);
    }
  }

  @ReactMethod
  public void pay(final String orderInfo, final Promise promise) {
    Runnable runnable = new Runnable() {
      @Override
      public void run() {
        PayTask payTask = new PayTask(getCurrentActivity());
        Map<String, String> map = payTask.payV2(orderInfo, true);
        promise.resolve(getWritableMap(map));
      }
    };
    Thread thread = new Thread(runnable);
    thread.start();
  }

  @ReactMethod
  public void payInterceptorWithUrl(final String h5PayUrl, final Promise promise) {
    PayTask payTask = new PayTask(getCurrentActivity());
    payTask.payInterceptorWithUrl(h5PayUrl, true, new H5PayCallback() {
      @Override
      public void onPayResult(H5PayResultModel h5PayResultModel) {
        WritableMap map = Arguments.createMap();
        map.putString("resultCode", h5PayResultModel.getResultCode());
        map.putString("returnUrl", h5PayResultModel.getReturnUrl());
        promise.resolve(map);
      }
    });
  }

  @ReactMethod
  public void getVersion(Promise promise) {
    PayTask payTask = new PayTask(getCurrentActivity());
    promise.resolve(payTask.getVersion());
  }

  private WritableMap getWritableMap(Map<String, String> map) {
    WritableMap writableMap = Arguments.createMap();
    for (Map.Entry<String, String> entry : map.entrySet()) {
      writableMap.putString(entry.getKey(), entry.getValue());
    }
    return writableMap;
  }
}

7. Write a Package and create AlipayPackage.java under the alipay package with the following code:

package  com.test.alipay;      //test is the package name, modified according to different projects

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class AlipayPackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
      return Arrays.<NativeModule>asList(new AlipayModule(reactContext));
    }

    // Deprecated from RN 0.47
    public List<Class<? extends JavaScriptModule>> createJSModules() {
      return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
      return Collections.emptyList();
    }
}

8. The last thing to do on Android side is to register this module and register the module in MainApplication:

import com.test.alipay.AlipayPackage;      //test is the package name, modified according to different projects
@Override
protected List<ReactPackage> getPackages() {
  @SuppressWarnings("UnnecessaryLocalVariable")
  List<ReactPackage> packages = new PackageList(this).getPackages();
  packages.add(new AlipayPackage());      // <--Registration module
  return packages;
}  

Ii. ios integration
1. Enter ios directory, cmd input command pod install

2. Download the sdk, put the AlipaySDK.bundle, AlipaySDK.framework file into the ios directory, enter the xcode, right-click the project add file...Import these two files into the project

3. In LinBinary With Libraries on the Build Phases tab, add the following dependencies:

  • If it is after Xcode 7.0, you need to add libc++.tbd, libz.tbd;
    If it is a version prior to Xcode 7.0, you need to add libc++.dylib, libz.dylib.

4. Create an Alipay folder under the project directory and an AlipayMoudle module, as shown below:

5. Write the AlipayModule.h code as follows:


#import <React/RCTBridgeModule.h>
   #import <React/RCTLog.h>
   @interface AlipayMoudle : NSObject <RCTBridgeModule>
   
@end

6. Write the following AlipayModule.m code:

#import <Foundation/Foundation.h>
#import "AlipayModule.h"
#import <AlipaySDK/AlipaySDK.h>
#import <React/RCTEventDispatcher.h>
#import <React/RCTBridge.h>
#import <React/RCTLog.h>
#import <React/RCTImageLoader.h>

@implementation AlipayMoudle{
  RCTPromiseResolveBlock relustBlock;
}
@synthesize bridge = _bridge;
- (instancetype)init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleOpenURL:) name:@"RCTOpenURLNotification" object:nil];
    }
    return self;
}


   RCT_EXPORT_METHOD(pay:(NSString *)orderInfo
    resolver:(RCTPromiseResolveBlock)resolve
    rejecter:(RCTPromiseRejectBlock)reject){
     relustBlock = resolve;
    //Apply registration scheme to define URL types in AliSDKDemo-Info.plist
    NSString *appScheme = @"alisdkdemo";
     if ([NSThread isMainThread]) {
       [[AlipaySDK defaultService] payOrder:orderInfo fromScheme:appScheme callback:^(NSDictionary *resultDic) {
         resolve(resultDic);
       }];
     }else{
       dispatch_async(dispatch_get_main_queue(), ^{
         [[AlipaySDK defaultService] payOrder:orderInfo fromScheme:appScheme        callback:^(NSDictionary *resultDic) {
           resolve(resultDic);
         }];
       });
     }
    
 }

- (BOOL)handleOpenURL:(NSNotification *)aNotification
{
    NSString * aURLString =  [aNotification userInfo][@"url"];
  if (![aURLString containsString:@"alisdkdemo"]) {
    return NO;
  }
    NSArray *relustArr = [aURLString componentsSeparatedByString:@"?"];
  if (relustArr.lastObject) {
    NSString *jsonStr = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,(__bridge CFStringRef)relustArr.lastObject,CFSTR(""),CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];

    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:nil];
    relustBlock(dict);
  }
  return YES;
}


 
RCT_EXPORT_MODULE(Alipay);
 
@end

7. Configuration

Apply registration scheme to define URL types in AliSDKDemo-Info.plist
The settings indicated by the arrow must be the same as NSString *appScheme = @ "alisdkdemo" in the previous step; they must be consistent,
Identifler is filled in as alipay

8. Write a method to call the native module and invoke Alipay Payment-------Call

import { NativeModules ,Platform} from 'react-native';
async pay(payData) {
NativeModules.Alipay.pay(payData).then((alipayData)=>{
if(Platform.OS === 'ios'){
if(alipayData.memo.ResultStatus9000){
callback(alipayData)
}
}else{
if(alipayData.resultStatus9000){
callback(alipayData)
}
}
})
}

8 original articles published. 6. 783 visits
Private letter follow

Tags: Android React SDK Java

Posted on Sat, 01 Feb 2020 23:20:34 -0500 by jrough