init method
Implementation
@override
Future<Map<String, dynamic>> init(Map<String, dynamic> config) async {
final prefs = this.prefs == null
? await SharedPreferences.getInstance()
: this.prefs!;
final token = prefs.getString("$_userId-${ConstantKeys.apiKey}");
dynamic contactIdentifier =
prefs.getString("$_userId-${ConstantKeys.contactIdentifier}");
dynamic userId = prefs.getString("$_userId-${ConstantKeys.userId}");
if (token != null && userId != null && contactIdentifier != null) {
logger.d(
"Used existing Chatwoot user id: $userId and token $token and contact identifier $contactIdentifier");
_chatwootContactIdentifier = userId;
return config
..addAll({
ConstantKeys.contactIdentifier: contactIdentifier,
ConstantKeys.apiKey: token,
ConstantKeys.userId: userId,
});
}
final Map<String, dynamic> data = {
"name": _name,
"identifier": _userId,
"custom_attributes": {"format": "m4a"}
};
final url = "/public/api/v1/inboxes/$_inboxIdentifier/contacts";
logger.d("Chatwoot authentication url: $url");
final response = await dio.post(url, data: data);
if (response.statusCode != 200) {
throw Exception("Failed to authenticate");
}
final body = response.data;
_chatwootContactIdentifier = body["source_id"];
final apikey = body["pubsub_token"];
userId = body["id"];
logger.d("Chatwoot user id: $_chatwootContactIdentifier");
logger.d("Chatwoot api key: $apikey");
await prefs.setString("$_userId-${ConstantKeys.apiKey}", apikey);
await prefs.setString("$_userId-${ConstantKeys.contactIdentifier}",
_chatwootContactIdentifier!);
await prefs.setString("$_userId-${ConstantKeys.userId}", "$userId");
return config
..addAll({
ConstantKeys.contactIdentifier: _chatwootContactIdentifier,
ConstantKeys.apiKey: apikey,
ConstantKeys.userId: userId.toString(),
});
}