Introduction of aar: ali phoneNumber – AuthSDK – 2.8.3. Aar, at the same time you need to use the Json parser library: implementation ‘com. Alibaba: fastjson: 1.2.61, WeChat SDK: API ‘com. Tencent. Mm. Opensdk: wechat – SDK – android – without – the mta: 6.6.4’

Tools:

import android.annotation.SuppressLint import android.os.Handler import android.os.Looper import com.alibaba.fastjson.JSON import com.blankj.utilcode.util.LogUtils import com.blankj.utilcode.util.Utils import com.mobile.auth.gatewayauth.* import com.mobile.auth.gatewayauth.model.TokenRet object AliAuthHelper { val SERVICE_TYPE_AUTH = 1 // Number authentication val SERVICE_TYPE_LOGIN = 2 // One-click login val ALI_AUTH_SDK_KEY = "z6Gec9VW0EY8h47ZKDa/YY+nPDlJ6NpJbsttsJYGe3W4U0BgJIiDmOLJoUCDYXwaoJuc0nt+YJ6/7NU2Z59s7OCwjespuDtmquMB2Cutykkpq/E9Vet1fdm se1LF9RgUglwVNncMDtc5SS5ggKThY7ownlph2gPgiTgYFX4ngJ361RJ5Xe9i3D00bJa4T52cLzgr+PqYmHmcWxPuAqLea9fJNXKy0C9YHZ6f0z6eJh2OCx+ wwVPTbFCfPrj4G3VqVPC400SW23wRkM5LyOd22w5td0pJhrV7IIu1xpEMyGQ=" val mAlicomAuthHelper: PhoneNumberAuthHelper by lazy { PhoneNumberAuthHelper.getInstance(Utils.getApp(), mTokenListener ) } var mainHandler = Handler(Looper.getMainLooper()) var mTokenListener = BaseListener() var config: BaseAliAuthConfig? = null init {/ / initialization mAlicomAuthHelper setAuthListener (mTokenListener) mAlicomAuthHelper. SetLoggerEnable (true) mAlicomAuthHelper.setAuthSDKInfo( ALI_AUTH_SDK_KEY ) } private fun initConfig(config: BaseAliAuthConfig) { mAlicomAuthHelper.setUIClickListener(config.createUIClickListener()) mAlicomAuthHelper.setAuthUIConfig(config.createAuthUIConfig()) if (config.createAuthRegisterXmlConfig() == null) { mAlicomAuthHelper.removeAuthRegisterXmlConfig() } else { mAlicomAuthHelper.addAuthRegisterXmlConfig(config.createAuthRegisterXmlConfig()) } } fun getLoginToken(config: BaseAliAuthConfig) { LogUtils.d("getLoginToken") mAlicomAuthHelper.checkEnvAvailable( SERVICE_TYPE_LOGIN ) initConfig( config ) AliAuthHelper.config = config mAlicomAuthHelper.getLoginToken(Utils.getApp(), 5000) } class BaseListener : TokenResultListener { override fun onTokenFailed(ret: String?) { mAlicomAuthHelper.hideLoginLoading() LogUtils.d("onTokenFailed p0 = $ret") var failTokenRet: TokenRet? = null try { failTokenRet = JSON.parseObject<TokenRet>(ret, TokenRet::class.java) } catch (e: Exception) { e.printStackTrace() } if (failTokenRet ! = null) { if (failTokenRet.code.contains("6000")) { mainHandler.post { config? .let { it.onAuthFailed(ret) config = null } } } } else { mainHandler.post { config? .let { it.onAuthFailed(ret) config = null } } } } @SuppressLint("CheckResult") override fun onTokenSuccess(ret: String?) { LogUtils.d("onTokenSuccess ret = $ret") var tokenRet: TokenRet? = null try { tokenRet = JSON.parseObject<TokenRet>(ret, TokenRet::class.java) } catch (e: Exception) { e.printStackTrace() } if (tokenRet ! = null) {when (tokenret.code) {"600000" -> {// Obtain token successfully mainHandler.post {config? . Let {it. OnAuthSuccess (tokenRet. Token) config = null}} mAlicomAuthHelper. QuitLoginPage ()} "600001" - > {/ / authorized page successfully mainHandler.post { config? .let { it.onStartAuthUISuccess(ret) } } } } } } } }Copy the code

Call method:

AliAuthHelper.getLoginToken(object : AliAuthLoginConfig() { @SuppressLint("CheckResult") override fun onAuthSuccess(token: String) { LogUtils.d("onTokenSuccess token = $token") viewModel.showLoading() AccountManager.quickLogin(token) .dofinally {viewmodel.dismissloading ()}.subscribe({// login successful}, { LogUtils.d("error it = $it") viewModel.handleError(it) }) } override fun onUiEventClick(viewType: Int) { when (viewType) { TYPE_CLICK_OTHER -> { LogUtils.d("TYPE_CLICK_OTHER") ActivityUtils.startActivity(LoginByPhoneActivity::class.java) } TYPE_CLICK_WECHAT -> { LogUtils.d("TYPE_CLICK_WECHAT") weChatLogin() } TYPE_CLICK_BY_PWD -> { LogUtils.d("TYPE_CLICK_BY_PWD") ActivityUtils.startActivity(LoginByPwdActivity::class.java) } } } override fun onStartAuthUISuccess(ret: String?) { viewModel.dismissLoading() } override fun onAuthFailed(ret: String?) { LogUtils.d("onTokenFailed ret = $ret") viewModel.dismissLoading() ActivityUtils.startActivity(LoginByPhoneActivity::class.java) } }) private fun weChatLogin() { viewModel.showLoading() ThirdPartLoginManger.weChatLogin(this, object : ThirdPartLoginManger.ThirdPartLoginCallback { override fun onAuthSuccess(authCode: String) { } override fun onAuthFail(error: Int, errorMsg: String) { viewModel.dismissLoading() } override fun onAliAuthSuccess() { viewModel.dismissLoading() } override fun onLoginSuccess() { viewModel.dismissLoading() } override fun onLoginFail(error: Throwable) {viewmodel.dismissloading () {viewmodel.handleError (error)}})}Copy the code

AliAuthLoginConfig:

import android.graphics.Color import android.view.View import com.blankj.utilcode.util.LogUtils import com.blankj.utilcode.util.StringUtils import com.etekcity.componentAccount.R import com.etekcity.vesyncbase.utils.PRIVACY_POLICY_URL import com.etekcity.vesyncbase.utils.TERMS_URL import com.mobile.auth.gatewayauth.AuthRegisterXmlConfig import com.mobile.auth.gatewayauth.AuthUIConfig import com.mobile.auth.gatewayauth.AuthUIControlClickListener import com.mobile.auth.gatewayauth.ui.AbstractPnsViewDelegate abstract class AliAuthLoginConfig : BaseAliAuthConfig(){ override fun createUIClickListener(): AuthUIControlClickListener { return AuthUIControlClickListener { code, context, jsonObj -> LogUtils.d("OnUIControlClick:code=" + code + ", JsonObj =" + if (jsonObj == NULL) "" else jsonobj.tojSONString ()) when (code) {"700001" -> {//700001 OnUiEventClick (TYPE_CLICK_OTHER)}}}} Override fun createAuthUIConfig(): AuthUIConfig { return AuthUIConfig.Builder() .setNavHidden(true) .setStatusBarHidden(true) .setPageBackgroundPath("bg_login") .setLogoImgPath("vesync_logo_white") .setLogoWidth(120) .setLogoHeight(53) // .setLogoOffsetY(92) .setSloganText(StringUtils.getString(R.string.login_logo_title)) .setSloganTextColor(Color.parseColor("#ffffff")) .setSloganTextSize(15) // .setSloganOffsetY(153) .setNumberColor(Color.parseColor("#ffffff")) .setNumberSize(18) // .setNumFieldOffsetY(245) .setLogBtnTextColor(Color.parseColor("#ffffff")) .setLogBtnTextSize(16) .setLogBtnText(StringUtils.getString(R.string.login_quick_login)) .setLogBtnBackgroundPath("ripple_button_bg") .setLogBtnHeight(44) // .setLogBtnOffsetY(308) .setLogBtnMarginLeftAndRight(40) .setSwitchAccText(StringUtils.getString(R.string.login_other_phone_login)) .setSwitchAccTextColor(Color.parseColor("#ffffff")) .setSwitchAccTextSize(14) // .setSwitchOffsetY(370) .setPrivacyBefore(StringUtils.getString(R.string.login_privacy_before)) .setAppPrivacyOne(StringUtils.getString(R.string.login_term), TERMS_URL) .setAppPrivacyTwo(StringUtils.getString(R.string.login_policy), PRIVACY_POLICY_URL) .setAppPrivacyColor(Color.WHITE, Color.parsecolor ("# 55c1A0 ")).setPrivacyTextSize(11).setCheckBoxHidden (true).setVEndorPrivacyPrefix (" SetVendorPrivacySuffix (" "). SetAuthPageActIn (" slide_in_right ", "slide_out_left") .setAuthPageActOut("slide_in_left","slide_out_right") .create() } override fun createAuthRegisterXmlConfig(): AuthRegisterXmlConfig? { return AuthRegisterXmlConfig.Builder() .setLayout( R.layout.login_include_other_way_auth, object : AbstractPnsViewDelegate() { override fun onViewCreated(view: View) { view.findViewById<View>(R.id.tv_wechat).setOnClickListener { onUiEventClick(TYPE_CLICK_WECHAT) AliAuthHelper.mAlicomAuthHelper.quitLoginPage() } view.findViewById<View>(R.id.tv_qq).setOnClickListener { onUiEventClick(TYPE_CLICK_QQ) AliAuthHelper.mAlicomAuthHelper.quitLoginPage() } view.findViewById<View>(R.id.tv_pwd).setOnClickListener { onUiEventClick(TYPE_CLICK_BY_PWD) AliAuthHelper.mAlicomAuthHelper.quitLoginPage() } } }) .build() } }Copy the code

BaseAliAuthConfig:

import com.mobile.auth.gatewayauth.AuthRegisterXmlConfig import com.mobile.auth.gatewayauth.AuthUIConfig import com.mobile.auth.gatewayauth.AuthUIControlClickListener abstract class BaseAliAuthConfig : AliAuthTokenListener, AliAuthUIClickListener {companion object {// Other login methods const val TYPE_CLICK_OTHER = 1 const val TYPE_CLICK_WECHAT = 2 const val TYPE_CLICK_QQ = 3 const val TYPE_CLICK_BY_PWD = 4 } abstract fun createUIClickListener(): AuthUIControlClickListener abstract fun createAuthUIConfig(): AuthUIConfig abstract fun createAuthRegisterXmlConfig(): AuthRegisterXmlConfig? }Copy the code

AliAuthTokenListener:

Interface AliAuthTokenListener {/** * The authorization interface is invoked successfully */ fun onStartAuthUISuccess(ret: String?) */ fun onAuthFailed(ret: String?) /** * Get token successfully */ fun onAuthSuccess(token: String)}Copy the code

AliAuthUIClickListener:

interface AliAuthUIClickListener {

    fun onUiEventClick(clickViewType: Int)
}
Copy the code

ThirdPartLoginManger:

object ThirdPartLoginManger { private var loginRepository = RepositoryProviders.of(CloudGlobalConfig.appSession).get( LoginRepository::class.java ) var mOauthType = "WeChat" var mCallback: ThirdPartLoginCallback? = null fun qqLogin(context: context, callback: ThirdPartLoginCallback) {} /** * Context, callback: ThirdPartLoginCallback) { WeChatHelper.initApi(context) mCallback = callback mOauthType = "WeChat" WeChatHelper.getAuthCode(object : WeChatHelper.WeChatAuthCallback { @SuppressLint("CheckResult") override fun onAuthSuccess(authCode: String) {callback.onAuthSuccess(authCode) GetThirdPartyAccount (mOauthType, authCode)} Override fun onAuthFail(error: Int, errorMsg: String) {// Failed to log in, throw to UI layer processing mCallback? .let { it.onAuthFail(error, errorMsg) mCallback = null } } }) } @SuppressLint("CheckResult") private fun getThirdPartyAccount(oauthType: String, authCode: String) {// Obtain the user information of the third party, determine whether the third party is bound to the mobile phone number, Go different branches AccountManager. GetThirdPartyAccount (oauthType, authCode). The subscribe ({the if (it. HasBindPhoneNumber) {/ / have bound their hands immediately, Direct login AccountManager. ThirdPartyLogin (oauthType, it. ThirdPartyAccountID). The subscribe {/ / login mCallback success? .let {callback -> callback.onLoginSuccess() mCallback = null}}} else { BindPhoneByVerityPhone (it. ThirdPartyAccountID)}}, {// Failed to get the interface, throwing it to the UI layer to process the mCallback? .let { callback -> callback.onLoginFail(it) mCallback = null } }) } /** * Call Ali Cloud account authentication interface to read token-> Read mobile phone number in the background interface -> Determine whether the account is bound -> Callback interface binding * Ali account authentication fails to obtain token-> Manual input mobile phone number interface * */ private Fun BindPhoneByVerityPhone (thirdPartyAccountID: String) {/ / callback interface read ali phone number AliAuthHelper. GetLoginToken (object: AliAuthBindConfig() { @SuppressLint("CheckResult") override fun onAuthSuccess(token: String) {logutils. d("onTokenSuccess token = $token") // After successful jump to verify mobile phone number interface // Check whether the account exists loginRepository.isAccountExit("accessToken", null, null, Token).subscribe({logutils.d (" it = $it") if (it.accountexist) {// The account exists, Play box prompts the user var activity = ActivityUtils. GetTopActivity () if the activity is FragmentActivity {showPhoneBoundDialog ( Activity. SupportFragmentManager, it countryCode, it. PhoneNumber, thirdPartyAccountID, token)}} else {/ / account was not found, Direct binding / / callback interface binding thirdPartLoginAndBindPhone (it countryCode, it phoneNumber, thirdPartyAccountID, token)}}, { LogUtils.d(" it = $it") mCallback? .let { callback -> callback.onLoginFail(it) mCallback = null } }) } override fun onUiEventClick(clickViewType: Int) {when (clickViewType) {// Click to bind other mobile phone numbers TYPE_CLICK_OTHER ->{ BindPhoneActivity.start(ActivityUtils.getTopActivity(),mOauthType,thirdPartyAccountID) } } } override fun onStartAuthUISuccess(ret: String?) { LogUtils.d("onStartAuthUISuccess ret = $ret") mCallback? .let { it.onAliAuthSuccess() } } override fun onAuthFailed(ret: String?) {logutils. d("onTokenFailed ret = $ret") // Failed to authenticate the account. Enter the binding process of mobile phone number mCallback? .let { callback -> callback.onAuthFail(1111,"") mCallback = null } BindPhoneActivity. Start (ActivityUtils. GetTopActivity (), mOauthType, thirdPartyAccountID)}})} / dialog already on the display account * * * * / fun  showPhoneBoundDialog( fragmentManager: FragmentManager, countryCode: String, phoneNumber: String, thirdPartyAccountID: String, accessToken: String ) { IOSMsgDialog.init(fragmentManager) .setTitle(StringUtils.getString(R.string.login_phone_bound_title)) .setNegativeButton(StringUtils.getString(R.string.login_phone_bound_other), View.OnClickListener {// Click to bind another phone BindPhoneActivity.start(ActivityUtils.getTopActivity(),mOauthType,thirdPartyAccountID) }) .setpositiveButton (stringutils. getString(r.string.mon_bind), view. OnClickListener {// bind, Call the third party registration binding mobile phone interface thirdPartLoginAndBindPhone (countryCode, phoneNumber, thirdPartyAccountID, AccessToken)}). Show the three of ()} / * * * account login binding mobile phone number * / @ SuppressLint (" CheckResult ") private fun thirdPartLoginAndBindPhone ( countryCode: String, phoneNumber: String, thirdPartyAccountID: String, accessToken: String ) { AccountManager.thirdPartyLoginAndBindPhone( mOauthType, "oneKey", countryCode, phoneNumber, ThirdPartyAccountID, NULL, accessToken). Subscribe ({// Login successful}, Let {callback -> callback.onLoginFail(it) mCallback = null}})} interface ThirdPartLoginCallback  { fun onAuthSuccess(authCode: String) fun onAuthFail(error: Int, errorMsg: String) fun onAliAuthSuccess() fun onLoginSuccess() fun onLoginFail(error: Throwable) } }Copy the code

WeChatHelper:

import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import com.blankj.utilcode.util.ConvertUtils import com.blankj.utilcode.util.LogUtils import com.blankj.utilcode.util.ToastUtils import com.blankj.utilcode.util.Utils import com.tencent.mm.opensdk.modelmsg.SendAuth import com.tencent.mm.opensdk.modelmsg.SendMessageToWX import com.tencent.mm.opensdk.modelmsg.WXMediaMessage import com.tencent.mm.opensdk.modelmsg.WXWebpageObject import com.tencent.mm.opensdk.openapi.IWXAPI import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler import com.tencent.mm.opensdk.openapi.WXAPIFactory import java.net.URL /** * * @Description: WxLoginHelper * 1, wechat Login Authorization * 2, wechat sharing * @author: connorTang * @createdate: 2020/7/13 19:23 */ object WeChatHelper { private lateinit var WXAppId :String private var isInit = false private var api: IWXAPI? = null const val SCENE_FRIEND_CIRCLE = 0 const val SCENE_CHAT = 1 var authCallback: WeChatAuthCallback? = null fun setWxAppId(appId: String) { LogUtils.i("setWxAppId appId = $appId") WXAppId = appId } fun initApi(context: Context) { if(! this::WXAppId.isInitialized){ LogUtils.e("you should set appId first!" ) return } if (! isInit && api == null) { isInit = true api = WXAPIFactory.createWXAPI( context, WXAppId, true ) api!! .registerapp (WXAppId)}} /** * getAuthCode */ getAuthCode(callback: WeChatAuthCallback) {API? .let { authCallback = callback if (! IsWXAppInstalled) {// toastutils. showLong(" not installed ") authFail(100, Scope = "snsapi_userinfo" req.state = "request_login" it.sendreq (req); }} /** * authFail(errorCode: Int, errorMsg: String) {authCallback? .let {it. OnAuthFail (errorCode, errorMsg) authCallback = null}} /** * String) { authCallback? .let {it. OnAuthSuccess (code) authCallback = null}} /** ** url shared link * imageUrl shared image address * title shared title * description Share the scene to share the scene description * * / fun shareUrl (url: String, imageUrl: String, title: String, the description: String, scene: Int) { initApi(Utils.getApp()) val webPage = WXWebpageObject() webPage.webpageUrl = url val msg = WXMediaMessage(webPage) msg.title = title msg.description = description Thread(Runnable { var thumb = BitmapFactory.decodeStream(URL(imageUrl).openStream()); var thumbBmp = Bitmap.createScaledBitmap(thumb, 120, 150, true); thumb.recycle() msg.thumbData = ConvertUtils.bitmap2Bytes(thumbBmp) val req = SendMessageToWX.Req() req.transaction = "share" req.message = msg req.scene = SendMessageToWX.Req.WXSceneTimeline when(scene){ SCENE_FRIEND_CIRCLE ->SendMessageToWX.Req.WXSceneTimeline SCENE_CHAT ->SendMessageToWX.Req.WXSceneSession } api!! .sendreq (req)}).start()} /** * handleIntent(context: context, intent: Intent, handler: IWXAPIEventHandler) { if (! isInit) { initApi(context) } try { api!! .handleIntent(intent, handler) } catch (e: Exception) { e.printStackTrace() } } interface WeChatAuthCallback { fun onAuthSuccess(authCode: String) fun onAuthFail(error: Int, errorMsg: String) } }Copy the code