- 版本:4.1.1
- GitHub: https://github.com/sczerniawski/nativescript-social-login
- NPM: https://npmjs.net.cn/package/%40sczerniawski%2Fnativescript-social-login
- 下载
- 昨日:0
- 上周:0
- 上个月:4
NativeScript Social Login
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
进行签名。因此,当你在一个设备上运行调试构建时,Google 将允许使用与调试 keystore 相关联的 SHA1 对应的 .apk 进行身份验证。
- 在 Google 开发者网站上创建一个应用程序 这里。
- 输入应用程序名称。这可以是任何名称,但它将显示给正在认证的用户。
- 输入 Android 包名。包名是 android 应用名称,位于
package.json
下的nativescript
对象中,作为id
属性。 - 然后配置 Google 服务。
- 选择
Google Sign-In
- 输入你的签名证书 SHA-1。这是你在运行
keytool
命令的第一个步骤中获得的 SHA1 值。 - 启用 Google 登录
- 如果你只启用 Google 登录,你不需要在应用程序中配置文件。
- 运行应用程序,并且
loginWithGoogle()
应该返回与所选 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;
}
用法
包含
在代码-behind 中包含模块
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);
});