Git Product home page Git Product logo

zalo_flutter's Introduction

A Flutter plugin for Zalo APIs.

Note: This plugin is still under development, and some APIs might not be available yet. Feedback and Pull Requests are most welcome!

1. Setup

1.1 Create app Zalo

To access Zalo APIs, you'll need to make sure to create your application.

1.2 Get ZaloAppID

Then, you access to Dashboard (https://developers.zalo.me/app/[ZaloAppID]/settings). Remember your ZaloAppID

1.3 Import the package

To use this plugin, follow the plugin installation instructions.

1.4 Android integration

  1. Open android/app/build.gradle and edit
minSdkVersion 21 // or bigger
  1. Open to /android/app/src/main/AndroidManifest.xml and edit
<application
    ...
    android:name=".MyApplication">
    <activity
        ...
        android:name=".MainActivity">
        ...
    </activity>

    ...

    <!-- ZaloFlutter start -->
    <meta-data
        android:name="com.zing.zalo.zalosdk.appID"
        android:value="@string/zalo_flutter_app_id" />
    <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="@string/zalo_flutter_app_id_protocol"/>
        </intent-filter>
    </activity>
    <!-- ZaloFlutter end -->
</application>
...

<!-- ZaloFlutter start -->
<queries>
    <package android:name="com.zing.zalo" />
</queries>
<!-- ZaloFlutter end -->
  1. Create file strings.xml(if not exists) on folder /android/app/src/main/res/values/strings.xml. Replace with your ZaloAppID
<resources>
    <string name="zalo_flutter_app_id">[ZaloAppID]</string>
    <string name="zalo_flutter_app_id_protocol">zalo-[ZaloAppID]</string>
</resources>
  1. Open file main.dart and add this widget to get HashKey
    const ZaloHashKeyAndroid(),

Then, you build app and copy HashKey

  1. Open Zalo Dashboard => Login => Android (https://developers.zalo.me/app/[ZaloAppID]/login)

Paste HashKey and YourPackageName to this page and press Save

NOTE: If you upload file .aab to Google Store, it will generate another HashKey, copy it to Dashboard.

  1. Add proguard for zaloSDK
-keep class com.zing.zalo.**{ *; }
-keep enum com.zing.zalo.**{ *; }
-keep interface com.zing.zalo.**{ *; }

Continue with Kotlin

  • Edit the file MainActivity.kt as below. Remember YourPackageName
package [YourPackageName]

import io.flutter.embedding.android.FlutterActivity
import android.content.Intent // <-- Add this line
import com.zing.zalo.zalosdk.oauth.ZaloSDK // <-- Add this line

class MainActivity: FlutterActivity() {
    override fun onActivityResult(requestCode:Int, resultCode:Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        ZaloSDK.Instance.onActivityResult(this, requestCode, resultCode, data) // <-- Add this line
    }
}
  • Create file MyApplication.kt in same folder of MainActivity.kt. Replace with your YourPackageName
package [YourPackageName]

import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import com.zing.zalo.zalosdk.oauth.ZaloSDKApplication

class MyApplication : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
    override fun onCreate() {
        super.onCreate()
        ZaloSDKApplication.wrap(this)
    }
    override fun registerWith(registry: PluginRegistry) {}
}

Continue with Java

  • Edit the file MainActivity.java as below. Remember YourPackageName
package [YourPackageName];

import io.flutter.embedding.android.FlutterActivity;
import androidx.annotation.NonNull; // <-- Add this line
import io.flutter.embedding.engine.FlutterEngine; // <-- Add this line
import io.flutter.plugins.GeneratedPluginRegistrant; // <-- Add this line

import android.content.Intent; // <-- Add this line
import com.zing.zalo.zalosdk.oauth.ZaloSDK; // Add this line

public class MainActivity extends FlutterActivity {
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ZaloSDK.Instance.onActivityResult(this, requestCode, resultCode, data); // Add this line
    }
}
  • Create file MyApplication.java in same folder of MainActivity.java. Replace with your YourPackageName
