In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you "java how to achieve Android app and Wechat authorized login function", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "java how to achieve Android app and Wechat authorized login function" this article.
Prepare for
Account system
Register for the Wechat open platform, create a mobile application, fill in a series of information, fill in the app signature and package name in the application platform, and obtain AppID and AppSecret after approval.
Load sdk and initialize
Load Wechat sdk
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 (); / / obtain the IWXAPI instance iwxapi = WXAPIFactory.createWXAPI (this, BuildConfig.WXAPP_ID, true) through the WXAPIFactory factory; / / register the applied appId to Wechat iwxapi.registerApp (BuildConfig.WXAPP_ID) / / it is recommended to dynamically monitor Wechat to start broadcasting to register with Wechat registerReceiver (new BroadcastReceiver () {@ Override public void onReceive (Context context, Intent intent) {/ / register the app to Wechat iwxapi.registerApp (BuildConfig.APPLICATION_ID);}, new IntentFilter (ConstantsAPI.ACTION_REFRESH_WXAPP));}}
AppID provided by WXAPP_ID for open platform
APPLICATION_ID is the name of the app package
Authorization login section
Create a new Packagewxapi in the app root directory (/ java/com.xxx.xxx/) and a new Activity name in wxapi: WXEntryActivity, which 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); / / hides the status bar getWindow () .setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); / / receives the sharing and the login intent transmits the handleIntent method, and processes the result 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: / / Wechat callback successful String code = ((SendAuth.Resp) baseResp) .code; / / get the code of Wechat, you can do a lot of things finish (); break Case BaseResp.ErrCode.ERR_AUTH_DENIED:// user refuses to authorize finish (); break; case BaseResp.ErrCode.ERR_USER_CANCEL:// user cancels finish (); break; default: finish (); break;}
Get open information through code, such as openid,access_token and so on.
Private void getOpenInfo (String code) {OkHttpUtils.get () .url ("https://api.weixin.qq.com/sns/oauth3/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, "Wechat authorization failed", 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) / / you can do a lot of things to get openid / / here you can dock your own system's user information and other finish ();}});}
You can query users' nicknames, avatars 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, "Wechat authorization failure", 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 sharing pictures * width thumbnails width * height thumbnails high * sence sharing scenarios 0: share to conversation, 1: moments, 2: share to favorites * / public static void Image (Bitmap bmp, int width, int height, int sence) {/ / initialize WXImageObject and WXMediaMessage objects WXImageObject imgObj = new WXImageObject (bmp); WXMediaMessage msg = new WXMediaMessage (); msg.mediaObject = imgObj / / set thumbnail Bitmap thumbBmp = Bitmap.createScaledBitmap (bmp, width, height, true); / / bmp.recycle (); msg.thumbData = bmpToByteArray (thumbBmp); / / construct a Req SendMessageToWX.Req req = new SendMessageToWX.Req (); req.transaction = buildTransaction ("img"); req.message = msg; req.scene = sence; req.userOpenId = App.userInfo.getOpenId () / / call the API api to send data to Wechat App.iwxapi.sendReq (req);}
Share links
/ * url: sharing link * title: sharing title * desc: sharing description * thumbBmp: sharing thumbnail * sence: sharing scenario 0: sharing to conversation, 1: moments, 2: sharing to favorites * / public static void Url (String url, String title, String desc, Bitmap thumbBmp, int sence) {/ / initialize a WXWebpageObject and fill in url WXWebpageObject webpage = new WXWebpageObject (); webpage.webpageUrl = url / initialize a WXMediaMessage object with WXWebpageObject object WXMediaMessage msg = new WXMediaMessage (webpage); msg.title = title; msg.description = desc; msg.thumbData = bmpToByteArray (thumbBmp); / / construct a Req SendMessageToWX.Req req = new SendMessageToWX.Req (); req.transaction = buildTransaction ("webpage"); req.message = msg; req.scene = sence; req.userOpenId = App.userInfo.getOpenId () / / call the API api to send data to Wechat 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,100, output); byte [] result = output.toByteArray (); try {output.close ();} catch (Exception e) {e.printStackTrace ();} return result;} considerations
This forced library often fails to load and freak out from time to time.
Implementation 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
Solution: give the package to down 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, put it in the libs directory, and load it manually.
Android {compileSdkVersion 28 repositories {/ / Local 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 that cannot be closed after sharing, that is, the failure of finish
In fact, after the callback, BaseResp.ErrCode.ERR_OK is not finished. There has to be a layer of logical judgment:
Public void onResp (BaseResp baseResp) {switch (baseResp.errCode) {case BaseResp.ErrCode.ERR_OK: / / you should also need to determine the type of callback success here. Log in or share, and then do the corresponding operation switch (baseResp.getType ()) {case ConstantsAPI.COMMAND_SENDAUTH: / / callback of successful login String code = ((SendAuth.Resp) baseResp) .code; / / login todo break Case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX: / / share success / / share todo Toast.makeText (getApplicationContext (), "share success!" , Toast.LENGTH_LONG) .show (); finish (); break; default: finish (); break;} case BaseResp.ErrCode.ERR_USER_CANCEL:// user cancels finish (); break; default: finish (); break }} these are all the contents of this article entitled "how java implements Android app and Wechat authorized login function". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.