Home > Java > javaTutorial > body text

A brief analysis of the complete connection between Android app and WeChat authorized login and sharing (code sharing)

奋力向前
Release: 2021-09-13 13:49:17
forward
2488 people have browsed it

In the previous article "How to solve the timeout problem of SSH connection to Linux (share)", we introduced how to solve the timeout problem of SSH connection to Linux. The following article will help you understand the complete connection between Android app and WeChat authorized login and sharing. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

A brief analysis of the complete connection between Android app and WeChat authorized login and sharing (code sharing)

Android app and WeChat authorized login, sharing and complete docking

Preparation

Account system

Register on the WeChat open platform, create a mobile application, fill in a series of information, fill in the app signature and package name on the application platform, and after passing the review, obtain AppID and AppSecret

Loading sdk and initialization

Loading WeChatsdk

implementation 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
Copy after login
Copy after login

Initialization

public class App extends Application {
  public static IWXAPI iwxapi;
  public void onCreate() {
    super.onCreate();

    // 通过WXAPIFactory工厂,获取IWXAPI的实例
    iwxapi = WXAPIFactory.createWXAPI(this, BuildConfig.WXAPP_ID, true);
    // 将应用的appId注册到微信
    iwxapi.registerApp(BuildConfig.WXAPP_ID);
    //建议动态监听微信启动广播进行注册到微信
    registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 将该app注册到微信
            iwxapi.registerApp(BuildConfig.APPLICATION_ID);
        }
    }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));
  }
}
Copy after login

WXAPP_IDThe AppID

APPLICATION_ID provided for the open platform is appPackage name

Authorization login part

Create a new Package in the app root directory (/java/com.xxx.xxx/) wxapi, create a new Activity in wxapi named: WXEntryActivity, it looks like this: /java/com.xxx.xxx /wxapi/WXEntryActivity.java

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      // 隐藏状态栏
      getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
      //接收到分享以及登录的intent传递handleIntent方法,处理结果
      App.iwxapi.handleIntent(getIntent(), this);

  }

  @Override
  public void onReq(BaseReq baseReq) {
  }

  @Override
  public void onResp(BaseResp baseResp) {
    switch (baseResp.errCode) {
      case BaseResp.ErrCode.ERR_OK:  //微信回调成功
        String code = ((SendAuth.Resp) baseResp).code;
        //取得微信的code ,就可以干很多事情
        finish();
        break;
      case BaseResp.ErrCode.ERR_AUTH_DENIED://用户拒绝授权
        finish();
        break;
      case BaseResp.ErrCode.ERR_USER_CANCEL://用户取消
        finish();
        break;
      default:
        finish();
        break;
    }
  }
}
Copy after login

Obtain open information through code, such as openid, access_token Wait for a series of information.

private void getOpenInfo(String code) {
  OkHttpUtils.get().url("https://api.weixin.qq.com/sns/oauth2/access_token")
          .addParams("appid", BuildConfig.WXAPP_ID)
          .addParams("secret", BuildConfig.WXAPP_Secret)
          .addParams("code", code)
          .addParams("grant_type", "authorization_code")
          .build().execute(new StringCallback() {
      @Override
      public void onError(Call call, Exception e, int id) {
          Toast.makeText(WXEntryActivity.this, "微信授权失败", Toast.LENGTH_LONG).show();
          finish();
      }

      @Override
      public void onResponse(String response, int id) {
          JSONObject jsonObject = JSONObject.parseObject(response);
          String openId = jsonObject.getString("openid");
          String access_token = jsonObject.getString("access_token");
          Log.v("openId", openId + "---" + access_token);
          // 取得openid 又可以干很多事情
          // 在这里可以 对接 自己的 系统的用户信息等
          finish();
      }
  });
}
Copy after login

You can query user nickname, avatar and other information through openid.

private void getUserInfo(String access_token, String openid) {
  OkHttpUtils.get().url("https://api.weixin.qq.com/sns/userinfo")
          .addParams("access_token", access_token)
          .addParams("openid", openid)
          .build().execute(new StringCallback() {
      @Override
      public void onError(Call call, Exception e, int id) {
          finish();
          Toast.makeText(WXEntryActivity.this, "微信授权失败", Toast.LENGTH_LONG).show();
      }

      @Override
      public void onResponse(String response, int id) {
          //JSONObject jsonObject = JSONObject.parseObject(response);
          Log.v("response", response);
      }
  });
}
Copy after login

