- 版本:1.0.0
- GitHub:
- NPM: https://npmjs.net.cn/package/nativescript-social-login-v2
- 下载
- 昨日:0
- 上周:1
- 上个月:9
NativeScript 社交登录
基于令牌的社交登录的 NativeScript 模块。
实现
提供者 | Android | iOS |
---|---|---|
是 | 是 | |
是 | 是 | |
否 | 否 |
许可证
文档
完整文档可在 readme.io 上找到。
更改
v1.4.x 至 1.5.x
- 实现了 iOS 登录
v1.3.x 至 1.4.x
- 实现了 iOS 登录
v1.2.x 至 1.3.x
ILoginConfiguration.google.isRequestAuthCode
的默认值现在为(false)
。这个行为未来将不再改变!
安装
运行
tns plugin add nativescript-social-login
在你的应用程序项目中安装模块。
Android
AndroidManifest.xml
权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- ... -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- ... -->
</manifest>
字符串
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="facebook_app_id">{{ YOUR_FACEBOOK_APP_ID }}</string>
<string name="fb_login_protocol_scheme">fb{{ YOUR_FACEBOOK_APP_ID }}</string>
</resources>
为调试构建设置 Android Google 登录
- 你需要与你机器上本地的
debug.keystore
关联的 SHA1 值。例如,以下命令可能是在 Windows 机器上运行的命令:
keytool -list -v -keystore C:/users/brad.martin/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
路径将根据您的机器上的路径而变化。Android 调试构建使用位于您机器上的默认 debug.keystore
进行签名。因此,当你在设备上运行调试构建时,由于它使用了与调试应用程序构建相关的 SHA1,Google 允许使用运行中的 .apk 进行身份验证。
- 在 Google 开发者网站上 这里 创建一个应用程序。
- 输入应用程序名称。这可以是任何名称,但将在验证用户时显示。
- 输入 Android 包名称。包名是 Android 应用名称,在 package.json 下的
nativescript
对象中作为id
属性。 - 接下来配置 Google 服务。
- 选择
Google Sign-In
- 输入你的签名证书 SHA-1。这是在运行
keytool
命令的第一步时获得的 SHA1 值。 - 启用 Google 登录
- 如果你只启用 Google 登录,你不需要在应用程序内部配置配置文件。
- 运行应用程序,并应返回与所选 Google 帐户相关联的数据。
iOS
GoogleService-Info.plist
你应该为你的应用程序生成一个 GoogleService-Info.plist
文件,并将其添加到 /app/App_Resources/iOS
文件夹中。你可以在此处找到此文件和更多信息 - https://developers.google.com/identity/sign-in/ios/start-integrating
Info.plist
将以下内容添加到位于 app/App_Resources/iOS 的 Info.plist 文件中
<!-- FACEBOOK AND GOOGLE LOGIN -->
<key>CFBundleURLTypes</key>
<array>
<!-- GOOGLE START -->
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>{YOUR_GOOGLE_REVERSED_CLIENT_ID}</string>
<!-- It shoud look like this: com.googleusercontent.apps.123123123-172648sdfsd76f8s7d6f8sd -->
<!-- Get it from your GoogleService-Info.plist -->
<!-- Read more - https://developers.google.com/identity/sign-in/ios/start-integrating -->
</array>
</dict>
<!-- GOOGLE END -->
<!-- FACEBOOK START -->
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb{YOUR_FACEBOOK_APP_ID_HERE}</string>
</array>
</dict>
</array>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>FacebookAppID</key>
<string>{YOUR_FACEBOOK_APP_ID_HERE}</string>
<key>FacebookDisplayName</key>
<string>FacebookLoginDemo</string>
<!-- FACEBOOK END -->
https://developers.facebook.com/docs/ios
应用程序主文件
将此添加到开始应用程序的文件中。如果您使用 Angular,则在 application.start({ /* */ });
或 platformNativeScriptDynamic().bootstrapModule(/* */)
之前添加以下代码
TypeScript
if (application.ios) {
class MyDelegate extends UIResponder implements UIApplicationDelegate {
public static ObjCProtocols = [UIApplicationDelegate];
applicationDidFinishLaunchingWithOptions(application: UIApplication, launchOptions: NSDictionary): boolean {
let gglDelegate = false;
try {
const errorRef = new interop.Reference();
GGLContext.sharedInstance().configureWithError(errorRef);
const signIn = GIDSignIn.sharedInstance();
gglDelegate = true;
} catch (error) {
console.log(error);
}
const fcbDelegate = FBSDKApplicationDelegate.sharedInstance().applicationDidFinishLaunchingWithOptions(application, launchOptions); // facebook login delegate
return gglDelegate || fcbDelegate;
}
applicationOpenURLSourceApplicationAnnotation(application, url, sourceApplication, annotation) {
const fcbDelegate = FBSDKApplicationDelegate.sharedInstance().applicationOpenURLSourceApplicationAnnotation(application, url, sourceApplication, annotation); // facebook login delegate
const gglDelegate = GIDSignIn.sharedInstance().handleURLSourceApplicationAnnotation(url, sourceApplication, annotation); // google login delegate
return fcbDelegate || gglDelegate;
}
}
application.ios.delegate = MyDelegate;
}
JavaScript
if (application.ios) {
var MyDelegate = (function (_super) {
__extends(MyDelegate, _super);
function MyDelegate() {
return _super !== null && _super.apply(this, arguments) || this;
}
MyDelegate.prototype.applicationDidFinishLaunchingWithOptions = function (application, launchOptions) {
var gglDelegate = false;
try {
var errorRef = new interop.Reference();
GGLContext.sharedInstance().configureWithError(errorRef);
var signIn = GIDSignIn.sharedInstance();
gglDelegate = true;
}
catch (error) {
console.log(error);
}
var fcbDelegate = FBSDKApplicationDelegate.sharedInstance().applicationDidFinishLaunchingWithOptions(application, launchOptions); // facebook login delegate
return gglDelegate || fcbDelegate;
};
MyDelegate.prototype.applicationOpenURLSourceApplicationAnnotation = function (application, url, sourceApplication, annotation) {
var fcbDelegate = FBSDKApplicationDelegate.sharedInstance().applicationOpenURLSourceApplicationAnnotation(application, url, sourceApplication, annotation); // facebook login delegate
var gglDelegate = GIDSignIn.sharedInstance().handleURLSourceApplicationAnnotation(url, sourceApplication, annotation); // google login delegate
return fcbDelegate || gglDelegate;
};
return MyDelegate;
}(UIResponder));
MyDelegate.ObjCProtocols = [UIApplicationDelegate];
application.ios.delegate = MyDelegate;
}
用法
包含
在您的代码背后包含模块
import SocialLogin = require("nativescript-social-login");
初始化
import Application = require("application");
import SocialLogin = require("nativescript-social-login");
if (Application.android) {
Application.android.on(Application.AndroidApplication.activityCreatedEvent, (event) => {
let result = SocialLogin.init({
activity: event.activity,
});
});
}
init()
函数接收一个(可选的)具有以下结构的对象
interface ILoginConfiguration {
/**
* The underlying custom activity to use.
*/
activity?: android.app.Activity;
/**
* Facebook specific configuration.
*/
facebook?: {
/**
* Initialize Facebook or not. Default: (true)
*/
initialize?: boolean;
/**
* Should Logout current Facebook session or not. Default: (false)
*/
clearSession?: boolean;
}
/**
* Google specific configuration.
*/
google?: {
/**
* Initialize Google or not. Default: (true)
*/
initialize?: boolean;
/**
* The server client ID for requesting server auth token.
*/
serverClientId?: string;
/**
* If true, it will request for offline auth code which server can use for fetching or refreshing auth tokens.
* It will be set in authCode property of result object.
*
* If false (default), it will request for token id. it will be set in authToken property of result object.
*/
isRequestAuthCode?: boolean;
}
/**
* Fallback action for the result of the underlying activity.
*/
onActivityResult?: (requestCode: number, resultCode: number, data: any) => void;
}
init()
返回的result
对象具有以下结构
interface IInitializationResult {
facebook: {
error: any,
isInitialized: boolean,
},
google: {
error: any,
isInitialized: boolean,
},
twitter: {
error: any,
isInitialized: boolean,
}
}
isInitialized
可以是(true)
表示成功,(false)
表示失败,(undefined)
表示“不支持”,以及(null)
表示跳过的提供商。
如果初始化过程中抛出异常,则定义error
属性。
登录
如果您想使用登录函数,必须提交一个回调,该回调接收一个具有以下结构的对象
interface ILoginResult {
/**
* Gets the auth token (if requested).
*/
authToken?: string;
/**
* Offline auth code used by servers to request new auth tokens.
*/
authCode?: string;
/**
* Gets the result code.
*/
code: LoginResultType;
/**
* The display name.
*/
displayName?: string;
/**
* First name of the user.
*/
firstName?: string;
/**
* Last name of the user.
*/
lastName?: string;
/**
* Gets the error (if defined).
*/
error?: any;
/**
* The ID of the user.
*/
id?: string;
/**
* The photo URL.
*/
photo?: string;
/**
* Gets the underlying provider.
*/
provider?: string;
/**
* The user token, like email address.
*/
userToken?: string;
}
以下函数已实现
提供者 | 提供者 |
---|---|
loginWithFacebook | |
loginWithGoogle |
示例
SocialLogin.loginWithFacebook(
(result) => {
console.log("code: " + result.code);
console.log("error: " + result.error);
console.log("userToken: " + result.userToken);
console.log("displayName: " + result.displayName);
console.log("photo: " + result.photo);
console.log("authToken: " + result.authToken);
}
);
值得注意的是,对于基于Angular的应用,此回调应在NgZone
中包装,以便Angular在完成时正确处理视图更新。
import { Component, NgZone } from "angular/core";
@Component({})
class SigninComponent {
constructor(private ngZone: NgZone) {}
login() {
SocialLogin.loginWithFacebook((result) => {
this.ngZone.run(() => {
console.log("code: " + result.code);
console.log("error: " + result.error);
console.log("userToken: " + result.userToken);
console.log("displayName: " + result.displayName);
console.log("photo: " + result.photo);
console.log("authToken: " + result.authToken);
});
});
}
}
还有来自dgomezs的优秀示例,展示了如何为Facebook配置您的应用程序。
日志记录
如果您想获取模块的日志输出,可以使用SocialLogin.addLogger()
函数添加一个回调,该回调接收来自模块的消息
SocialLogin.addLogger(function(msg: any, tag: string) {
console.log('[nativescript-social-login]: (' + tag + '): ' + msg);
});