Flutter项目集成环信客服云功能

  • 前言:目前环信sdk还没有以flutter插件的形式提供支持,所以需要各自在android端和ios端集成

  • 前期准备:在 https://kefu.easemob.com/ 中设置好账号信息,flutter项目创建完成。

  • 附环信客服文档:http://docs.easemob.com/cs/300visitoraccess/androidsdkapi

  • ps:本项目在安卓端采取插件形式集成,在ios端采取class的方式集成(在正式项目中统一一种集成方式较好)

android端

一.创建flutter插件

创建flutter插件

一步步设置好后,AS会帮助创建一个flutter插件项目

插件项目目录

接下来主要在hx_plugin.dart文件下编写代码

hx_plugin.dart

1.首先创建MethodChannel对象、StreamController,并添加监听方法,这样就能接收原生端发送的广播:

  static  MethodChannel _channel =
      const MethodChannel('hxkefu_plugin')..setMethodCallHandler(_handle);

 static StreamController _messageController = new StreamController.broadcast();

  static Future _handle(MethodCall call){
  //接收原生端发送名为message_listen的广播
    if(call.method=="message_listen"){
      _messageController.add(call.arguments);
    }
  }

2.编写flutter端发送到原生端的广播,下面的所有方法都是根据环信文档的androidAPI来写:

//初始化方法,在flutter端调用其他环信api前必须先调用该方法
  static Future init(String appkey,String tenantId) async {
     await _channel.invokeMethod('hxInit',{
       "appkey":appkey,
       "tenantId":tenantId
     });

  }
  
//环信注册api
  static Future register(String username,String password)async{
    return await _channel.invokeMethod('hxRegister',{
      "username":username,
      "password":password,
    });
  }
  
//环信登录api
  static Future login(String username,String password,String userAvatar) async {
    return await _channel.invokeMethod('hxLogin',{
      "username":username,
      "password":password,
      "userAvatar":userAvatar
    });

  }

//环信登出api
  static Future logout() async {
    return await _channel.invokeMethod('hxLogout');

  }

  //进入聊天界面
  static Future start(String kefuchannelimid) async {
    return await _channel.invokeMethod('start',{
      "kefuchannelimid":kefuchannelimid
    });

  }
  //获得所有会话
  static Future getAllConversions()async{
    return await _channel.invokeMethod("getAllConversations");
  }
  
  static Future sendOrderInfo(String title,String orderTitle,String price,
      String desc,String imageUrl,String itemUrl,String content,String kefuchannelimid)async{
    return await _channel.invokeMethod("sendOrderInfo",{
      "title":title,
      "orderTitle":orderTitle,
      "price":price,
      "desc":desc,
      "imageUrl":imageUrl,
      "itemUrl":itemUrl,
      "content":content,
      "kefuchannelimid":kefuchannelimid
    });
  }

3. 在flutter项目中通过本地依赖的方式来引用

//在pubspec.yaml文件中引入,该插件项目文件与flutter项目同级
  hxkefu_plugin:
    path: "../hxkefu_plugin"

4.在flutter端调用该插件API

///在需要的地方调用插件API即可
///初始化
HxkefuPlugin.init("${appkey}", "${tenantId}");
///其他API的调用不一一展示了

5.在插件android端依赖环信androidSDK

将该插件项目以原生安卓中打开:


在安卓中打开

在插件项目的build.gradle文件引入环信androidSDK依赖


build.gradle文件
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        //环信客服SDK
        implementation 'com.hyphenate:kefu-easeui-android:latest.release' //或者 compile 'com.hyphenate:kefu-easeui-android:1.1.9r2'
        //EaseUI中 头像获取用到了glide,请添加glide库
        implementation 'com.github.bumptech.glide:glide:4.7.1' //其他版本也可以
        //EaseUI中,fragment用到了android-support-v4包
        implementation 'com.android.support:support-v4:28.0.0' //其他版本也可以
        compileOnly 'com.android.support:appcompat-v7:28.0.0-alpha1'
        compileOnly 'com.android.support:multidex:1.0.1'
        compileOnly 'com.android.support.constraint:constraint-layout:1.1.0'
        implementation 'androidx.core:core:1.5.0-alpha04'
    }

并点击sync project with gradle files安装依赖


image.png

6.android端的代码主要在下图中的文件进行编写:

HxkefuPlugin.java

