47 lines
1.8 KiB
Kotlin
47 lines
1.8 KiB
Kotlin
package com.img.rabbit.utils
|
|
|
|
import com.tencent.mm.opensdk.constants.Build
|
|
import com.tencent.mm.opensdk.modelbiz.WXOpenCustomerServiceChat
|
|
import com.tencent.mm.opensdk.modelmsg.SendAuth
|
|
import com.tencent.mm.opensdk.openapi.IWXAPI
|
|
import kotlinx.coroutines.CancellationException
|
|
import kotlinx.coroutines.Dispatchers
|
|
import kotlinx.coroutines.withContext
|
|
|
|
/** SDK calls may synchronously query WeChat's ContentProvider. Keep them off the UI thread. */
|
|
object WechatRequests {
|
|
suspend fun authorize(api: IWXAPI, state: String): String? = execute {
|
|
if (!api.isWXAppInstalled) return@execute "您没有安装微信客户端,请先下载安装"
|
|
val request = SendAuth.Req().apply {
|
|
scope = "snsapi_userinfo"
|
|
this.state = state
|
|
}
|
|
if (api.sendReq(request)) null else "无法打开微信授权,请重试"
|
|
}
|
|
|
|
suspend fun customerService(api: IWXAPI, corpId: String?, url: String?): String? = execute {
|
|
if (!api.isWXAppInstalled) return@execute "未安装微信客户端"
|
|
if (api.wxAppSupportAPI < Build.SUPPORT_OPEN_CUSTOMER_SERVICE_CHAT) {
|
|
return@execute "当前微信版本不支持在线客服,请升级微信"
|
|
}
|
|
if (corpId.isNullOrBlank() || url.isNullOrBlank()) {
|
|
return@execute "客服信息暂不可用,请稍后重试"
|
|
}
|
|
val request = WXOpenCustomerServiceChat.Req().apply {
|
|
this.corpId = corpId
|
|
this.url = url
|
|
}
|
|
if (api.sendReq(request)) null else "无法打开微信客服,请重试"
|
|
}
|
|
|
|
private suspend fun execute(block: () -> String?): String? = withContext(Dispatchers.IO) {
|
|
try {
|
|
block()
|
|
} catch (e: CancellationException) {
|
|
throw e
|
|
} catch (e: Exception) {
|
|
"微信暂时无法响应,请稍后重试"
|
|
}
|
|
}
|
|
}
|