HarmonyOS next之harmony_flutter_alipay(自定义支付入口)

一.MethodChannel

1.flutter端代码

  • 创建MethodChannel交互通道exam_ohos_utils
  • 接收ohos端传递过来的进度
/// An implementation of [ExamOhosUtilsPlatform] that uses method channels.
class MethodChannelExamOhosUtils extends ExamOhosUtilsPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('exam_ohos_utils');

  @override
  Future<String> getPlatformVersion() async {
    final version = await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  @override
  Future<Map> aliPayAuth(String auth) async {
    final version = await methodChannel.invokeMethod<Map>('aliPayAuth');
    return version;
  }
}

2.ohos端代码

  • 继承FlutterPlugin实现onAttachedToEngine方法
  • 创建MethodChannel实例exam_ohos_utils
  • 引入'@cashier_alipay/cashiersdk' 支付宝支付
  • 通过MethodResult回传参数
import { Pay } from '@cashier_alipay/cashiersdk';
import {
  FlutterPlugin,
  FlutterPluginBinding,
  MethodCall,
  MethodCallHandler,
  MethodChannel,
  MethodResult,
} from '@ohos/flutter_ohos';
import { BusinessError } from '@kit.BasicServicesKit';

/** ExamOhosUtilsPlugin **/
export default class ExamOhosUtilsPlugin implements FlutterPlugin, MethodCallHandler {
  private channel: MethodChannel | null = null;

  constructor() {
  }

  getUniqueClassName(): string {
    return "ExamOhosUtilsPlugin"
  }

  onAttachedToEngine(binding: FlutterPluginBinding): void {
    this.channel = new MethodChannel(binding.getBinaryMessenger(), "exam_ohos_utils");
    this.channel.setMethodCallHandler(this)
  }

  onDetachedFromEngine(binding: FlutterPluginBinding): void {
    if (this.channel != null) {
      this.channel.setMethodCallHandler(null)
    }
  }

  onMethodCall(call: MethodCall, result: MethodResult): void {
    if (call.method == "getPlatformVersion") {
      //测试方法
      result.success("OpenHarmony ^ ^ ")
    } else if (call.method == "aliPayAuth") {
      //ali支付
      new Pay().pay(call.args as string, true).then((payResult) => {
        result.success(payResult)
      }).catch((error: BusinessError) => {
        const infoMap = new Map<string,string>();
        infoMap.set("resultStatus", "-1");
        result.success(infoMap)
      });
    } else {
      result.notImplemented()
    }
  }
}