Flutter Kakao认证插件kakao_flutter_sdk_auth的使用

发布于 1周前 作者 caililin 来自 Flutter

Flutter Kakao认证插件kakao_flutter_sdk_auth的使用

本文档介绍了如何在Flutter项目中使用Kakao认证插件(kakao_flutter_sdk_auth)。该插件目前支持Android和iOS平台,并将在未来支持web平台。

要求

以下是使用该插件所需的条件:

  • Dart 3.3.0或更高版本
  • Flutter 3.19.0或更高版本
  • Android Studio 3.6.1或更高版本
  • 目标Android API级别21或更高(Android 5.0 (Lollipop)或更高)
  • Xcode 11.0或更高版本
  • iOS 11.0或更高版本
  • iOS部署目标11.0或更高版本
  • Web浏览器支持

如何开发

要将Kakao API与Flutter SDK集成,请阅读以下文档:

如何贡献

如果您想为本仓库做出贡献,请阅读以下文档:

许可证

该软件根据以下Apache 2许可证授权,引用如下:

Copyright 2019 Kakao Corp. https://www.kakaocorp.com

Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this project except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0.

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.

### 完整示例Demo

#### 1. 添加依赖

首先,在`pubspec.yaml`文件中添加`kakao_flutter_sdk_auth`依赖项:

```yaml
dependencies:
  flutter:
    sdk: flutter
  kakao_flutter_sdk_auth: ^1.0.0

然后运行flutter pub get以获取新添加的依赖项。

2. 初始化SDK

main.dart文件中初始化Kakao SDK。在main()函数中添加以下代码:

import 'package:flutter/material.dart';
import 'package:kakao_flutter_sdk_auth/kakao_flutter_sdk_auth.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await KakaoSdk.init(nativeAppKey: 'YOUR_NATIVE_APP_KEY');
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Kakao Login Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              _loginWithKakao();
            },
            child: Text('Login with Kakao'),
          ),
        ),
      ),
    );
  }

  Future<void> _loginWithKakao() async {
    try {
      // 开始登录流程
      var authCode = await AuthCodeClient.instance.authorize();
      print("Auth Code: $authCode");
      
      // 使用Auth Code获取Access Token
      var token = await OAuthClient.instance.tokenWithAuthCode(authCode);
      print("Token: ${token.accessToken}");
    } catch (e) {
      print("Error: $e");
    }
  }
}

3. 配置Android

android/app/src/main/AndroidManifest.xml文件中添加Kakao登录回调URL:

<activity android:name="com.kakao.sdk.auth.AuthServiceActivity">
  <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="com.yourapp.scheme" android:host="oauth"/>
  </intent-filter>
</activity>

4. 配置iOS

ios/Runner/Info.plist文件中添加Kakao登录回调URL:

<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>kakaoYOURAPPKEY</string>
    </array>
  </dict>
</array>

更多关于Flutter Kakao认证插件kakao_flutter_sdk_auth的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter Kakao认证插件kakao_flutter_sdk_auth的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter应用中使用kakao_flutter_sdk_auth插件进行Kakao认证的示例代码。这个插件允许你的Flutter应用通过Kakao账户进行用户认证。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加kakao_flutter_sdk_auth依赖:

dependencies:
  flutter:
    sdk: flutter
  kakao_flutter_sdk_auth: ^latest_version  # 请替换为最新的版本号

然后运行flutter pub get来安装依赖。

2. 配置Android项目

在Android项目的android/app/src/main/AndroidManifest.xml文件中,添加必要的权限和Kakao SDK的配置:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <!-- 添加必要的权限 -->
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        ...>

        <!-- Kakao SDK配置 -->
        <meta-data
            android:name="com.kakao.sdk.app_key"
            android:value="YOUR_KAKAO_APP_KEY"/>
        <activity
            android:name="com.kakao.auth.AuthorizationActivity"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:launchMode="singleTop"
            android:noHistory="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="YOUR_KAKAO_REDIRECT_URI"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

YOUR_KAKAO_APP_KEYYOUR_KAKAO_REDIRECT_URI替换为你的Kakao开发者控制台中配置的实际值。

3. 配置iOS项目

对于iOS项目,你需要在Info.plist文件中添加Kakao SDK的配置,并在AppDelegate.swiftAppDelegate.m中进行一些设置(假设你使用Swift):

Info.plist中添加:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>YOUR_KAKAO_REDIRECT_URI</string>
        </array>
    </dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>kakaotalk</string>
    <string>kakaostory</string>
    <string>kakaolink</string>
    <string>kakaoapi</string>
</array>

AppDelegate.swift中添加:

import UIKit
import Flutter
import KakaoSDK // 确保你已经通过CocoaPods安装了KakaoSDK

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    KakaoSDK.initialize(with: .init(appKey: "YOUR_KAKAO_APP_KEY"))
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

  override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    if KakaoSDK.handleOpen(url, options: options) {
      return true
    }
    return super.application(app, open: url, options: options)
  }
}

4. 使用Kakao认证

在你的Flutter代码中,你可以使用kakao_flutter_sdk_auth插件进行认证。以下是一个简单的示例:

import 'package:flutter/material.dart';
import 'package:kakao_flutter_sdk_auth/kakao_flutter_sdk_auth.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _accessToken = '';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Kakao Auth Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('Access Token: $_accessToken'),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: _loginWithKakao,
                child: Text('Login with Kakao'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _loginWithKakao() async {
    try {
      final result = await KakaoAuth.login();
      setState(() {
        _accessToken = result.accessToken;
      });
      print('User Info: ${result.userProfile}');
    } catch (e) {
      print('Error: $e');
    }
  }
}

在这个示例中,当用户点击“Login with Kakao”按钮时,应用会尝试使用Kakao账户进行认证,并在成功后显示访问令牌和用户信息。

请确保你已经正确配置了Kakao开发者控制台,并且你的应用有权访问所需的Kakao API。

回到顶部