Tuesday, March 28, 2017

Android WeChat Login Integration

Android WeChat Login:

To integrate Wechat in your Android Application.you need 3 things:

1)AppId
2)Package Name
3)SH1 :Generated using the same Package Name

Like any 3rd party integration there is  a console of WeChat.you can go there generate the App Id by providing very simple information to their console.The app Id is important as it's how WeChat identifies the application requesting authorization.

There are many things which you should take care.

1)The package name of your application must be same whatever you have given in the WeChat console.
2)Generate the SH1 using the same package name.

I couldn't find a gradle import for the WeChat SDK. Their official site gives instructions on how to import their SDK into the libs folder of your application.

http://dev.wechat.com/wechatapi/installguide


Note:Follow these steps line by line .Do not miss anything:

Pitfalls


  • WeChat seems to break if your package name differs from your applicationId. This is probably due to the reflection used by WeChat to respond to your request. If your package name differs from what's set in WeChat, you'll transition to WeChat when an auth attempt is made but you'll never get a response. If your applicationID differs from what's in WeChat, nothing at all will happen when you request an authorization. Basically you must not use applicationId.

  • Package name can be mixed case but what's saved in WeChat must exactly match what's in your application.

  • The Signature hash should only be alpha numeric. Do no include other symbols like ":"
  • You must have a validated WeChat app on the device (use a real phone).

  • You must use the proper project structure. If your package name is com.test.app, you must place your activity for handling WeChat responses at com.test.app.wxapi.WXEntryActivity.

  • You must register before attempting to get a token.

  • Be careful with minified code (Proguard). There are articles online that mention minified code can mess up WeChat communication.

  • You must export your WXEntryActivity in your manifest.

Once everything is lined up, there is very little code needed to generate a token. However if anything is incorrect, you will likely never see any transition to WeChat, a failure to load WeChat if a transition occurs, or no response from WeChat after you give your application access.


Sample Code:

Let say you a WeChat Button then on the click of that button just open this Activity:


public String WE_CHAT_APP_ID = "wxg4c3e70195c29k17";//you put your app id here.you will get something
like this



public class WeChatSendRequestActivity extends Activity {

    Button test;
    private IWXAPI api;

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.test);
        api = WXAPIFactory.createWXAPI(this, AppConstants.WE_CHAT_APP_ID,true);
        api.registerApp(AppConstants.WE_CHAT_APP_ID);
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "none";
        api.sendReq(req);
        finish();

    }
}

test.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:orientation="vertical"              android:layout_width="match_parent"              android:layout_height="match_parent">


</LinearLayout>



Another Activity provided by Wechat Sdk then call back would come here:


package com.pack.package.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.pack.package.R;
import com.pack.package.util.apputil.AppConstants;
import com.pack.package.util.apputil.AppSharedPreference;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.ShowMessageFromWX;
import com.tencent.mm.opensdk.modelmsg.WXAppExtendObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler{
   
   private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;
   
   private Button gotoBtn, regBtn, launchBtn, checkBtn, scanBtn;
   
   // IWXAPI ǵ�����app��΢��ͨŵopenapiӿ    private IWXAPI api;
   
    @Override    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.frag_login);
        
        // ͨ��WXAPIFactory��������ȡIWXAPI��ʵ��       api = WXAPIFactory.createWXAPI(this, AppConstants.WE_CHAT_APP_ID, true);
      try {
           api.handleIntent(getIntent(), this);
        } catch (Exception e) {
           e.printStackTrace();
        }
    }

   @Override   protected void onNewIntent(Intent intent) {
      super.onNewIntent(intent);
      
      setIntent(intent);
        api.handleIntent(intent, this);
   }

   @Override   public void onReq(BaseReq req) {
      switch (req.getType()) {
      case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
         goToGetMsg();     
         break;
      case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
         goToShowMsg((ShowMessageFromWX.Req) req);
         break;
      default:
         break;
      }
   }


   @Override   public void onResp(BaseResp resp) {
      int result = 0;

      SendAuth.Resp response = (SendAuth.Resp) resp;
      Log.V("Access Token::"+response.code);

      //Toast.makeText(this, "baseresp.getType = " + resp.openId, Toast.LENGTH_SHORT).show();            switch (resp.errCode) {
      case BaseResp.ErrCode.ERR_OK:
         result = R.string.errcode_success;
         break;
      case BaseResp.ErrCode.ERR_USER_CANCEL:
         result = R.string.errcode_cancel;
         break;
      case BaseResp.ErrCode.ERR_AUTH_DENIED:
         result = R.string.errcode_deny;
         break;
      case BaseResp.ErrCode.ERR_UNSUPPORT:
         result = R.string.errcode_unsupported;
         break;
      default:
         result = R.string.errcode_unknown;
         break;
      }
      

      finish();
   }
   
   private void goToGetMsg() {
      /*Intent intent = new Intent(this, GetFromWXActivity.class);      intent.putExtras(getIntent());      startActivity(intent);      finish();*/   }
   
   private void goToShowMsg(ShowMessageFromWX.Req showReq) {
   /* WXMediaMessage wxMsg = showReq.message;      WXAppExtendObject obj = (WXAppExtendObject) wxMsg.mediaObject;            StringBuffer msg = new StringBuffer(); // ��֯һ������ʾ����Ϣ����
      msg.append("description: ");      msg.append(wxMsg.description);      msg.append("\n");      msg.append("extInfo: ");      msg.append(obj.extInfo);      msg.append("\n");      msg.append("filePath: ");      msg.append(obj.filePath);            Intent intent = new Intent(this, ShowFromWXActivity.class);      intent.putExtra(Constants.ShowMsgActivity.STitle, wxMsg.title);      intent.putExtra(Constants.ShowMsgActivity.SMessage, msg.toString());      intent.putExtra(Constants.ShowMsgActivity.BAThumbData, wxMsg.thumbData);      startActivity(intent);      finish();*/   }
}



add these in your manifest:


<receiver    android:name=".util.socialutil.wechat.AppRegister"    android:permission="com.tencent.mm.plugin.permission.SEND" >
    <intent-filter>
        <action android:name="com.tencent.mm.plugin.openapi.Intent.ACTION_REFRESH_WXAPP" />
    </intent-filter>
</receiver>

<activity    android:name="com.pack.package.wxapi.WXEntryActivity"    android:label="@string/app_name"    android:exported="true"    android:launchMode="singleTop">
    <!--   <intent-filter>            <action android:name="android.intent.action.MAIN" />            <category android:name="android.intent.category.LAUNCHER" />        </intent-filter>-->
        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <data android:scheme="sdksample"/>
        </intent-filter>
</activity>

<activity    android:name="com.pack.package.util.socialutil.wechat.WeChatSendRequestActivity"    android:label="@string/app_name"    >


in second activity you will get the response(Access Token ) in switch case and you can get anything
from that access token like other access token such as facebook,google,twitter etc.

2 comments:

Vmate said...

VMATE

jagadish said...

https://free-download-linkmf.blogspot.com/2013/08/wechat-app-download-for-nokia-asha-501.html?showComment=1586011437367#c7300747541261886099