Sitemap

How to Integrate OCID into your dApp? Step-by-Step

6 min readNov 24, 2024
Press enter or click to view image in full size
https://id.opencampus.xyz/

Are you participating in the $250k EDU Chain Hackathon — Semester 2 or working on a new project on the Open Campus L3 (EduChain) but unsure how to get started? How does your dApp or platform interact with the Open Campus broad education ecosystem? How can you connect your dApp to the OC Ecosystem? while building on the EduChain.

To simplify this process, Open Campus has developed the Open Campus ID (OCID) and released an OCID Connect SDK.

This SDK makes it easy to integrate OCID into your dApp or any project you’re building.

Let’s dive in and learn everything from scratch — exploring the features of their SDK, understanding how to use it, and following the best practices to build your project effectively.

About Open Campus

Open Campus is a community-driven project (DAO) focused on creating a decentralized education system. It uses blockchain and Web3 technology to make learning better for everyone.

For example, Open Campus works with schools and organizations to help teachers earn rewards for creating educational content, while students can securely store their learning records on the blockchain. This way, education becomes more accessible and fair for all.

Making Education Decentralized and Accessible

About OCID

Open Campus ID is a Soulbound Token (SBT), a non-transferable NFT that represents a learner’s online persona.

As part of Open Campus’ blockchain protocol, it issues Decentralized Identifiers (DIDs) in the form of SBTs. These tokens give learners full control over their information.

They can choose what details to associate with their OC ID, such as their learning profile, and decide when and with whom to share them.

About OCID Connect SDK

Press enter or click to view image in full size

The OCID Connect SDK is a JavaScript-based tool that lets you integrate the Open Campus ID (OCID) into your app or platform.

Think of it as a way to add a “Connect with OCID” button to your site, similar to how websites offer “Login with Google” or “Login with Twitter.”

With this SDK, your users can securely link their OCIDs to your platform, giving them access to the Open Campus ecosystem.

For example, if you’re building an e-learning app, the SDK allows users to log in with their OCIDs. This connects their profile to the blockchain-based Open Campus education ecosystem, where their achievements and learning history are securely stored and easily accessible.

Why Do You Need It?

The OCID Connect SDK makes it simple to integrate Open Campus’ secure authentication system into your application. It provides pre-built tools like a JavaScript wrapper and React components to save you time and effort.

The SDK also adheres to the OpenID Connect (OIDC) standard, ensuring high security and compatibility with existing authentication systems.

Using the SDK, you can seamlessly retrieve user OCIDs and link them to your system, enabling features like personalized profiles, decentralized learning records, or exclusive ecosystem benefits — all with just a few lines of code.

How to Get Started (Step-by-Step)

Press enter or click to view image in full size
https://eduhub.dev/

The quickest way to get started is by using EduKit (also known as create-edu-dapp). If you’re stuck on something, unsure what to do, or prefer not to directly integrate the SDK into your application, you can use EduKit. It’s a starter kit that includes six pre-built example dApps with OCID and Web3 tools integrated, making it easy to build any type of dApp on EduChain.

To begin, open your terminal and run the following command:

npx create-edu-dapp your-dapp-name

After the setup, check the README.md file inside your project for further instructions, or find more details here.

There are two ways you can integrate the OCID Connect SDK into your Decentralized Application.

Choose the method that best fits your tech stack:

ReactJS/Next.js or JavaScript Integration.

1. ReactJS/Next.js Integration

If you’re building your dApp using ReactJS or Next.js, follow these steps:

Step 1: Install the SDK

Open your project terminal and run:

npm install @opencampus/ocid-connect-js

Step 2: Create a Wrapper Component

In your React/Next.js project, create a file:

components/OCConnectWrapper.jsx

Add the following code:

'use client';

import { OCConnect } from '@opencampus/ocid-connect-js';

export default function OCConnectWrapper({ children, opts, sandboxMode }) {
return (
<OCConnect opts={opts} sandboxMode={sandboxMode}>
{children}
</OCConnect>
);
}

This wraps your application and connects it to the OCID ecosystem. Replace sandboxMode with false for production use.

Step 3: Update Root Layout

In a Next.js project, update the layout file:

app/layout.jsx

Add the wrapper:

