Table of Contents
Preparation
Authorization login part
Sharing part
Notes
Home Java javaTutorial A brief analysis of the complete connection between Android app and WeChat authorized login and sharing (code sharing)

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

Sep 13, 2021 pm 01:47 PM
java

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles