3️⃣Step 3 - Use the access point in your code
Before You Begin:
Make sure you have completed "Step 2 - Create your first access point with payments". Click Here.
Make sure you are familiar with access points and how to create them. Click Here.
Use Access Points in your Code:
Now, simply grab the access ID from the dashboard after you've set up the access point, and utilize it with "connectWithPopup" in your code.
Next, retrieve the "access" property, which is a List<String>, from getUser(), and verify whether the user has access to the content.
Here are code examples that will explain it better:
Need an example project?
https://github.com/eartho-group/one-client-react
Use the useEarthoOne
hook in your components to access the authentication state (isLoading
, isConnected
and user
) and authentication methods (connectWithPopup
and logout
):
// src/App.js
import React from 'react';
import { useEarthoOne } from '@eartho/one-client-react';
function App() {
const {
isLoading,
isConnected,
error,
user,
connectWithPopup,
logout,
} = useEarthoOne();
if (isLoading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Oops... {error.message}</div>;
}
if (isConnected) {
if(user.access.includes("YOUR_EARTHO_PREMIUM_ACCESS_ID")){
User Has Premium Access!
}
return (
<div>
Hello {user.displayName}{' '}
<button onClick={() => logout({ returnTo: window.location.origin })}>
Log out
</button>
</div>
);
} else {
return <button
className="btn premium_button"
id="login"
onClick={() => connectWithPopup({ accessId: "YOUR_EARTHO_PREMIUM_ACCESS_ID" })}
>
Log in
</button>;
}
}
export default App;
Use with a Class Component
Use the withEarthoOne
higher order component to add the earthoOne
property to Class components:
import React, { Component } from 'react';
import { withEarthoOne } from '@eartho/one-client-react';
class Profile extends Component {
render() {
// `this.props.earthoOne` has all the same properties as the `useEarthoOne` hook
const { user, logout } = this.props.earthoOne;
return <div>Hello {user.name}</div>;
}
}
export default withEarthoOne(Profile);
Need an example project? https://github.com/eartho-group/one-client-js 1. Copy the code below to your code 2. After you copied the code, don't forget to change the values of 2.1. YOUR_EARTHO_CLIENT_ID 2.2. redirect_uri 2.3. YOUR_EARTHO_ACCESS_ID You can find these values at https://creator.eartho.io/
If you are using Web version 9/8:
//1. Loading our SDK
import { createEarthoOne, connectWithPopup } from "@eartho/one-client-js";
const earthoOneConfig = {
clientId: "YOUR_EARTHO_CLIENT_ID",
authorizationParams: {
redirect_uri: window.location.origin
}
};
const earthoOne = createEarthoOne(earthoOneConfig);
async function checkPremium(){
const user = await earthoOne.getUser();
if(user.access.includes("YOUR_EARTHO_PREMIUM_ACCESS_ID")){
console.log("User Has Premium Access!")
}
}
//2. On clicking on this div, Eartho dialog will pop up.
<div onClick="connectToAccess">
</div>
//3. Defining a function to trigger the flow
function connectToAccess() {
const ACCESS_ID = "YOUR_EARTHO_ACCESS_ID";
earthoOne.connectWithPopup({accessId: ACCESS_ID})
.then(async () => {
//4. The ID token you need to pass to your backend:
const idToken = await earthoOne.getIdToken();
console.log("ID Token: " + idToken);
// Useful data for your client-side scripts:
const profile = earthoOne.getUser();
console.log('ID: ' + profile.uid); // Don't send this directly to your server!
console.log('Full Name: ' + profile.displayName);
console.log('Given Name: ' + profile.firstName);
console.log('Family Name: ' + profile.lastName);
console.log('Image URL: ' + profile.photoURL);
console.log('Email: ' + profile.email);
}).catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
});
}
function printCurrentMember(){
//You can also fetch the member in any time this way:
const earthoMember = earthoOne.getUser();
console.log(earthoMember);
}
If you are using JS vanilla:
//in your callback route (<MY_CALLBACK_URL>)
window.addEventListener('load', async () => {
earthoOne = new EarthoOne({
clientId: '<EARTHO_CLIENT_ID>',
});
const user = await earthoOne.getUser();
console.log(user);
});
async function checkPremium(){
const user = await earthoOne.getUser();
if(user.access.includes("YOUR_EARTHO_PREMIUM_ACCESS_ID")){
console.log("User Has Premium Access!")
}
}
document.getElementById('login').addEventListener('click', async () => {
await earthoOne.connectWithPopup({accessId:"YOUR_EARTHO_CLIENT_ID"});
});
Need an example project? https://github.com/eartho-group/one-client-vue
Add login to your application
In order to add login to your application you can use the connectWithRedirect
function that is exposed on the return value of useEartho
, which you can access in your component's setup
function.
<script>
import { useEartho } from '@eartho/one-client-vue';
export default {
setup() {
const { connectWithPopup, logout, getUser } = useEartho();
return {
login: () => {
connectWithPopup({access_id:"YOUR_EARTHO_ACCESS_ID"});
}
};
}
};
</script>
Calling an API
<script>
import { useEarthoOne } from '@eartho/one-client-vue';
export default {
setup() {
const { getIdToken } = useEarthoOne();
return {
doSomethingWithToken: async () => {
const token = await getIdToken();
const response = await fetch('https://api.example.com/posts', {
headers: {
Authorization: `Bearer ${token}`
}
});
const data = await response.json();
}
};
}
};
</script>
Need an example project? https://github.com/eartho-group/one-client-angular
Next, inject the AuthService
service into a component where you intend to provide the functionality to log in, by adding the AuthService
type to your constructor. Then, provide a connectWithRedirect()
method and call this.auth.connectWithRedirect()
to log the user into the application.
import { Component } from '@angular/core';
// Import the AuthService type from the SDK
import { AuthService } from '@eartho/one-client-angular';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'My App';
// Inject the authentication service into your component through the constructor
constructor(public auth: AuthService) {}
connectWithRedirect(): void {
// Call this to redirect the user to the login page
this.auth.connectWithPopup({access_id:"YOUR_EARTHO_ACCESS_ID"});
}
}
Need an example project? https://github.com/eartho-group/one-client-kotlin
Example of use in fragment
//1. Create config
private val config: EarthoOneConfig by lazy {
// -- REPLACE this credentials with your own Eartho app credentials!
val clientId = "YOUR_EARTHO_CLIENT_ID";
val clientSecret = "YOUR_EARTHO_CLIENT_SECRET";
val account = EarthoOneConfig(clientId, clientSecret)
}
//2. Create eartho one instance
private val earthoOne: EarthoOne by lazy {
EarthoOne(requireContext(), config)
}
//3. call connectWithRedirect and the user will be redirect
earthoOne.connectWithRedirect("YOUR_EARTHO_ACCESS_ID",
onSuccess = { result ->
//4. in case you want to manage users by yourself
sendToServer(result.idToken)
});
//Fetch id token
earthoOne.getIdToken()
//Or fetch user
earthoOne.getUser(onSuccess = { result ->
activity?.runOnUiThread {
binding.result.text = "Connected\n" + result.displayName
binding.resultImage.setImageURI(Uri.parse(result.photoURL))
}
});
Need an example project? https://github.com/eartho-group/one-client-swift
//1. Create eartho one instance.
// DO NOT FORGET to change the values. https://creator.eartho.world
let earthoOne = EarthoOne(
"YOUR_EARTHO_CLIENT_ID",
"YOUR_EARTHO_CLIENT_SECRET")
//2. call connectWithRedirect and the user will be redirect
earthoOne.connectWithPopup(
accessId: "YOUR_EARTHO_ACCESS_ID",
onSuccess: { Credentials in
//4. in case you want to manage users by yourself
let idToken = earthoOne.getIdToken()
//Or get user anytime after login
let user = earthoOne.getUser()
print(user?.displayName)
},
onFailure: { WebAuthError in
})
Need an example project? https://github.com/eartho-group/one-client-flutter
late EarthoOne earthoOne;
//1. Create eartho one instance
// DO NOT FOREGET to change the values. https://creator.eartho.world
earthoOne = EarthoOne(
clientId: "YOUR_EARTHO_CLIENT_ID",
clientSecret: "YOUR_EARTHO_CLIENT_SECRET");
//2. Call init function
earthoOne?.init();
//3. call connectWithRedirect and the user will be redirect
ElevatedButton(
onPressed: () async {
final credentials = await earthoOne?.connectWithRedirect("YOUR_EARTHO_ACCESS_ID");
setState(() {
_credentials = credentials;
});
},
child: const Text("Login")),
4. After Login
//Get user
final user = await earthoOne?.getUser();
//Get id token
final idToken = await earthoOne?.getIdToken();
Need an example project? https://github.com/eartho-group/one-client-react-native
import { init as earthoInit, connectWithRedirect, getIdToken, getUser } from '@eartho/one-client-react-native';
//1. Init the sdk
React.useEffect(() => {
earthoInit(
"YOUR_EARTHO_CLIENT_ID",
"YOUR_EARTHO_CLIENT_SECRET");
}, []);
//2. open the access dialog
connectWithRedirect("access id: e.g. YOUR_EARTHO_ACCESS_ID")
//3. Get id token or user
console.log(await getIdToken());
console.log(await getUser());
function example(){
Last updated