Android accepts Alipay to pay

The official document: opendocs.alipay.com/open/204/10…

The document also has the corresponding Demo code, but it is Android Native code, which needs to be modified if you want to call it on React Native.

So here’s how to connect to the payment SDK on React Native.

1. Import Alipay SDK

Download link: opendocs.alipay.com/open/54/104…

Alipaysdk-standard-15.8.03.3 alipaySDK-standard-15.8.03.3

1. After downloading the SDK, put the AliPaySDK-15.8.03.210428205839. Aar in the file (this is only the SDK version I have downloaded at present, the actual file will be subject to the downloaded file) into the liBS directory of the project (if there is no such directory, create a new one by yourself) :

Build. Gradle in the Android directory and add the following content to the libs directory as a dependency repository:

// Add the following content flatDir {dirs' repositories'} //... Jcenter () and other repositories}Copy the code

3. Add the following content in build.gradle under app directory to rely on alipay SDK for the project:

Implementation (name: 'alipaySDK-15.8.03.210428205839. Aar ', ext: 'aar') // ... Other dependencies}Copy the code

2. Modify the run permission

Androidmanifest.xml in Android /app/ SRC /main has the following 3 permissions:

android.permission.INTERNET
android.permission.ACCESS_NETWORK_STATE
android.permission.ACCESS_WIFI_STATE
Copy the code

3. Write and call alipay payment interface

You can refer to my project catalog. Since my project needs to connect Alipay and wechat Payment, I write the payment modules together and separate Alipay and wechat separately.

Create a pay package, then create an Alipay package, create a new Alipay. Java file:

2. Copy payresult. Java to pay/ Alipay directory in the downloaded Demo:

3. Write the AliPay. Java file

Import the following packages at the beginning of the file:

packagePay. Alipay;importOwn package name.R;import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import java.util.Map;
import com.alipay.sdk.app.PayTask;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
Copy the code

Then write the main business code:

public class AliPay extends ReactContextBaseJavaModule {
    private static ReactApplicationContext reactContext;
    public static Promise promise;

    public AliPay(ReactApplicationContext context) {
        super(context);
        reactContext = context;
    }

    private static final int SDK_PAY_FLAG = 1;

    / * * * ReactContextBaseJavaModule getName method to realize requirements derived class. * This function returns a string name that marks the module on the JavaScript side. * Here we call this module AliPay so that it can be accessed in JavaScript via * NativeModules.AliPay. * /
    @Override
    public String getName(a) {
        return "AliPay";
    }

    /** * Payment result acquisition and processing * After the payment, a Toast will pop up to show the result, but it is not known whether the order has been successfully paid. * For the payment result, merchants are requested to rely on the asynchronous notification result of the server. * * Here are the key points: Private Handler mHandler = new Handler(looper.getMainLooper ()) * Private Handler mHandler = new Handler() * However, running on RN will cause an error, which probably means that a handle cannot be created on this thread. The solution is to pass looper.getMainLooper () */ to the constructor
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /** * For the payment result, please rely on the asynchronous notification result of the server. Synchronizes notification results as notification of end of payment only. * /
                    String resultInfo = payResult.getResult();// Synchronization returns the information to be validated
                    String resultStatus = payResult.getResultStatus();
                    / / resultStatus pay for 9000 represents success, specific resultStatus results code meaning see https://opendocs.alipay.com/open/204/105301
                    AliPay.promise.resolve(resultStatus);
                    break;
                }
                default:
                    break; }}; };/** * payV2 payV2 payV2 payV2 payV2 payV2 payV2 payV2 payV2 payV2 payV2 payV2@params{String} orderInfo back end returns the order data to you */
    @ReactMethod
    public void payV2(String orderInfo, Promise promise) {
        AliPay.promise = promise;

        final Runnable payRunnable = new Runnable() {
            @Override
            public void run(a) {
                PayTask alipay = new PayTask(getCurrentActivity());
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = newMessage(); msg.what = SDK_PAY_FLAG; msg.obj = result; mHandler.sendMessage(msg); }};// Must be called asynchronously
        Thread payThread = newThread(payRunnable); payThread.start(); }}Copy the code

4. Registration module

After writing the payment module, you need to register the module. If you do not register the module, you will not be able to access the module in JS.

Create a new Java class in the /pay directory and name it PayPackage

The specific code is as follows:

packageOwn package name. Pay;importPay. Alipay. Alipay;import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class PayPackage implements ReactPackage {

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

    @Override
    public List<NativeModule> createNativeModules( ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();

        /** * Register module */ here
        // Pay by AliPay. This ApiPay is AliPay
        modules.add(new AliPay(reactContext));

        returnmodules; }}Copy the code

5. Export modules

Once a module is registered, it needs to be exported so that NativeModules can be accessed in React Native.

In android/app/SRC/main/Java/com/your application name/MainApplication. Add the following code in Java:

// MainApplication.java.importOwn package name.PayPackage;// <-- import the package from which we registered the module above.protected List<ReactPackage> getPackages(a) {
  @SuppressWarnings("UnnecessaryLocalVariable")
  List<ReactPackage> packages = new PackageList(this).getPackages();
  // Packages that cannot be autolinked yet can be added manually here, for example:
  // packages.add(new MyReactNativePackage());
  
  // Payment module
  packages.add(new PayPackage()); // <-- add this line and replace the class name with the name of your Package class..return packages;
}
Copy the code

