跳到主要內容

Quick Start

Integrating DID Connect is simplest by first creating a Blocklet. If you are unsure how to create a Blocklet, please refer to: Create Blocklet Document

Preconditions

  • Already installed and configured DID Wallet, and the phone and computer are connected to the same local area network.
  • The Blocklet using React template has been created, the following document uses @arcblock/did-connect, and the Blocklet has been successfully running.

Install dependencies

plain
npm install @/arcblock/did-connect
# yanr add @arcblock/did-connect
# pnpm i @arcblock/did-connect

Project Preparation

The following code is an example of requesting user personal information

In the server-side code of the project, add a lib/auth.js file:

javascript
const path = require('path');
const WalletAuthenticator = require('@blocklet/sdk/lib/wallet-authenticator');
const WalletHandler = require('@blocklet/sdk/lib/wallet-handler');

const authenticator = new WalletAuthenticator();
const handlers = new WalletHandler({
  authenticator,
});

module.exports = {
  handlers,
};

Then add the corresponding auth-handler file:

javascript
const omit = require('lodash/omit');

const action = 'request-profile';

module.exports = {
  action,

onConnect() {

return {

    profile: () => ({

      description: 'Please provide your full profile',

      fields: ['fullName', 'email', 'phone', 'signature', 'avatar', 'birthday'],

    }),

  }

},

  onAuth: ({ userDid, userPk, claims, updateSession }) => {
    const claim = claims.find((x) => x.type === 'profile');
    updateSession({
      result: {
        ...omit(claim, ['type', 'signature']),
        did: userDid,
        pk: userPk,
      },
    });
  },
};

Then the auth-handler needs to be registered in the entry file of the service-side code:

javascript
const express = require('express');
const app = express();

const { handlers } = require('./libs/auth');

handlers.attach({ app, ...require('./routes/auth/request-profile') });

const port = parseInt(process.env.BLOCKLET_PORT, 10);
app.listen(port, (err) => {
  if (err) throw err;
  logger.info(`> ${name} v${version} ready on ${port}`);
});

At this point, the server has the ability to respond to requests for user personal information in DID Connect. Next, we need to build the front-end part of the DID Connect code.

Add the ThemeProvider in the entry file of a React project (usually src/app.js):

javascript
import { ThemeProvider } from '@did-connect/react';

export default function WrappedApp() {
  return (
    <ThemeProvider>
      <App />
    </ThemeProvider>
  );
}

Connect Wallet

Add the following components to the application, and then mount the components onto a certain page:

javascript
import { useState } from 'react';
import useConnect from '@arcblock/did-connect/lib/Connect/use-connect';

function RequestProfileConnect() {
  const { connectApi, connectHolder } = useConnect();
  const [connectedUser, setConnectedUser] = useState({});

  const openConnect = () => {
    connectApi.open({
      action: 'request-profile',
      locale: 'en',
      onSuccess({ result }) {

setConnectedUser(result);
      },
      messages: {
        title: 'Request user profile',
        scan: 'Please provide your name and email to continue'
      },
    });
  }

  return (
    <header className="app-header">
      {!connectedUser && (
        <Button type="button" variant="contained" size="large" onClick={openConnect}>
          Continue With
        </Button>
      )}
      {connectedUser && (
        <div style={{ textAlign: 'left' }}>
          Connected: <pre>{JSON.stringify(connectedUser, null, 2)}</pre>
          <button type="button" onClick={​openConnect}>
            Switch User
          </button>
        </div>
      )}
      {connectHolder}
    </header>
  );
}

export default RequestProfileConnect;

The role of this component is: After the user connects the wallet, the user information is stored in connectedUser and displayed on the page.

The key part in the code:

javascript
connectApi.open({

action: 'request-profile',

locale: 'en',

onSuccess({ result }) {

setConnectedUser(result);

},

messages: {

title: 'Request user profile',

scan: 'Please provide your name and email to continue'

},
});
  • messages: The text that users see during the conversation
  • action: The name of the action corresponding to the server-side code
  • Locale: The language displayed in the current session
  • onSuccess: Callback after the current session is successful.

For complete examples, please refer to:

did-connect/playground/react at main · ArcBlock/did-connect