reactNative 集成支付宝支付

一、android集成

1、下载支付宝sdk,在android/app下新建libs文件夹,将sdk放入此目录
sdk下载地址

2、将libs目录下的alipaySDK-20180403.aar导入,在android/app/build.gradle里添加如下代码:

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

2.5、在android/build.gradle添加如下:

allprojects {
     
    repositories {
     
        mavenLocal()
        flatDir {
                 //支付宝需要
            dirs 'libs'
        }
       ......
    }
}

3、在android/app/src/AndroidManifest.xml文件里面添加声明:

<!-- 支付宝权限声明 -->
<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、在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、在android/app/src/main/java/com/项目文件里面创建alipay文件夹,和微信支付一样,处理回调

6、编写 Module,在alipay包下创建AlipayModule.java,代码如下:

package com.test.alipay;                     //test是包名,根据不同项目进行修改

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();
  }

  // 添加沙箱模式
  @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、编写 Package,在alipay包下创建AlipayPackage.java,代码如下:

package  com.test.alipay;      //test是包名,根据不同项目进行修改

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、最后在 Android 这边要做的最后一件事就是注册这个模块,在MainApplication中注册模块:

import com.test.alipay.AlipayPackage;      //test是包名,根据不同项目进行修改
@Override
protected List<ReactPackage> getPackages() {
     
  @SuppressWarnings("UnnecessaryLocalVariable")
  List<ReactPackage> packages = new PackageList(this).getPackages();
  packages.add(new AlipayPackage());      // <-- 注册模块
  return packages;
}  

二、ios集成
1、进入ios目录,cmd输入命令pod install

2、下载sdk,将AlipaySDK.bundle,AlipaySDK.framework文件放入ios目录下,进入xcode中点击项目右键add file …导入这两个文件到项目中

3、在Build Phases选项卡的Link Binary With Libraries中,增加以下依赖:
reactNative 集成支付宝支付_第1张图片

  • 如果是Xcode 7.0之后的版本,需要添加libc++.tbd、libz.tbd;
    如果是Xcode 7.0之前的版本,需要添加libc++.dylib、libz.dylib。

4、在项目目录下创建Alipay文件夹,并创建AlipayMoudle模块,如下图所示:
reactNative 集成支付宝支付_第2张图片
5、编写AlipayModule.h代码如下:



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

6、编写AlipayModule.m代码如下:

#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;
    //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
    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、配置

应用注册scheme,在AliSDKDemo-Info.plist定义URL types
箭头所指的设置必须和上一步中的NSString *appScheme = @“alisdkdemo”;必须保持一致,
Identifler填写为alipay
reactNative 集成支付宝支付_第3张图片

8、编写调用原生模块的方法,调起支付宝支付-------调用

 import {
      NativeModules ,Platform} from 'react-native';
 async pay(payData) {
     
 // NativeModules.Alipay.setAlipaySandbox(true)          //沙箱---仅限于android
 NativeModules.Alipay.pay(payData).then((alipayData)=>{
     
            if(Platform.OS === 'ios'){
     
                if(alipayData.memo.ResultStatus==9000){
     
                    callback(alipayData)
                }
            }else{
     
                if(alipayData.resultStatus==9000){
     
                    callback(alipayData)
                }
            }
        })
 }

你可能感兴趣的:(reactNative,reactjs)