Exponent 应用集成 Google。Exponent 提供了比较少的 native API, 因为你可以直接 HTTP 访问 Google 的 REST APIs 比如: fetch
// Example of using the Google REST API
async function getUserInfo(accessToken) {
let userInfoResponse = await fetch('https://www.googleapis.com/userinfo/v2/me', {
headers: { Authorization: `Bearer ${accessToken}`},
});
return userInfoResponse;
}
在 Exponent 客户端里,你只能用 WebView 方式登录。如果你 build 一个 standalone app, 你可以用该平台的 native 登录,文档最后会详细介绍。
使用 Google 登录,你需要在 Google Developer Console 创建一个项目,然后创建一个 OAuth 2.0 client ID。
https://oauth.host.exp.com
到 "Authorised redirect URIs"。import Exponent from 'exponent';
async function signInWithGoogleAsync() {
try {
const result = await Exponent.Google.logInAsync({
webClientId: YOUR_CLIENT_ID_HERE,
scopes: ['profile', 'email'],
});
if (result.type === 'success') {
return result.accessToken;
} else {
return {cancelled: true};
}
} catch(e) {
return {error: true};
}
}
Exponent.Google.
logInAsync
(options)¶提示用户用 Google 登录,并且授予 app 权限来获取该用户 Google 的部分信息
- param object options
参数map。
- behavior (string) -- 用什么方式登录, 支持
web
或者system
。 本地 (system
) 只支持 standalone app (按照下面的步骤 build)。默认在 Exponent 应用里是web
, standalone 里是system
.- scopes (array) -- 当前登录需要 Google 的哪些权限(数组), 权限为字符串, 具体参考: (https://gsuite-developers.googleblog.com/2012/01/tips-on-using-apis-discovery-service.html). 默认权限是
['profile', 'email']
。- webClientId (string) -- 这个 app 在 Google 注册的 client ID, 支持 web 登录。
- iosClientId (string) -- 这个 app 在 Google 注册的 client ID, 支持 standalone app 本地登录。
- returns
如果用户或者 Google 取消登录,返回
{ type: 'cancel' }
.否则的话,返回
{ type: 'success', accessToken, idToken, serverAuthCode, user: {...profileInformation} }
.accessToken
是一个字符串,用来请求 Google HTTP API。
如果你想在 standalone app 里支持 native 登录,你可以按照下面的步骤。不需要的话,
你只需要在 signInAsync
options 参数里定义 behavior: 'web'
, 跳过下面
这些步骤就好了。
keytool -list -printcert -jarfile growler.apk | grep SHA1 | awk '{ print $2 }'
(替换 growler.apk
为第 2 步生成的apk).exp.json
里的 package name, (比如: ca.brentvatne.growlerprowler) 到 Package name 字段. 保存.exp.json
,添加 client id 到 android.config.googleSignIn.apiKey
.keytool -list -printcert -jarfile growler.apk | grep SHA1 | awk '{ print $2 } | sed -e 's/\://g'
(替换 growler.apk
为第 2 步生成的apk).exp.json
, key 为 android.config.googleSignIn.certificateHash
.Exponent.Google.logInAsync(..)
的时候, 一定要把第 1 步拿到的 Web Application client ID 作为 webClientId
option 传参。我们也不知道为什么 Google 在 Android 上需要这一步,我们就姑且这么做把。如果你想在 standalone app 里支持 native 登录,你可以按照下面的步骤。不需要的话,
你只需要在 signInAsync
options 参数里定义 behavior: 'web'
, 跳过下面
这些步骤就好了。
bundleIdentifier
到你的 exp.json
bundleIdentifier
, 然后点击 "Create".exp.json
, key 为 ios.config.googleSignIn.reservedClientId
.Exponent.Google.logInAsync
的时候, 把 "Client ID" 作为 iosClientId
option, 比如: Exponent.Google.logInAsync({iosClientId: YOUR_CLIENT_ID, ...etc});
.