@TOC

preface

Last week, I have been busy with the optimization task before the New Year. The leaders want to stimulate your potential more and more at the end of the year. The tasks come one by one and you can go home when you finish them. As a newcomer to the company, working with unfamiliar code and no one around to help you develop a few features in such a short period of time was a bit of a struggle. I waited until now to call it a day and have time to take stock of the goblins who had tortured me to death last week. (The example is still mostly Kotlin)

Wechat tripartite login

Integrated wechat tripartite login process is not difficult, but there are a lot of holes in the middle of the official did not say clearly. Let’s start from the beginning and discuss the pits we encounter in detail.

  1. Register as a wechat open platform user and apply for an application.

    This step should not be too much, is a simple registration process. However, in the Android app, the signature of the app is obtained through the signature tool provided by wechat: GenSignature. In this tool, you can enter the name of the application package installed on the machine to obtain the signature of the app. Just fill it in. The audit says seven working days, but it takes a few hours.

  2. Import the third-party package and initialize it

Bring in the three-way bag. Same old rule

com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+
Copy the code

Reference this address in your project’s Gradle file and update it to make it available.

And then initialize it, usually in the Application:

val appID = "wxecb9abc374b780c2"
val api: IWXAPI = WXAPIFactory.createWXAPI(this, appID, true)
private fun initWx(a) {
   api.registerApp(appID)
}
Copy the code

Of course, many people directly place this step in the Activity or Fragment that needs to be called and logged in, but we are here to prevent the need to add other functions of wechat in the future, so we put it here.

  1. Next is the operation inside the Activity or Fragment.

    private fun startWxLogin(a) {
        val appID = "wxecb9abc374b780c2"
        val api: IWXAPI = WXAPIFactory.createWXAPI(this, appID, true)
        if(! api.isWXAppInstalled) { showShort("You have not installed wechat yet")}else {
            val req = SendAuth.Req()
            req.scope = "snsapi_userinfo"
            req.state = "zhys_wxlogin"
            api.sendReq(req)
        }
    }
    Copy the code

    This method is to tune up the wechat operation, put this method into the corresponding click event inside. Req. scope is fixed to this, and req.state is customized.

  2. Next, we need to create a new class to receive messages from wechat. Because the package name and signature are registered on wechat official website, wechat transmits the information to this class in the way of absolute path. This class has strict naming rules. Wxapi: WXEntryActivity: WXEntryActivity: WXEntryActivity: WXEntryActivity: WXEntryActivity The package name. Wxapi WXEntryActivity, such as website registered com. Androidproject. Test, so the package name that the class should be com. Androidproject. Test. Wxapi. WXEntryActivity. Here is the basic way to write this class

class WXEntryActivity : Activity(), IWXAPIEventHandler {
    private var mWeixinAPI: IWXAPI? = null
    private val RETURN_MSG_TYPE_LOGIN = 1
    private val RETURN_MSG_TYPE_SHARE = 2

    public override fun onCreate(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        mWeixinAPI = WXAPIFactory.createWXAPI(this, WEIXIN_APP_ID, true) mWeixinAPI!! .handleIntent(this.intent, this)}override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent) setIntent(intent) mWeixinAPI!! .handleIntent(intent,this)// This sentence must be called
    }

    // Requests sent by wechat will be called back to the onReq method
    override fun onReq(req: BaseReq) { LogUtils.d("onReq")}// Send the response result to wechat request
    override fun onResp(resp: BaseResp) {
        LogUtils.d("onResp")
        when (resp.errCode) {
            BaseResp.ErrCode.ERR_OK -> {
                LogUtils.d("ERR_OK")
                // The message was sent successfully
                val sendResp = resp as SendAuth.Resp
                val code = sendResp.code
                EventBus.getDefault().post(code,"wxCode")
                finish()
            }
            BaseResp.ErrCode.ERR_USER_CANCEL -> {
                if (resp.type == RETURN_MSG_TYPE_SHARE){
                    showShort("Share failure")}else{
                    showShort("Login failed")
                }
                LogUtils.e("ERR_USER_CANCEL")
            }
            BaseResp.ErrCode.ERR_AUTH_DENIED -> LogUtils.e("ERR_AUTH_DENIED")
            else -> {
                showShort("Wechat login error")
                LogUtils.d("Wechat login error"+""+resp.errCode+resp.errStr)
                finish()
            }
        }// Send cancelled
        // Send was rejected
        // Send back

    }
    companion object {
        private val APP_SECRET = "305c1e604e79f7e9b4c9a617c67c345c"
        val WEIXIN_APP_ID = "wxecb9abc374b780c2"
        private val uuid: String? = null}}Copy the code
  1. Here, we only use the code returned by wechat, and then send it to the back end. The back end integrates the three-party login function of wechat to get our user information. If we want to get relevant user information, we can also get it.

