Zalo SDK集成指南
配置部分
1.官方sdk链接 https://developers.zalo.me/docs/sdk/android-sdk/tong-quan
2.zalo sdk主要提供的功能
- 集成zalo登录
- 获取用户信息,朋友列表
- 支持android4.3及以上
3.demo链接 https://gitlab.com/zalosdk/repositories
集成步骤
第一步:去Zolo后台创建应用 http://developers.zalo.me
需要提供包名,签名文件SHA1的Base64编码(也称为密钥散列)
//签名文件SHA1的Base64编码获取方法 public static String getApplicationHashKey(Context ctx) throws Exception { PackageInfo info = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); String sig = Base64.encodeToString(md.digest(), Base64.DEFAULT).trim(); if (sig.trim().length() > 0) { return sig; } } }
第二步
在app的build.gradle文件配置
//仓库地址 repositories { maven { url "https://gitlab.com/api/v4/projects/50747855/packages/maven" } } //依赖 implementation "me.zalo:sdk-core:+" implementation "me.zalo:sdk-auth:+" implementation "me.zalo:sdk-openapi:+"
第三步
appId配置
//res下的strings.xml <string name="appID"> 替换成你的appID </string> //清单文件 AndroidManifest.xml <!-- Required zalo app id --> <meta-data android:name="com.zing.zalo.zalosdk.appID" android:value="@string/appID" />
//android11及以上需要以下配置才能调用Zalo登录
<queries>
<package android:name="com.zing.zalo" />
</queries>
第四步
Application配置
方法一:没有自己的Application
<application android:name="com.zing.zalo.zalosdk.oauth.ZaloSDKApplication" />
方法二:如果有自己的Application
public class DemoApplication extends Application { @Override public void onCreate() { super.onCreate(); ZaloSDKApplication.wrap(this);//加入这一行就行了 } }
第五步
配置Zalo的web登录
//android12(api>=31)需要声明 android:exported="true"
<activity android:name="com.zing.zalo.zalosdk.oauth.BrowserLoginActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="zalo-{你的appID}" />
</intent-filter>
</activity>
第六步
混淆配置
-keep class com.zing.zalo.\*\*{ \*; } -keep enum com.zing.zalo.\*\*{ \*; } -keep interface com.zing.zalo.\*\*{ \*; }
代码部分
登录部分
注意:
oauthCode 仅仅10分钟有效,所以活到到 oauthCode 后,立即获取 AccessToken 和 RefreshToken
AccessToken 是1小时有效,用与调用官方api
RefreshToken 是三个月有效,用于检查登录和登出
(这个还不是很懂)授权码 code challenge 和 code verifier
- code_challenge = Base64.encode(SHA-256.hash(ASCII(code_verifier))
- code_verifier 是任何字符串 数字
第一步
调用登录
//loginVia :APP 只使用App进行登录 ; WEB 只使用Web进行登录 ;APP_OR_WEB 有app调app没app调web,最好选这个,不然产品会跳脚
ZaloSDK.Instance.authenticateZaloWithAuthenType (Activity, LoginVia loginVia, String codeChallenge, OAuthCompleteListener) //default extInfo null,不使用透传,一般服务端没啥要求的我们选这个 //ZaloSDK.Instance.authenticateZaloWithAuthenType (Activity, LoginVia loginVia, String codeChallenge, JSONObject extInfo, OAuthCompleteListener)
添加监听器
OAuthCompleteListener listener = new OAuthCompleteListener() { @Override public void onAuthenError(ErrorResponse errorResponse) { //授权失败 } @Override public void onGetOAuthComplete(OauthResponse response) { String code = response.getOauthCode() //授权成功 } };
第二步
获取登录返回的数据
@Override protected void onActivityResult(int reqCode, int resCode, Intent d) { super.onActivityResult(requestCode, resultCode, data); ZaloSDK.Instance.onActivityResult(this, reqCode, resCode, d); }
获取Access Token部分
//ctx 应用的上下文; oacode 登录返回的 ;codeVerifier 见登录代码部分
ZaloSDK.Instance.getAccessTokenByOAuthCode( Context ctx,String oacode, String codeVerifier, new ZaloOpenAPICallback() { @Override public void onResult(JSONObject data) { int err = data.optInt("error"); if (err == 0) { //clearOauthCodeInfo(); //clear used oacode access_token = data.optString("access_token");//访问官方api的token refresh_token = data.optString("refresh_token");//登录的token,过期了要重新登录,有效期3个月 long expires_in = Long.parseLong(data.optString("expires_in"));//access_token的过期时间,默认3600s //Store data token in app cache .... } } });
获取Access Token部分2
因为access token的过期时间1小时,所以过期之后我们需要通过refresh token去重新获取
ZaloSDK.Instance.getAccessTokenByRefreshToken(Context ctx,String refresh_token, new ZaloOpenAPICallback() { @Override public void onResult(JSONObject data) { int err = data.optInt("error"); if (err == 0) { access_token = data.optString("access_token"); refresh_token = data.optString("refresh_token");//必须要重新保存它哦,因为通过refresh token获取access token只能使用一次,下一次请求必须使用这个新的 long expires_in = Long.parseLong(data.optString("expires_in")); //Update new data token in app cache .... } } });
验证Refresh Token是否有效
ZaloSDK.Instance.isAuthenticate(refreshToken, new ValidateCallback() { @Override public void onValidateComplete(boolean validated, int errorCode, OauthResponse oauthResponse) { if (validated) { // refreshToken còn hiệu lực... long expireTime = oauthResponse.getExpireTime(); } } });
登出
ZaloSDK.Instance.unauthenticate();
获取用户的基本信息(userId,userName,头像地址)
//field:id , picture ,name
ZaloSDK.Instance.getProfile(
Context ctx,String access_token, ZaloOpenAPICallback callback, String[] fields)
//返回示例
{
"id": "UserId",
"name": "User Name",
"picture": {
"data": {
"url": "User avatar url"
}
}
}
附录
code Verifier生成示例
private fun genCodeVerifier(): String { val sr = SecureRandom() val code = ByteArray(32) sr.nextBytes(code) return Base64.encodeToString(code, Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING) }
code Challenge生成示例
private fun genCodeChallenge(codeVerifier: String): String { var result = "" try { val bytes = codeVerifier.toByteArray(charset("US-ASCII")) val md = MessageDigest.getInstance("SHA-256") md.update(bytes, 0, bytes.size) val digest = md.digest() result = Base64.encodeToString( digest, Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING ) } catch (_: Exception) { } return result }
Error Code错误码对照表
| Error code | Describe |
|---|---|
| -5000 | App id is invalid |
| -5001 | Invalid callback url |
| -5002 | Invalid client secret |
| -5003 | Invalid oauthorized code |
| -5004 | Invalid access token |
| -5005 | Invalid ios bundle id |
| -5006 | Invalid android package |
| -5007 | Invalid Session |
| -5008 | Invalid android sign key |
| -5009 | Invalid code challenge |
| -5010 | Invalid code verifier |
| -5011 | Invalid refresh token |
| -5012 | Invalid oa id |
| -5013 | Invalid body data |
| -5014 | Invalid required params |
| -5015 | Invalid grant type |
| -5016 | Authorized code expired |
| -5017 | Refresh token expired |
| -5018 | Invalid state |
| -5019 | Refresh token is not guest refresh token |
| -6000 | user is invalid |
| -6001 | Invalid Permission (not in white list) |
| -6002 | User not login |
| -6003 | User not consent |
| -6004 | User not own OA |
| -6005 | User banned |
| -7000 | Invalid csrf token |
| -7001 | Cannot create access token |
| -7002 | Could not create Authorized code. |
| -7003 | Had an error when verify session user |
| -7004 | Your application might be not approve or disable by admin |
| -7005 | Process forgot passwd guest account failed |
| -7006 | Build redirect uri failed |
| -7007 | WEB_VIEW_LOGIN_NOT_ALLOWED |
| -7008 | USER_BACK |
| -7009 | USER_REJECT |
| -7010 | ZALO_WEBVIEW_COOKIE_ERROR |
| -7011 | CANT_LOGIN_GOOGLE |
| -7012 | CANT_LOGIN_FACEBOOK |
| -7013 | CANT_LOGIN_ZINGME |
| -8000 | There was an unknown error |
| -8001 | NO_NETWORK |
| -9000 | Invalid parameter |
| -9001 | Invalid user id |
| -9002 | Can’t resolve to a valid user ID |
| -9003 | Your app don’t link with any Official Account |
| -9004 | User not visible |
| -9005 | Accessing friend requests requires the extended permission read_requests |
| -9006 | Session key invalid. This could be because the session key has an incorrect format, or because the user has revoked this session |
| -9007 | Sending of requests has been temporarily disabled for this application |
| -9008 | Syntax error |
| -9009 | Call fail |
| -9010 | Method is not support for this api |
| -9011 | unknown exception |
| -9012 | Item not exits |
| -9013 | App Id in use is disabled or banded |
| -9014 | Quota for your app is limited |
| -9015 | Limit of friends list is too large. Maximum: 50 |
| -9016 | Quota daily for your app is limited |
| -9017 | Quota weeky for your app is limited |
| -9018 | Quota monthly for your app is limited |
| -9019 | Quota monthly for your app is limited |
| -9020 | User has not played game for 30 days ago |
| -9021 | Do not disturb user. User hasn’t talked to friend for 30 days ago |
| -9022 | Recipient was reached quota message recieve (1 message per 3 days) |
| -9023 | Sender and Recipient is not friend |
| -9024 | Quota daily per user for your app is limited |
| -9025 | Your friend is not using app |
| -9026 | Your friend is using app |

浙公网安备 33010602011771号