主要展示了环信初始化api的代码,关于环信文档上其他需要的api也是这样的写法了。

  public static  Context mContext;
  static final Handler handler = new Handler(Looper.getMainLooper());
  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "${your_channel_name}");
    mContext = flutterPluginBinding.getApplicationContext();
    channel.setMethodCallHandler(this);
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull final Result result) {
    if (call.method.equals("getPlatformVersion")) {
      result.success("Android " + android.os.Build.VERSION.RELEASE);
    } else if(call.method.equals("hxInit")){
      String appkey = call.argument("appkey");
      String tenantId = call.argument("tenantId");

      System.out.println("==========appkey========="+appkey);
      System.out.println("==========tenantId========="+tenantId);
      ChatClient.Options options = new ChatClient.Options();
      options.setAppkey(appkey);
      options.setTenantId(tenantId);
      _uiProvider = UIProvider.getInstance();
      // Kefu SDK 初始化
      if (!ChatClient.getInstance().init(mContext, options)){
        return;
      }
      // Kefu EaseUI的初始化
     _uiProvider.init(mContext);
//      setEaseUIProvider(mContext);

      connectionListener = new  EMConnectionListener() {
        @Override
        public void onConnected() {
          System.out.println("网络连接成功");
        }

        @Override
        public void onDisconnected(int i) {

        }
      };
    }
  }

ios端

因为当时是两个人负责android和ios端,所以集成的方式不太一样,正确的做法是应该把插件在xcode那边编写好ios的代码,并调试。

1.在xcode打开插件项目,并引入环信ios sdk并配置

首先要下载环信提供的客服SDK,下载地址:http://www.easemob.com/download/cs(下载“iOS客服访客端SDK”)
往项目导入sdk的做法参考环信客服云文档-CEC IOS SDK集成-第3步:集成基础功能-准备工作。
PS:使用的环信sdk都是不包含实时音视频的版本,即:HelpDeskLite.framework和
HyphenateLite.framework,并使用环信demo里的EasyUI界面作为客服对话页面。

2.编写ios代码

在Runner文件夹创建文件。

@property(nonatomic) UIViewController *rootVc;


@end

@implementation HXPlugin


static NSString *const kMethodChannelName = @"${your_channel_name}";

static FlutterMethodChannel *mchannel;

static NSString *avatarUrl = @"";

static NSString *userName = @"";

//通道初始化
+(void) registerWithRegistrar:(NSObject*)registar{
    mchannel = [FlutterMethodChannel methodChannelWithName:kMethodChannelName binaryMessenger:[registar messenger]];
    HXPlugin* instance = [[HXPlugin alloc] init];
    [registar addMethodCallDelegate:instance channel:mchannel];
}

//处理消息
-(void)handleMethodCall:(FlutterMethodCall*) call result:(FlutterResult) result{
    NSLog(@"监听事件:%@",call.method);
    if([@"init" isEqualToString:call.method]){
        BOOL result = [self init:call.arguments[@"app_key"] withTenantId:call.arguments[@"tenant_id"]];
     
        if(result){
            //初始化成功
            NSLog(@"环信初始化成功");
        }else{
            //初始化失败
            NSLog(@"环信初始化成功");
        }
    }else if([@"login" isEqualToString:call.method]){
        NSLog(@"环信user_name:%@", call.arguments[@"user_name"]);
        NSLog(@"环信password:%@", call.arguments[@"password"]);
        BOOL result = [self login:call.arguments[@"user_name"] :call.arguments[@"password"]];
        if(result){
            NSLog(@"环信登录成功");
        }else{
            NSLog(@"环信登录失败");
        }
    }
}

-(BOOL) init:(NSString*)appKey withTenantId:(NSString*) tenantId{
    HDOptions *option = [[HDOptions alloc] init];
    //初始化表情
    [[HDEmotionEscape sharedInstance] setEaseEmotionEscapePattern:@"\\[[^\\[\\]]{1,3}\\]"];
    [[HDEmotionEscape sharedInstance] setEaseEmotionEscapeDictionary:[HDConvertToCommonEmoticonsHelper emotionsDictionary]];
    option.appkey = appKey;
    option.tenantId = tenantId;
    HDError *initError = [[HDClient sharedClient] initializeSDKWithOptions:option];
    if(initError){
        //初始化失败
        NSLog(@"初始化错误信息:%@",initError.errorDescription);
        return NO;
    }else{
        //初始化成功
        return YES;
    }
}

-(BOOL)login:(NSString*) userName:(NSString*) password{
    HDClient *client = [HDClient sharedClient];
    if(client.isLoggedInBefore == NO){
        HDError *error = [client loginWithUsername:userName password:password];
        if(error){
            //登录失败
            NSLog(@"登录失败错误信息:%@",error.errorDescription);
            return NO;
        }else{
            //登陆成功
            return YES;
        }
    }else{
        //已经登录了
        NSLog(@"环信已经登录");
        return NO;
    }
}

你可能感兴趣的:(Flutter项目集成环信客服云功能)