


Detailed graphic and text explanation of Android development WeChat authorized login and WeChat sharing analysis
Mar 15, 2017 pm 05:19 PMThis article mainly introduces the detailed explanation with pictures and textsAndroid Development of WeChat authorized login and WeChat sharing analysis. It has certain reference value. If you need it, you can learn more.
Preface
In the wave of mobile Internet, Internet-connected APPs have killed single-machine devices on the beach. Many companies hope that their applications can have an account system, but many users do not necessarily buy it. : Why should I register an account for your application? Weibo, WeChat, and QQ have almost become must-install applications on everyone’s mobile phone, so WeChat, Weibo, and QQ said: Come on, come on, you can use my account to log in to your home applications, as long as you follow OAuth2.0 Just the protocol standard. Therefore, third-party social account login has become the choice of many emerging applications. Since the online documents of Tencent’s official WeChat open platform are somewhat different from the latest SDK, and the structural order of login-related documents is somewhat disordered, I will record some of my experiences here today. , to organize the official online documents of the WeChat open platform. At the same time, WeChat sharing can expand the influence of your own APP, so the WeChat sharing function is also a function that many developers need. I have compiled it here, hoping to be helpful to future friends in the same field.
WeChat login
The following content is excerpted from Tencent Open Platform: https://open.weixin.qq.com/cgi -bin/showdocument?action=dir_list&t=resource/res_list&verif y=1&id=open1419317851&token=6bfe3acd2969037c7217667f24f8eeaf714e5113&lang=zh_CN
Authorization process description
WeChat OAuth2.0 authorized login allows WeChat users to use WeChat identitySecurity Log in to third-party applications or websites. After the WeChat user authorizes to log in to the third-party application that has accessed WeChat OAuth2.0, the third party can obtain the user's Interface calling credentials (access_token), through access_token, the authorization relationship interface of the WeChat open platform can be called, so as to obtain the basic open information of WeChat users and help users realize basic open functions.
WeChat OAuth2.0 authorized login currently supports authorization_code mode, which is suitable for application authorization with server side. The overall process of this model is:
1. A third party initiates a WeChat authorized login request. After the WeChat user allows authorization of the third-party application, WeChat will launch the application or redirect to the third-party website, and bring Authorize the temporary ticket code parameter;
2. Add AppID and AppSecret through the code parameter, and exchange for access_token through API;
3. Pass access_token makes an interface call to obtain the user's basic data resources or help the user implement basic operations.
Get access_token sequence diagram:
Note: If the developer needs to call the login interface, developer authentication needs to be performed and submitted 300Dayang, the official online document says that there is no need to pay. In fact, that is the past tense, but the online document has not been updated.
The following will explain the WeChat authorized login process in sequence. All network requests are GET requests.
1. Get temporary ticket code
2. Get access_token & openid
3. Check whether access_token is valid
4. Refresh or renew access_token
5. Get WeChat user details
Get temporary ticket code
The first three arrows pointing to the right
{ // 發(fā)出授權(quán)申請(qǐng) Final SendAuth.Req req = new SendAuth.Req(); req.scope = "snsapi_userinfo"; req.state = "wechat_sdk_微信登錄,分享demo_test"; api.sendReq(req); }
The process of the two arrows pointing to the left is reflected in the code:
public void onResp(BaseResp resp) ;// 這個(gè)回調(diào)接口位于IWXAPIEventHandler中
The returned data is resp. When used to request login authorization, it is an instance of SendAuth.Resp. The data carried is:
ErrorCode: ERR_OK = 0 (user agrees); ERR_AUTH_DENIED = -4 (user refuses authorization); ERR_USER_CANCEL = -2 (user cancels)
code: The code that the user exchanges for access_token, Only valid when ErrCode is 0
state: A flag used by a third-party program to identify the uniqueness of its request when sending. It is passed in when the third-party program calls sendReq and is sent by the WeChat terminal. Return, state string length cannot exceed 1K
lang:微信客戶端當(dāng)前語(yǔ)言
country:微信客戶端當(dāng)前國(guó)家
以上數(shù)據(jù)均以static String形式存在SendAuth.Resp的resp對(duì)象中。
注意:當(dāng)使用微信提供最新的SDK/library時(shí),上面有些數(shù)據(jù)是不存在,微信開(kāi)放平臺(tái)的文檔和API及SDK沒(méi)有同步更新。讀者可使用最下方微信登錄,分享demo中的筆者使用的jar包構(gòu)建工程。
獲取access_token & openid
最后一條向右的箭頭表示:使用得到的code,獲取access_token,openid,接口為:
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
注意:微信的接口鏈接是使用SSL的安全鏈接,普通的HttpClient訪問(wèn)會(huì)導(dǎo)致應(yīng)用崩潰或報(bào)錯(cuò),詳細(xì)方法請(qǐng)下載最下方的微信登錄,分享demo代碼
參數(shù)說(shuō)明
appid: 應(yīng)用唯一標(biāo)識(shí),在微信開(kāi)放平臺(tái)提交應(yīng)用審核通過(guò)后獲得
secret:應(yīng)用密鑰AppSecret,在微信開(kāi)放平臺(tái)提交應(yīng)用審核通過(guò)后獲得
code :填寫第一步獲取的code參數(shù)
grant_type:固定值,填authorization_code
最下方向左的箭頭表示使用code訪問(wèn)完鏈接返回的數(shù)據(jù),json攜帶的數(shù)據(jù)有:
access_token:接口調(diào)用憑證
expires_in:access_token的有效期,一般為7200(秒),也即是兩小時(shí)
refresh_token:用戶刷新access_token
openid:授權(quán)用戶唯一標(biāo)識(shí)
scope:用戶授權(quán)的作用域,使用逗號(hào)(,)分隔
檢查access_token是否有效
由于access_token有效期為兩小時(shí),所以進(jìn)行下一步操作前最好進(jìn)行一次檢查,接口為:
https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID
傳入的參數(shù)為accesss_token和openid。
access_token有效時(shí)返回的json是:
{ "errcode":0,"errmsg":"ok" }
失效時(shí)的返回?cái)?shù)據(jù)為:
{ "errcode":40003,"errmsg":"invalid openid" }
如果access_token有效,則跳過(guò)下一步,失效時(shí)需要刷新或續(xù)期access_token。
刷新或續(xù)期access_token
接口說(shuō)明
access_token是調(diào)用授權(quán)關(guān)系接口的調(diào)用憑證,由于access_token有效期(目前為2個(gè)小時(shí))較短,當(dāng)access_token超時(shí)后,可以使用refresh_token進(jìn)行刷新,access_token刷新結(jié)果有兩種:
1.若access_token已超時(shí),那么進(jìn)行refresh_token會(huì)獲取一個(gè)新的access_token,新的超時(shí)時(shí)間;
2.若access_token未超時(shí),那么進(jìn)行refresh_token不會(huì)改變access_token,但超時(shí)時(shí)間會(huì)刷新,相當(dāng)于續(xù)期access_token。
refresh_token擁有較長(zhǎng)的有效期(30天),當(dāng)refresh_token失效的后,需要用戶重新授權(quán)。
刷新accessToken接口為:
https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
參數(shù)說(shuō)明:
appid:應(yīng)用唯一標(biāo)識(shí)
grant_type:固定值,填refresh_token
refresh_token:填寫前面獲取到的refresh_token的值
返回的json數(shù)據(jù)有:
access_token:接口調(diào)用憑證
expires_in:access_token接口調(diào)用憑證超時(shí)時(shí)間,單位(秒)
refresh_token:用戶刷新access_token
openid:授權(quán)用戶唯一標(biāo)識(shí)
scope:用戶授權(quán)的作用域,使用逗號(hào)(,)分隔
獲取微信用戶詳細(xì)信息
獲取access_token,openid后,就可以用來(lái)獲取更多用戶信息,比如微信昵稱,頭像,性別等。接口為:
https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
可獲取的json攜帶的數(shù)據(jù)有:
openid:普通用戶的標(biāo)識(shí),對(duì)當(dāng)前開(kāi)發(fā)者帳號(hào)唯一
nickname:普通用戶昵稱
sex:普通用戶性別,1為男性,2為女性
province:普通用戶個(gè)人資料填寫的省份
city:普通用戶個(gè)人資料填寫的城市
country:國(guó)家,如中國(guó)為CN
headimgurl:用戶頭像,最后一個(gè)數(shù)值代表正方形頭像大?。ㄓ?、46、64、96、132數(shù)值可選,0代表640*640正方形頭像),用戶沒(méi)有頭像時(shí)該項(xiàng)為空
privilege:用戶特權(quán)信息,json數(shù)組,如微信沃卡用戶為(chinaunicom)
unionid:用戶統(tǒng)一標(biāo)識(shí)。針對(duì)一個(gè)微信開(kāi)放平臺(tái)帳號(hào)下的應(yīng)用,同一用戶的unionid是唯一的。
微信官方建議:
開(kāi)發(fā)者最好保存unionID信息,以便以后在不同應(yīng)用之間進(jìn)行用戶信息互通。
微信登錄的流程結(jié)束了, 至于開(kāi)發(fā)者需要將那些用戶信息上傳到自家的app服務(wù)器就取決于開(kāi)發(fā)者了。
微信分享
1、微信分享分為微信好友分享,朋友圈分享,當(dāng)然,還有收藏也是共用分享的接口,無(wú)需授權(quán)登錄即可調(diào)用分享接口。
2、由于好友分享,朋友圈分享和收藏只是一個(gè)參數(shù)的區(qū)別,所以下面只講好友分享,具體的可以下載最下方的微信登錄,分享demo源碼進(jìn)行查看。
3、微信可以分享的內(nèi)容包括,純文字,圖片,鏈接,音樂(lè),視頻,app,emoji表情等。
微信分享流程
1、在你的工程里面新建一個(gè)wxapi包,并且新建一個(gè)WXEntryActivity,繼承Activity,或其他Activity(這兩步是必須的,微信開(kāi)發(fā)文檔中有提到),詳見(jiàn):
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=1417751808&token=&lang=zh_CN
2、并在manifest文件里面加上exported屬性,設(shè)置為true。
3、實(shí)現(xiàn)一個(gè)IWXAPIEventHandler接口。
微信發(fā)送的請(qǐng)求將回調(diào)到onReq方法,發(fā)送到微信請(qǐng)求的響應(yīng)結(jié)果將回調(diào)到onResp方法
在WXEntryActivity中將接收到的intent及實(shí)現(xiàn)了IWXAPIEventHandler接口的對(duì)象傳遞給IWXAPI接口的handleIntent方法,示例如下:
api.handleIntent(getInent(),this);
當(dāng)微信發(fā)送請(qǐng)求到你的應(yīng)用,將通過(guò)IWXAPIEventHandler接口的onReq方法進(jìn)行回調(diào),類似的,應(yīng)用請(qǐng)求微信的響應(yīng)結(jié)果將通過(guò)onResp回調(diào)。
注意
如果需要混淆代碼,為了保證sdk的正常使用,需要在proguard.cfg加上下面兩行配置:
-keep class com.tencent.mm.sdk.** { *; }
微信分享詳細(xì)代碼流程是:
IWXAPI api = WXAPIFactory.createWXAPI(this, APP_ID, false);// 傳入申請(qǐng)到的appid,得到一個(gè)IWXAPI的實(shí)例 api.registerApp(APP_ID);// 將app注冊(cè)到微信列表,我不知道這是什么意思,有知道的請(qǐng)告訴我,謝謝! // 開(kāi)始分享純文本到給好友 WXTextObject textObj = new WXTextObject(); textObj.text = text; // 用WXTextObject對(duì)象初始化一個(gè)WXMediaMessage對(duì)象 WXMediaMessage msg = new WXMediaMessage(); msg.mediaObject = textObj; // 發(fā)送文本類型的消息時(shí),title字段不起作用 // msg.title = "Will be ignored"; msg.title = "分享文字標(biāo)題"; msg.description = text; // 構(gòu)造一個(gè)Req SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("text"); // transaction字段用于唯一標(biāo)識(shí)一個(gè)請(qǐng)求 req.message = msg; req.scene = SendMessageToWX.Req.WXSceneTimeline;// 表示發(fā)送場(chǎng)景為朋友圈,這個(gè)代表分享到朋友圈 // req.scene = SendMessageToWX.Req.WXSceneSession;//表示發(fā)送場(chǎng)景為好友對(duì)話,這個(gè)代表分享給好友 // req.scene = SendMessageToWX.Req.WXSceneFavorite;// 表示發(fā)送場(chǎng)景為收藏,這個(gè)代表添加到微信收藏 // 調(diào)用api接口發(fā)送數(shù)據(jù)到微信 api.sendReq(req);
上面大致的表現(xiàn)了一個(gè)分享純文本給好友的場(chǎng)景,如果需要分享到朋友圈,只需要更改req.scene字段值。
1、其中IWXAPI.registerAPP(APP_ID)是官方demo中的一行代碼,表示的是將app注冊(cè)到微信列表,我并不知道有什么用,所謂的微信列表出現(xiàn)在哪兒?該行代碼刪除后,仍然可以獲取登錄授權(quán),實(shí)現(xiàn)分享等功能。有知道的請(qǐng)告訴我,謝謝!
2、目前筆者遇到無(wú)法分享在線圖片WXImageObject的問(wèn)題,分享在線圖片時(shí)出現(xiàn)分享界面右上角“發(fā)送”按鈕灰色,無(wú)法點(diǎn)擊的情況,希望分享成功的朋友告訴我,謝謝!問(wèn)題如下圖
要分享鏈接,圖片,音樂(lè),視頻等需要將WXTextObject 對(duì)象改成對(duì)應(yīng)的obj對(duì)象。詳細(xì)請(qǐng)下載文章下方的微信登錄,分享demo。
后記
由于微信官方demo中并未提供微信登錄的代碼示例,分享的代碼很齊全,可是分享在線圖片的代碼在我這里卻又問(wèn)題,所以筆者將自己的一些經(jīng)驗(yàn)和遇到的坑總結(jié)在這里,包括了微信第三方登錄,微信分享的內(nèi)容,希望對(duì)大家有所幫助。也希望筆者在文中提到的問(wèn)題有熱心人能夠解答
//1、 注冊(cè)到微信列表有什么用,微信列表在哪兒可以看到 IWXAPI.registerApp(APP_ID); //2、 我為什么無(wú)法使用以下代碼分享在線圖片 WXImageObject imgObj = new WXImageObject(); imgObj.imageUrl = imgUrl;// 在線圖片鏈接 WXMediaMessage msg = new WXMediaMessage(); msg.mediaObject = imgObj; Bitmap bmp = BitmapFactory.decodeStream(new URL(url).openStream()); Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true); bmp.recycle(); msg.thumbData = Util.bmpToByteArray(thumbBmp, true); SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("img"); req.message = msg; req.scene = isTimelineCb.isChecked() ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession; api.sendReq(req);
最近有人向我反映生成的apk無(wú)法正常運(yùn)行。在此進(jìn)行解釋:
The reason why the apk generated by the demo source code cannot run normally is that when adding an application to the WeChat open platform, the package name, application signature, and app_id are bound. The apk you signed does not work, and the demo code is for reference and communication only.
The above is the detailed content of Detailed graphic and text explanation of Android development WeChat authorized login and WeChat sharing analysis. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

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

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)