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

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:+'

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));
  }
}

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;
    }
  }
}

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();
      }
  });
}

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);
      }
  });
}

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);
}

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);
}

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;
}

Notes

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

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

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')

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;
  }
}

【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
This article is reproduced at:禅境花园. If there is any infringement, please contact admin@php.cn delete
Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

Is Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksIs Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksMay 13, 2025 am 12:03 AM

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

Demystifying the JVM: Your Key to Understanding Java ExecutionDemystifying the JVM: Your Key to Understanding Java ExecutionMay 13, 2025 am 12:02 AM

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

See all articles

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

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools