This paper adds login authorization and sharing of wechat SDK to the project based on the previously encapsulated SocialSDK. This paper briefly introduces the access and usage of wechat login sharing

Specific code project Github address: github.com/tsy12321/So…

Series of articles

Series one Secondary encapsulation and use of Android SDK Series two source code analysis series three wechat SDK access series four QQ SDK access series five Sina Weibo SDK access

1 Official Documents

Wechat official access document:

Open.weixin.qq.com/cgi-bin/sho…

2 Login Authorization

Wechat login authorization is based on OAuth2.0 standard.

The official documentation for the entire authorization process is clear:

Open.weixin.qq.com/cgi-bin/sho…

Here are a few concepts to understand:

  1. Call up the code that will be returned after wechat authorization is confirmed, and use this code to exchange for access_token
  2. After the access_token authorization is successful, all interfaces provided by wechat are obtained through the access_token. The access_token is obtained after the code+ APPID +secret request. Therefore, it is recommended that the client store the access_token on the server after obtaining the code. (The SDK secret encapsulated here is stored locally, so it is convenient to call. If it requires high security, it is suggested to put this step on the server, and do not store secret on the client)
  3. Refresh_token Access_token is time-sensitive. When the Access_token is invalid, you can obtain a new access_token by using refresh_token. However, if refresh_token expires, the client can only be called again for authorization.

2.1 Android Access Authorization Code

Initialize wXAPI and register:

this.mWXApi = WXAPIFactory.createWXAPI(context.getApplicationContext(), this.mConfig.appId);
        this.mWXApi.registerApp(this.mConfig.appId);Copy the code

Call when authorizing login:

SendAuth.Req req1 = new SendAuth.Req();
req1.scope = sScope;
req1.state = "snsapi_userinfo,snsapi_friend,snsapi_message";

if(!this.mWXApi.sendReq(req1)) {
    this.mAuthListener.onError(this.mConfig.getName(), "sendReq fail");
    LogUtils.e("wxapi sendReq fail");
}Copy the code

Callback result:

The callback treatment is explained below.

3 share

Wechat corresponds to 5 kinds of sharing and 2 channels (wechat session and moments)

So! Call different wechat apis according to the type of media to share.

@Override
    public void share(IShareMedia shareMedia, ShareListener shareListener) {
        this.mShareListener = shareListener;

        WXMediaMessage msg = new WXMediaMessage();
        String type = "";

        if(shareMedia instanceof ShareWebMedia) {       // Web sharing
            ShareWebMedia shareWebMedia = (ShareWebMedia) shareMedia;
            type = "webpage";

            //web object
            WXWebpageObject webpageObject = new WXWebpageObject();
            webpageObject.webpageUrl = shareWebMedia.getWebPageUrl();

            msg.mediaObject = webpageObject;
            msg.title = shareWebMedia.getTitle();
            msg.description = shareWebMedia.getDescription();
            msg.thumbData = BitmapUtils.bitmap2Bytes(shareWebMedia.getThumb());
        } else if(shareMedia instanceof ShareTextMedia) {   // Text sharing
            ShareTextMedia shareTextMedia = (ShareTextMedia) shareMedia;
            type = "text";

            //text object
            WXTextObject textObject = new WXTextObject();
            textObject.text = shareTextMedia.getText();

            msg.mediaObject = textObject;
            msg.description = shareTextMedia.getText();
        } else if(shareMedia instanceof ShareImageMedia) {  // Image sharing
            ShareImageMedia shareImageMedia = (ShareImageMedia) shareMedia;
            type = "image";

            //image object
            WXImageObject imageObject = new WXImageObject();
            / / image limit 10 m
            imageObject.imageData = BitmapUtils.compressBitmap(BitmapUtils.bitmap2Bytes(shareImageMedia.getImage()), 10 * 1024 * 1024);

            msg.mediaObject = imageObject;

            // Zoom the image directly
            Bitmap thumb = Bitmap.createScaledBitmap(shareImageMedia.getImage(), 200.200.true);
            msg.thumbData = BitmapUtils.bitmap2Bytes(thumb);
            thumb.recycle();
        } else if(shareMedia instanceof ShareMusicMedia) {  // Music sharing
            ShareMusicMedia shareMusicMedia = (ShareMusicMedia) shareMedia;
            type = "music";

            WXMusicObject musicObject = new WXMusicObject();
            musicObject.musicUrl = shareMusicMedia.getMusicUrl();

            msg.mediaObject = musicObject;
            msg.title = shareMusicMedia.getTitle();
            msg.description = shareMusicMedia.getDescription();
            msg.thumbData = BitmapUtils.bitmap2Bytes(shareMusicMedia.getThumb());
        } else if(shareMedia instanceof ShareVideoMedia) {      // Video sharing
            ShareVideoMedia shareVideoMedia = (ShareVideoMedia) shareMedia;
            type = "video";

            WXVideoObject videoObject = new WXVideoObject();
            videoObject.videoUrl = shareVideoMedia.getVideoUrl();

            msg.mediaObject = videoObject;
            msg.title = shareVideoMedia.getTitle();
            msg.description = shareVideoMedia.getDescription();
            msg.thumbData = BitmapUtils.bitmap2Bytes(shareVideoMedia.getThumb());
        } else {
            if(this.mShareListener ! =null) {
                this.mShareListener.onError(this.mConfig.getName(), "shareMedia error");
            }
            return ;
        }

        // Compress thumbnails to 32KB
        if(msg.thumbData ! =null && msg.thumbData.length > 'yao') {        // Determine the size in wechat SDK
            msg.thumbData = BitmapUtils.compressBitmap(msg.thumbData, 'yao');
        }

        / / initiate the request
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.message = msg;
        req.transaction = buildTransaction(type);

        if(this.mConfig.getName() == PlatformType.WEIXIN) {     // Share friends
            req.scene = SendMessageToWX.Req.WXSceneSession;
        } else if(this.mConfig.getName() == PlatformType.WEIXIN_CIRCLE) {      // Share your moments
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }

        if(!this.mWXApi.sendReq(req)) {
            if(this.mShareListener ! =null) {
                this.mShareListener.onError(this.mConfig.getName(), "sendReq fail");
            }
            LogUtils.e("wxapi sendReq fail"); }}Copy the code

Points to note in sharing:

  1. The image size of the photo sharing is within 10M
  2. Keep all thumbnails in 32KB

Then there are some other parameters that you can refer to the local Api documentation downloaded from the wechat SDK resources.

SendReq returns false if the argument is wrong and cannot be shared.

4 wechat result callback

Wechat requires the wxapi.wxentryActivity file to be executed in the project, which will be called by the callback. So we create a custom WXCallbackActivity, write everything in that file, and then the WXEntryActivity in the specific project just inherits from that Activity.

WXCallbackActivity see below:

public abstract class WXCallbackActivity extends Activity implements IWXAPIEventHandler {

    protected WXHandler mWXHandler = null;

    public WXCallbackActivity(a) {}protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SocialApi api = SocialApi.get(this.getApplicationContext());
        this.mWXHandler = (WXHandler)api.getSSOHandler(PlatformType.WEIXIN);
        this.mWXHandler.onCreate(this.getApplicationContext(), PlatformConfig.getPlatformConfig(PlatformType.WEIXIN));
        this.mWXHandler.getWXApi().handleIntent(this.getIntent(), this);
    }

    protected final void onNewIntent(Intent paramIntent) {
        super.onNewIntent(paramIntent);
        SocialApi api = SocialApi.get(this.getApplicationContext());
        this.mWXHandler = (WXHandler)api.getSSOHandler(PlatformType.WEIXIN);
        this.mWXHandler.onCreate(this.getApplicationContext(), PlatformConfig.getPlatformConfig(PlatformType.WEIXIN));
        this.mWXHandler.getWXApi().handleIntent(this.getIntent(), this);
    }

    public void onResp(BaseResp resp) {
        if(this.mWXHandler ! =null&& resp ! =null) {
            try {
                this.mWXHandler.getWXEventHandler().onResp(resp);
            } catch(Exception var3) { ; }}this.finish();
    }

    public void onReq(BaseReq req) {
        if(this.mWXHandler ! =null) {
            this.mWXHandler.getWXEventHandler().onReq(req);
        }

        this.finish(); }}Copy the code

The callback data is found to be processed primarily in onResp, and then in WXCallbackActivity the final processing is placed in WXHandler.

WXHandler callback handling:


public WXHandler(a) {
    this.mEventHandler = new IWXAPIEventHandler() {
        public void onResp(BaseResp resp) {
            int type = resp.getType();
            switch(type) {
                case ConstantsAPI.COMMAND_SENDAUTH:     // Authorization returns
                    WXHandler.this.onAuthCallback((SendAuth.Resp)resp);
                    break;

                case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:        // Share returns
                    WXHandler.this.onShareCallback((SendMessageToWX.Resp)resp);
                    break; }}public void onReq(BaseReq req) {}}; }// Validate the callback
protected void onAuthCallback(SendAuth.Resp resp) {
    switch (resp.errCode) {
        case BaseResp.ErrCode.ERR_OK:       // Authorization succeeded
            getAuthWithCode(resp.code);
            break;

        case BaseResp.ErrCode.ERR_USER_CANCEL:      // Authorization cancelled
            if(this.mAuthListener ! =null) {
                this.mAuthListener.onCancel(PlatformType.WEIXIN);
            }
            break;

        default:    // Authorization failed
            CharSequence err = TextUtils.concat(new CharSequence[]{"weixin auth error (", String.valueOf(resp.errCode), "):", resp.errStr});
            if(mAuthListener ! =null) {
                mAuthListener.onError(PlatformType.WEIXIN, err.toString());
            }
            break; }}Copy the code

Note that some of the constant definitions for the callback (ConstantsAPI.COMMAND_SENDAUTH, baseresp.errcode.err_OK, etc.) are defined in the native API. So, if you have a problem, take a look at the API documentation provided by wechat.

Wechat local API documentation

At the end

The above has realized the access of wechat platform. When the access party needs to access the wechat part, it only needs to reference social_sdK. jar and wechat SDK package into the project at the same time to invoke the login and sharing related to wechat.

The end of this article, will continue to access other platforms…