Well, so far, so much for the basic use of wechat, let’s talk about the pit I met when I integrated wechat.

At the beginning, after I finished writing and running according to the official website step by step, I found that the wechat call up interface only flashes by, and the call up is closed in a moment, and the debug in the WXEntryActivity class is not triggered. Apparently, wechat didn’t find this class. So I checked the package name, which is exactly the same as the official website, and then I checked the signature, and found that the debug mode installation and packaged installation signature are different. That was a mess, so I came to the conclusion, let’s pack it and test it later. But !!!! After changing the signature or not, online search solutions said that the package name is wrong. But I left to see right to see the package name is completely consistent ah, and then this problem troubled me for a day. By the time you get home at night and are exhausted, you want to make one last effort, so you experiment. And then I found out that this code was designed to be packaged in different environments with different suffixes,

applicationIdSuffix ".develop"
Copy the code

At this point, you’d think I’d made a stupid mistake and solved the problem by looking for a package name with the same suffix as the one registered on the official website (I hope so), but it turns out it’s not that simple.

Find the same bag name thought you could breathe a sigh of relief, but found that still not. I feel at this time and this line of code must have a relationship, online success cases are absolutely fixed package name. So I commented out this line of code, changed the wechat registered package name into a form without suffix, and sure enough, it worked. (Heart ten thousand grass mud horse pentium). Although successful, this project cannot be carried on like this, because QQ login is still needed later, the package name of Tencent open platform cannot be modified, and other third-party SDK is also used, which will affect other functions. I had to change the directory structure and just write that suffix in there. Then cut out another branch, maintaining the original directory structure and ensuring that other functions can be tested in the test environment.

Wechat login pit:

  1. Note that the package names are consistent

  2. The signature of the debug run is inconsistent with the signature of the package. (If wechat returns ERR=-6 after integration, the signature is probably inconsistent. It is also possible that wechat has run wrong signatures before, which will be recorded in wechat cache, and the cache needs to be cleared or reinstalled directly.)

  3. //applicationIdSuffix ".develop"
    //signingConfig signingConfigs.release
    Copy the code

Can not use these two lines of code (the latter is my experiment), more frustrated is so far do not know the reason, I hope the predestiny people see this article can answer it.

QQ tripartite login

Next we talk about QQ tripartite login, QQ tripartite login is actually very simple, I stumbled in this place is pure lack of experience.

QQ tripartite landing SDK or rely on the form of lib package to achieve. Download the lib package from the official website and use it once you’ve introduced it.

  1. First instantiate where you need to call:

    val mTencent: Tencent = Tencent.createInstance("Your appid", applicationContext)
    Copy the code

    Then pull up QQ login:

    mTencent.login(this."all", BaseUiListener())
    Copy the code

    Here BaseUiListener is writing himself to receive the qq callback. I need to write it myself.

  2. Write QQ callbacks

    public class BaseUiListener implements IUiListener {
        // Note that the test needs to register the debugger QQ id on Tencent open platform
        @Override
        public void onComplete(Object response) {
            try {
    // String openId = ((JSONObject) response).getString("openid");
    // String expires = ((JSONObject) response).getString("expires_in");
                String token = ((JSONObject) response).getString("access_token");
                LogUtils.d(((JSONObject) response).getString("access_token"));
                EventBus.getDefault().post(token,"qqToken");
            } catch(JSONException e) { e.printStackTrace(); }}@Override
        public void onError(UiError e) {
            LogUtils.d("code:" + e.errorCode + ", msg:"
                    + e.errorMessage + ", detail:" + e.errorDetail);
        }
    
        @Override
        public void onCancel(a) {
            LogUtils.d("onCancel"); }}Copy the code

Here I only need QQ’s accessToken, so I took this value, and other personal information can also be accessed.

QQ need to pay attention to the point is in the test environment need to go to Tencent open platform registration debugger QQ number, otherwise it will only continue to pull up no response. (Oddly enough, you don’t need to register for ios, which I haven’t noticed).

So far, wechat QQ tripartite landing pit even if completed, these pit delayed me too long, but also worth it. Here’s a little bit more off topic:

I also used Baidu’s offline voice synthesis, but there was a problem that the voice could not be read when typing formal packages. I went to lock the packaged lines of code and concluded the following:

// minifyEnabled false
// shrinkResources false
Copy the code

These two lines should not be added arbitrarily, shrinking resource and shrinking file will delete resource files it deems useless. It is most likely to be deleted by mistake, so offline voice is not available.

The final summary

Some time ago, I was too tight, my blog was not more, and I did not do my own maintenance project, so I will slowly keep up with it. These potholes took a long time, but gained a lot of experience, and will not make mistakes in the future.