fluwx官方链接:https://pub.dev/packages/fluwx

import 'package:flutter/material.dart';
//微信支付回调
responseFromPayment.listen((WeChatPaymentResponse event){
         
});

//微信分享回调
responseFromShare.listen((WeChatShareResponse event){
       
});

只看实现方式,看到这里就好了,以下为本人查询该问题全过程。

官方文档没有找到fluwx分享后的回调(可能是我没找到),于是去看微信官方文档(https://developers.weixin.qq.com/doc/oplatform/Mobile_App/Access_Guide/Android.html安卓接入指南)

[4] 接收微信的请求及返回值

如果你的程序需要接收微信发送的请求,或者接收发送到微信请求的响应结果,需要下面 3 步操作:

a. 在你的包名相应目录下新建一个 wxapi 目录,并在该 wxapi 目录下新增一个 WXEntryActivity 类

b. 实现 IWXAPIEventHandler 接口,微信发送的请求将回调到 onReq 方法,发送到微信请求的响应结果将回调到 onResp 方法

c. 在 WXEntryActivity 中将接收到的 intent 及实现了 IWXAPIEventHandler 接口的对象传递给 IWXAPI 接口的 handleIntent 方法,示例如下图:

api.handleIntent(getIntent(), this);

当微信发送请求到你的应用,将通过 IWXAPIEventHandler 接口的 onReq 方法进行回调,类似的,应用请求微信的响应结果将通过 onResp 回调。

但是我的WXEntryActivity并没有实现IWXAPIEventHandler接口,但是fluwx文档中提到,可以直接继承FluwxWXEntryActivity来实现。所以打开FluwxWXEntryActivity。

/*
 * Copyright (C) 2018 The OpenFlutter Organization
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jarvan.fluwx.wxapi

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.jarvan.fluwx.handler.FluwxRequestHandler
import com.jarvan.fluwx.handler.FluwxResponseHandler
import com.jarvan.fluwx.handler.WXAPiHandler
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler


open class FluwxWXEntryActivity : Activity(), IWXAPIEventHandler {


    // IWXAPI 是第三方app和微信通信的openapi接口

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        try {
            WXAPiHandler.wxApi?.handleIntent(intent, this)
        } catch (e: Exception) {
            e.printStackTrace()
            finish()
        }

    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)

        setIntent(intent)

        try {
            WXAPiHandler.wxApi?.handleIntent(intent, this)
        } catch (e: Exception) {
            e.printStackTrace()
            finish()
        }
    }


    override fun onReq(baseReq: BaseReq) {
        // FIXME: 可能是官方的Bug,从微信拉起APP的Intent类型不对,无法跳转回Flutter Activity
        // 稳定复现场景:微信版本为7.0.5,小程序SDK为2.7.7
        val activity = FluwxRequestHandler.getRegistrar()?.activity()
        if (baseReq.type == 4 && activity is Activity) {
            // com.tencent.mm.opensdk.constants.ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX = 4
            startActivity(Intent(this, activity::class.java))
            finish()
        }
    }

    // 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法
    override fun onResp(resp: BaseResp) {
        FluwxResponseHandler.handleResponse(resp)
        finish()
    }


}

onResp上面注释的很明白。其实现在如果只是想实现android 层的就已经结束了,直接在自己的WXEntryActivity中重写onResp方法,按照项目业务逻辑操作就好了。

由于我们公司需要对应android和ios两个平台,所以还是要确认一下,fluwx如果有内部回调接口则说明是两个平台统一一个方法回调,如果没有则需要针对不同平台处理。带着这个问题开始从源头查起。

首先确定插件交互名称。

public final class GeneratedPluginRegistrant {
  public static void registerWith(PluginRegistry registry) {
    if (alreadyRegisteredWith(registry)) {
      return;
    }
    FluwxPlugin.registerWith(registry.registrarFor("com.jarvan.fluwx.FluwxPlugin"));
  }
}
class FluwxPlugin(private val registrar: Registrar, channel: MethodChannel) : MethodCallHandler {
    companion object {
        @JvmStatic
        fun registerWith(registrar: Registrar): Unit {
            val channel = MethodChannel(registrar.messenger(), "com.jarvanmo/fluwx") 
        }
    }
}

找到MethodChannel后在flutter项目中全局检索"com.jarvanmo/fluwx"(如果这块不清楚先去看dart与android之间的交互)找到

fluwx_iml.dart,贴出一部分代码,这是fluwx库的入口,有兴趣的可以详细看一下。

StreamController<WeChatShareResponse> _responseShareController =
    new StreamController.broadcast();

/// Response from share
Stream<WeChatShareResponse> get responseFromShare =>
    _responseShareController.stream;

StreamController<WeChatAuthResponse> _responseAuthController =
    new StreamController.broadcast();

/// Response from auth
Stream<WeChatAuthResponse> get responseFromAuth =>
    _responseAuthController.stream;

StreamController<WeChatPaymentResponse> _responsePaymentController =
    new StreamController.broadcast();

///Response from payment
Stream<WeChatPaymentResponse> get responseFromPayment =>
    _responsePaymentController.stream;

Stream<WeChatLaunchMiniProgramResponse> get responseFromLaunchMiniProgram =>
    _responseLaunchMiniProgramController.stream;

///Response from launching mini-program
StreamController<WeChatLaunchMiniProgramResponse>
    _responseLaunchMiniProgramController = new StreamController.broadcast();

StreamController<WeChatSubscribeMsgResp> _responseFromSubscribeMsg =
    new StreamController.broadcast();

///Response from subscribing micro-message
Stream<WeChatSubscribeMsgResp> get responseFromSubscribeMsg =>
    _responseFromSubscribeMsg.stream;

StreamController<AuthByQRCodeResult> _authByQRCodeFinishedController =
    new StreamController.broadcast();

///invoked when [authByQRCode] finished
Stream<AuthByQRCodeResult> get onAuthByQRCodeFinished =>
    _authByQRCodeFinishedController.stream;

StreamController<Uint8List> _onAuthGotQRCodeController =
    new StreamController.broadcast();

///when QRCode received
Stream<Uint8List> get onAuthGotQRCode => _onAuthGotQRCodeController.stream;

StreamController _onQRCodeScannedController = new StreamController();

///after uer scanned the QRCode you just received
Stream get onQRCodeScanned => _onQRCodeScannedController.stream;

StreamController<WeChatAutoDeductResponse> _responseAutoDeductController =
    new StreamController.broadcast();

/// Response from AutoDeduct
Stream<WeChatAutoDeductResponse> get responseFromAutoDeduct =>
    _responseAutoDeductController.stream;

final MethodChannel _channel = const MethodChannel('com.jarvanmo/fluwx')
  ..setMethodCallHandler(_handler);

Future<dynamic> _handler(MethodCall methodCall) {
  if ("onShareResponse" == methodCall.method) {
    _responseShareController.sink
        .add(WeChatShareResponse.fromMap(methodCall.arguments));
  } else if ("onAuthResponse" == methodCall.method) {
    _responseAuthController.sink
        .add(WeChatAuthResponse.fromMap(methodCall.arguments));
  } else if ("onLaunchMiniProgramResponse" == methodCall.method) {
    _responseLaunchMiniProgramController.sink
        .add(WeChatLaunchMiniProgramResponse.fromMap(methodCall.arguments));
  } else if ("onPayResponse" == methodCall.method) {
    _responsePaymentController.sink
        .add(WeChatPaymentResponse.fromMap(methodCall.arguments));
  } else if ("onSubscribeMsgResp" == methodCall.method) {
    _responseFromSubscribeMsg.sink
        .add(WeChatSubscribeMsgResp.fromMap(methodCall.arguments));
  } else if ("onAuthByQRCodeFinished" == methodCall.method) {
    _handleOnAuthByQRCodeFinished(methodCall);
  } else if ("onAuthGotQRCode" == methodCall.method) {
    _onAuthGotQRCodeController.sink.add(methodCall.arguments);
  } else if ("onQRCodeScanned" == methodCall.method) {
    _onQRCodeScannedController.sink.add(null);
  } else if ("onAutoDeductResponse" == methodCall.method) {
    _responseAutoDeductController.sink
        .add(WeChatAutoDeductResponse.fromMap(methodCall.arguments));
  }

  return Future.value(true);
}

标注的看命名可以猜到是有关分享相应的,然后点进new StreamController.broadcast()一看。

/**
 * A controller where [stream] can be listened to more than once.
 *
 * The [Stream] returned by [stream] is a broadcast stream.
 * It can be listened to more than once.
 *
 * A Stream should be inert until a subscriber starts listening on it (using
 * the [onListen] callback to start producing events). Streams should not
 * leak resources (like websockets) when no user ever listens on the stream.
 *
 * Broadcast streams do not buffer events when there is no listener.
 *
 * The controller distributes any events to all currently subscribed
 * listeners at the time when [add], [addError] or [close] is called.
 * It is not allowed to call `add`, `addError`, or `close` before a previous
 * call has returned. The controller does not have any internal queue of
 * events, and if there are no listeners at the time the event is added,
 * it will just be dropped, or, if it is an error, be reported as uncaught.
 *
 * Each listener subscription is handled independently,
 * and if one pauses, only the pausing listener is affected.
 * A paused listener will buffer events internally until unpaused or canceled.
 *
 * If [sync] is true, events may be fired directly by the stream's
 * subscriptions during an [add], [addError] or [close] call.
 * The returned stream controller is a [SynchronousStreamController],
 * and must be used with the care and attention necessary to not break
 * the [Stream] contract.
 * See [Completer.sync] for some explanations on when a synchronous
 * dispatching can be used.
 * If in doubt, keep the controller non-sync.
 *
 * If [sync] is false, the event will always be fired at a later time,
 * after the code adding the event has completed.
 * In that case, no guarantees are given with regard to when
 * multiple listeners get the events, except that each listener will get
 * all events in the correct order. Each subscription handles the events
 * individually.
 * If two events are sent on an async controller with two listeners,
 * one of the listeners may get both events
 * before the other listener gets any.
 * A listener must be subscribed both when the event is initiated
 * (that is, when [add] is called)
 * and when the event is later delivered,
 * in order to receive the event.
 *
 * The [onListen] callback is called when the first listener is subscribed,
 * and the [onCancel] is called when there are no longer any active listeners.
 * If a listener is added again later, after the [onCancel] was called,
 * the [onListen] will be called again.
 */
factory StreamController.broadcast(
    {void onListen(), void onCancel(), bool sync: false}) {
  return sync
      ? new _SyncBroadcastStreamController<T>(onListen, onCancel)
      : new _AsyncBroadcastStreamController<T>(onListen, onCancel);
}

如果不明白,直接有道翻译注释。

最后也是尝试性的导入fluwx包后,输入respon就出来了很多提示!!!

android微信分享没有回调函数 微信分享回调新规_微信

找到responseFromShare.listen,参数一目了然

android微信分享没有回调函数 微信分享回调新规_微信_02

赶紧测试验证,统统通过,完成。

第一次写,纯属个人纪录。如果有人能看到并帮助到了你,那是意外收获,不谢。