package [YourPackageName]

import android.app.Application;

import com.zing.zalo.zalosdk.oauth.ZaloSDKApplication;

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        ZaloSDKApplication.wrap(this);
    }
}

iOS integration

  1. Open ios/Runner/Info.plist file, edit and replace with your ZaloAppID
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	...

	<!-- ZaloFlutter start-->
	<key>CFBundleURLTypes</key>
	<array>
		<dict>
			<key>CFBundleTypeRole</key>
			<string>Editor</string>
			<key>CFBundleURLName</key>
			<string>zalo</string>
			<key>CFBundleURLSchemes</key>
			<array>
				<string>zalo-[ZaloAppID]</string>
			</array>
		</dict>
	</array>
	<key>ZaloAppID</key>
	<string>[ZaloAppID]</string>
	<key>LSApplicationQueriesSchemes</key>
	<array>
		<string>zalosdk</string>
		<string>zaloshareext</string>
	</array>
      <!-- ZaloFlutter end-->
</dict>
</plist>
  1. Open ios/Runner/AppDelegate.swift file, add the following Zalo function code
import UIKit
import Flutter
import ZaloSDK // Add this line

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
    // Zalo function go here
    override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        return ZDKApplicationDelegate.sharedInstance().application(app, open: url, options: options)
    }
}
  1. Open ios/Runner.xcodeproj/project.pbxproj, search PRODUCT_BUNDLE_IDENTIFIER and copy your BundleID

  2. Open Zalo Dashboard => Login => IOS (https://developers.zalo.me/app/[ZaloAppID]/login) Paste BundleID to this page and press Save

Usage

Add the following import to your Dart code:

import 'package:zalo_flutter/zalo_flutter.dart';

Functions:

  • Get HashKey Android for register app in dashboard Zalo
String? data = await ZaloFlutter.getHashKeyAndroid();
  • Authenticate (with app or webview)
ZaloLogin data = await ZaloFlutter.login(
    refreshToken: refreshToken,
);
  • Log out - SDK clear oauth code in cache
await ZaloFlutter.logout();
  • Validate refresh token
bool data = await ZaloFlutter.validateRefreshToken(
    refreshToken: refreshToken,
);
  • Get Zalo user profile
ZaloProfile data = await ZaloFlutter.getUserProfile(
    accessToken: accessToken,
);

Author

Pham Tien Dung

If you have any questions, feel free to message me right away

Gmail: [email protected]

Github: https://github.com/tiendung01023

zalo_flutter's People

Contributors

metajet98 avatar phonghoang2k avatar tiendung01023 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

zalo_flutter's Issues

Cannot login when run the example project

I have tried your example project and the login function is not working any ways with a error:
{error_name:Invalid Parameter,error_reason:,ref_doc:https://developers.zalo.me/docs/api/social-api/tham-khao/user-access-token-post-4316,error_description:Invalid Parameter,error:-1040}

java.lang.Exception: DeviceHelper.getAdvertiseID call on main thread!!

Flutter version:

Flutter (Channel stable, 3.16.5, on macOS 13.5.1 22G90 darwin-arm64, locale en-VN)
E/getAdvertiseID(30585): java.lang.Exception: DeviceHelper.getAdvertiseID call on main thread!!
E/getAdvertiseID(30585): 	at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
E/getAdvertiseID(30585): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2308)
E/getAdvertiseID(30585): 	at android.os.Handler.dispatchMessage(Handler.java:106)
E/getAdvertiseID(30585): 	at android.os.Looper.loopOnce(Looper.java:201)
E/getAdvertiseID(30585): 	at android.os.Looper.loop(Looper.java:288)
E/getAdvertiseID(30585): 	at android.app.ActivityThread.main(ActivityThread.java:7898)
E/getAdvertiseID(30585): 	at java.lang.reflect.Method.invoke(Native Method)
E/getAdvertiseID(30585): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
E/getAdvertiseID(30585): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)