4. Initiate Alipay payment in JS

Ok, after the above steps, we have a native payment module written. If you modify the native code, you need to re-run the react-native run-Android command to recompile the project so that the native code will take effect.

Then import the NativeModules modules in React-Native, which refer to the native modules that we write ourselves on Android or IOS. Directly call the function in the corresponding module in the native module.

This is used in the form of a Promise because promise.resolve is used in the native module to return the result.

import { NativeModules } from 'react-native';

/** * NativeModules.AliPay * corresponds to the return value of getName() function ** in the AliPay. Java file prepared in Step 3, while the payV2 method corresponds to the AliPay * / payV2 () function
enum AliPayResult { SUCCESS = 9000, UNKNOW_DEALING = 8000, UNKNOW = 6004, NETWORK_ERR = 6002, CANCEL = 6001, REPEAT_REQ = 5000, FAIL = 4000 }

export const aliPay = async (orderInfo) => {
  const result_code = await NativeModules.AliPay.payV2(orderInfo)
  // Do different processing according to result_code
}
Copy the code

Android connected to wechat Pay

With the above to pay the basis of alipay, wechat pay is very convenient.

The official document: pay.weixin.qq.com/wiki/doc/ap…

1. Background Settings

This part I will not say, we look at the official document to do it! Just fill in these two items!

2. Import wechat Pay SDK

1. Add the following content in build.gradle under app directory to rely on wechat SDK:

Dependencies {/ / WeChat pay implementation "com. Tencent. Mm. Opensdk: wechat - SDK - android - without - the mta: +" / / other dependent}Copy the code

3. Write native code

1. Set up the wechat payment catalog

Under the pay package, create a wechat package:

Create conconst. Java file under /pay/wechat

This file is mainly used to store your APPID:

packageYour package name. Pay. Wechat;public class Const {
    public static final String APP_ID = "Your APPID";
}
Copy the code

3. Create wechatPay. Java under /pay/wechat

This file is the main code for activating wechat Pay:

packageYour package name. Pay. Wechat;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.ReadableMap;
import com.facebook.react.bridge.WritableMap;

import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

public class WeChatPay extends ReactContextBaseJavaModule {
    private static ReactApplicationContext reactContext;
    public static Promise promise;

    private IWXAPI api;

    public WeChatPay(ReactApplicationContext context) {
        super(context);
        reactContext = context;
        api = WXAPIFactory.createWXAPI(context, Const.APP_ID, false);
        api.registerApp(Const.APP_ID);
    }

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

    @ReactMethod
    public void pay(ReadableMap request, Promise promise) {
        WeChatPay.promise = promise;

        PayReq req = new PayReq();
        req.appId = request.getString("appid");
        req.partnerId = request.getString("partnerid");
        req.prepayId = request.getString("prepayid");
        req.packageValue = "Sign=WXPay";
        req.nonceStr = request.getString("nonceStr");
        req.timeStamp = request.getString("timestamp");
        req.sign = request.getString("sign");

        int wxSdkVersion = api.getWXAppSupportAPI();
        if (wxSdkVersion >= Build.PAY_SUPPORTED_SDK_INT) {
            api.sendReq(req);
        } else if (wxSdkVersion == 0) {// wechat is not installed
            WritableMap map = Arguments.createMap();
            map.putInt("errCode", -3);
            WeChatPay.promise.resolve(map);
        } else {
            // the wechat version is too low
            WritableMap map = Arguments.createMap();
            map.putInt("errCode", -4); WeChatPay.promise.resolve(map); }}}Copy the code

4. Write wechat pay callback code

This step is to get the results of wechat Pay.

1. First, create a WXAPI package under your Android project.

⚠ Pay attention !!!! This bag must be on the bottom layer of your bag, not anywhere else!

2. Create a wxPayEntryActivity.java file under the wxAPI package

⚠ Pay attention !!!! Don’t change the file name either

Code:

packageYour package name. Wxapi;importPay. Wechat.Const;importPay. Wechat.WeChatPay;import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.IllegalViewOperationException;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final String TAG = "WXPayEntryActivity";
    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, Const.APP_ID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onResp(BaseResp resp) {
        System.out.println("onResp2");
        if(resp.getType()== ConstantsAPI.COMMAND_PAY_BY_WX){
            try {
                // Return the payment result.
                WritableMap map = Arguments.createMap();
                map.putInt("errCode", resp.errCode);
                WeChatPay.promise.resolve(map);
                finish();
            } catch(IllegalViewOperationException e) { WeChatPay.promise.reject(e); }}}}Copy the code

5. Registration module

In pay/ paypackage.java, add the following code:

// Wechat Pay
modules.add(new WeChatPay(reactContext));
Copy the code

See the alipay payment section above for the specific code of this file

6, modify,AndroidManifest.xml

Add an Activity

<activity
        android:name=".wxapi.WXPayEntryActivity"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Translucent.NoTitleBar"
        android:exported="true"
        android:taskAffinity="!!!!!! Your package name !!!!!!"
        android:launchMode="singleTask">
</activity>
Copy the code

7. Call in JS

import { NativeModules } from "react-native"

enum WeChatPayResult { SUCCESS = 0, ERROR = -1, CANCEL = -2, NOT_INSTALL = -3, VERSION_TOO_LOW = -4 }

const { errCode } = await NativeModules.WeChatPay.pay(request)
// Do different things according to errCode
Copy the code

The passed request argument is an object containing the following attributes: