


A 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.
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_ID
The AppID
APPLICATION_ID
provided for the open platform is app
Package 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

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

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