Got this error randomly with the login function? Any ideas how to fix it?

Android14 bị báo lỗi Bản zalo hiện tại không tương thích! mặc dù đã cập nhật bản mới nhất

Mình đang gặp lỗi không thể mở zalo trên android14 (những bản khác chạy bình thường).

Khi code chạy tới đây
Map<dynamic, dynamic> res = await ZaloFlutter.login(
refreshToken: refreshToken,
);
Show thông báo Zalo hiện tại không tương thích :

DEBUG CONSOLE:
D/ScrollerOptimizationManager( 6666): registerConfigChangedListener
W/libc ( 6666): Access denied finding property "ro.vendor.display.iris_x7.support"
D/VRIMainActivity: hardware acceleration = true, forceHwAccelerated = false
D/BufferQueueConsumer( 6666): connect: controlledByApp=false
E/OpenGLRenderer( 6666): Unable to match the desired swap behavior.
D/VRIMainActivity: vri.reportNextDraw android.view.ViewRootImpl.performTraversals:4376 android.view.ViewRootImpl.doTraversal:2992 android.view.ViewRootImpl$TraversalRunnable.run:10469 android.view.Choreographer$CallbackRecord.run:1671 android.view.Choreographer$CallbackRecord.run:1680
D/VRIMainActivity: vri.Setup new sync=wmsSync-VRI[MainActivity]#22
D/OpenGLRenderer( 6666): makeCurrent grContext:0xb40000779037c4e0 reset mTextureAvailable
D/BLASTBufferQueue( 6666): VRI[MainActivity]#11 acquireNextBufferLocked size=973x388 mFrameNumber=1 applyTransaction=true mTimestamp=1476429047394385(auto) mPendingTransactions.size=0 graphicBufferId=28630251995207 transform=0
D/VRIMainActivity: vri.reportDrawFinished

Hask key không tương thích với file aab

Hiện tại ứng dụng của mình có tích hợp phần đăng nhập thông qua Zalo và đang bị lỗi như sau:

Trường hợp 1 (Ứng dụng được build ra file apk dạng debug): Hash key tương ứng bản build ra file apk dạng debug thì thực hiện đăng nhập thành công

Trường hợp 2 (Ứng dụng được build ra file apk dạng release có dùng keystore): Hash key tương ứng bản build ra file apk dạng release thì thực hiện đăng nhập thành công

Trường hợp 3 (Ứng dụng được build ra file aab có dùng keystore và đã upload lên CHPlay): Hash key tương ứng bản build ra file aab thì thực hiện đăng nhập không thành công và báo lỗi ("error_name":"Invalid android sign key","error_reason":"Hash key is invalid","ref_doc":"https://developers.zalo.me/docs/api/social-api/tham-khao/user-access-token-post-4316","error_description":"Invalid android sign key")

Trường hợp 4: các thiết bị Android 13 là tất cả đều không thực hiện được đăng nhập bằng Zalo. Android 12 trở xuống thì sẽ gặp như Trường hợp 1, 2 và 3

Cho mình hỏi là hiện tại phần tạo Hash key này chỉ có hiệu lực trên các file apk hay sao, còn file aab thì thế nào có cách nào khác để tạo Hash key phù hợp với bản build dạng file aab không. Giữa cách tạo Hash key cho file apk và file aab có gì khác không?

Đang sử dụng thư viện phiên bản (zalo_flutter 0.0.5) https://pub.dev/packages/zalo_flutter

Rất mong được hổ trợ gấp phần này.

Lỗi trong trường hợp zalo chưa được đăng nhập trước đó

Mình hiện tại đang vướng 1 case khá là lạ
Trong trường hợp Zalo chưa được đăng nhập trước đó, mình thao tác login thì call back trả về không có data nào cả, mình check debug thì thấy nó không chạy vào OAuthCompleteListener. Giúp mình sửa đoạn này với ạ, mình cảm ơn !

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.