import OCConnectWrapper from '../components/OCConnectWrapper';

export default function RootLayout({ children }) {
const opts = {
redirectUri: 'http://localhost:3000/redirect',
referralCode: 'PARTNER6', // Your partner code
};

return (
<html lang="en">
<body>
<OCConnectWrapper opts={opts} sandboxMode={true}>
{children}
</OCConnectWrapper>
</body>
</html>
);
}

Step 4: Create a Redirect Page

Create a file for handling login redirects:

app/redirect/page.jsx

Add the following:

'use client';

import { LoginCallBack } from '@opencampus/ocid-connect-js';
import { useRouter } from 'next/navigation';

export default function RedirectPage() {
const router = useRouter();
const loginSuccess = () => router.push('/');
const loginError = (error) => console.error('Login error:', error);
return (
<LoginCallBack
successCallback={loginSuccess}
errorCallback={loginError}
/>
);
}

Step 5: Add a Login Button

Create a file for the login button:

components/LoginButton.jsx

Add this code:

'use client';

import { useOCAuth } from '@opencampus/ocid-connect-js';

export default function LoginButton() {
const { ocAuth } = useOCAuth();
const handleLogin = async () => {
try {
await ocAuth.signInWithRedirect({ state: 'opencampus' });
} catch (error) {
console.error('Login error:', error);
}
};
return <button onClick={handleLogin}>Login with OCID</button>;
}

Step 6: Use Components on Your Home Page

Update your home page:

app/page.jsx

Add:

'use client';

import LoginButton from '../components/LoginButton';
import { useOCAuth } from '@opencampus/ocid-connect-js';

export default function Home() {
const { authState } = useOCAuth();
if (authState.isLoading) return <div>Loading...</div>;
if (authState.error) return <div>Error: {authState.error.message}</div>;
return (
<div>
<h1>Welcome to My App</h1>
{authState.isAuthenticated ? (
<p>You are logged in! {JSON.stringify(authState)}</p>
) : (
<LoginButton />
)}
</div>
);
}

2. JavaScript Integration

If you’re using a library/framework other than ReactJS, such as VueJS or plain JavaScript, follow these steps:

Step 1: Initialize the SDK

Import and set up the SDK in your JavaScript file:

import { OCAuthSandbox } from '@opencampus/ocid-connect-js';

const authSdk = new OCAuthSandbox();

Step 2: Start the Login Process

Use the signInWithRedirect method to initiate login:

authSdk.signInWithRedirect({ state: 'opencampus' });

Step 3: Handle Login Response

After the login process, use handleLoginRedirect to retrieve user authentication data:

try {
const authState = await authSdk.handleLoginRedirect();
if (authState.idToken) {
console.log('Login successful:', authState);
} else {
console.log('Login incomplete');
}
} catch (error) {
console.error('Login error:', error);
}

Step 4: Access User Info

Retrieve the authenticated user’s OCID and wallet address:

const userOCId = authSdk.getAuthState().OCId;
const walletAddress = authSdk.getAuthState().ethAddress;
console.log('User OCID:', userOCId);
console.log('Wallet Address:', walletAddress);

Step 5: Move to Production

Switch from OCAuthSandbox to OCAuthLive for production:

import { OCAuthLive } from '@opencampus/ocid-connect-js';
const authSdk = new OCAuthLive();

Now you’re ready to integrate the OCID Connect SDK into your dApp using the different implementation ways that best fits your stack!

Important

  • Explore Documentation
    — Read the official docs to know about the key fundamentals of SDK.
  • Technical Guide
    — Check the GitHub Readme for more technical integration details.
  • Add the Connect Button
    — Use the Figma design to customize your “Connect with OCID” button.
  • Production Whitelisting
    — Whitelist your official project domain by filling out this form in order to have OCID Auth accessibility in Production Mode.

Note: Development Mode aka staging area doesn’t require any whitelisting, it’s just for testing purposes only.

With this, you’re all set to empower your dApp with Open Campus ID integration!

Stay updated with the latest in cutting-edge technology! Follow me:

Thanks for reading!

--

--

Asharib Ali
Asharib Ali

Written by Asharib Ali

✨ I build & teach AI and Blockchain stuff⚡

No responses yet