Sharing part

Share pictures:

/**
*bmp 分享图片
*width 缩略图宽
*height 缩略图高
*sence 分享场景 0:分享到对话,1:朋友圈 ,2:分享到收藏
*/
public static void Image(Bitmap bmp, int width, int height, int sence) {
    //初始化 WXImageObject 和 WXMediaMessage 对象
    WXImageObject imgObj = new WXImageObject(bmp);
    WXMediaMessage msg = new WXMediaMessage();
    msg.mediaObject = imgObj;

    //设置缩略图
    Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, width, height, true);
    //bmp.recycle();
    msg.thumbData = bmpToByteArray(thumbBmp);

    //构造一个Req
    SendMessageToWX.Req req = new SendMessageToWX.Req();
    req.transaction = buildTransaction("img");
    req.message = msg;
    req.scene = sence;
    req.userOpenId = App.userInfo.getOpenId();
    //调用api接口,发送数据到微信
    App.iwxapi.sendReq(req);
}
Copy after login

Share link

/**
*url: 分享链接
*title: 分享标题
*desc: 分享描述
*thumbBmp: 分享缩略图
*sence: 分享场景 0:分享到对话,1:朋友圈 ,2:分享到收藏
*/
public static void Url(String url, String title, String desc, Bitmap thumbBmp, int sence) {
    //初始化一个WXWebpageObject,填写url
    WXWebpageObject webpage = new WXWebpageObject();
    webpage.webpageUrl = url;

    //用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
    WXMediaMessage msg = new WXMediaMessage(webpage);
    msg.title = title;
    msg.description = desc;
    msg.thumbData = bmpToByteArray(thumbBmp);

    //构造一个Req
    SendMessageToWX.Req req = new SendMessageToWX.Req();
    req.transaction = buildTransaction("webpage");
    req.message = msg;
    req.scene = sence;
    req.userOpenId = App.userInfo.getOpenId();

    //调用api接口,发送数据到微信
    App.iwxapi.sendReq(req);
}
Copy after login

Two auxiliary functions

private static String buildTransaction(String type) {
    return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}

private static byte[] bmpToByteArray(Bitmap bmp) {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.PNG, 100, output);

    byte[] result = output.toByteArray();
    try {
        output.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
Copy after login

Notes

This forced library often fails to load, causing convulsions from time to time

implementation 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
Copy after login
Copy after login

Solution: down the package and load it manually, here: https ://bintray.com/wechat-sdk-team/maven

Download the corresponding version library such as: wechat-sdk-android-without-mta-6.6.5.aar, and put it in the libs directory. Just load it manually

android {
    compileSdkVersion 28

    repositories {  //本地aar方式
      flatDir {
        dirs 'libs' //this way we can find the .aar file in libs folder
      }
  }
}

implementation(name: 'wechat-sdk-android-without-mta-6.6.5', ext: 'aar')
Copy after login

The problem cannot be closed after sharing, that is, the finish fails

In fact, after the callback, it is notBaseResp.ErrCode.ERR_OK That’s it, there must be a layer of logical judgment:

public void onResp(BaseResp baseResp) {
  switch (baseResp.errCode) {
      case BaseResp.ErrCode.ERR_OK:
        // 在此处应该还需要判断 回调成功类型。是登录还是分享,然后做相对应的操作
        switch (baseResp.getType()) {
          case ConstantsAPI.COMMAND_SENDAUTH: //登录成功的回调
              String code = ((SendAuth.Resp) baseResp).code;
              // 登录 todo              
              break;
          case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX: //分享成功
              // 分享 todo
              Toast.makeText(getApplicationContext(), "分享成功!", Toast.LENGTH_LONG).show();
              finish();
              break;
          default:
              finish();
              break;
        }
      case BaseResp.ErrCode.ERR_USER_CANCEL://用户取消
        finish();
        break;
      default:
        finish();
        break;
  }
}
Copy after login

【End】

Recommended learning: java video tutorial

The above is the detailed content of A brief analysis of the complete connection between Android app and WeChat authorized login and sharing (code sharing). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:chuchur.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!