メインコンテンツにスキップ

WeChat mini program

情報

WeChat Mini Program support is available from Casdoor 1.41.0.

WeChat Mini Program does not use standard OAuth redirects, so sign-in uses the mini program’s login code sent to Casdoor instead of a redirect to the Casdoor page. Example: casdoor-wechat-miniprogram-example. See also WeChat Mini Program login.

Config: CASDOOR_HOSTNAME — the Casdoor server URL (e.g. https://door.casbin.com).

ステップ1:Casdoorをデプロイする

Deploy the Casdoor server. Then:

  1. Confirm Casdoor is reachable and working.
  2. In conf/app.conf, set origin to CASDOOR_HOSTNAME.

Casdoor設定

Step 2: Configure the application

  1. In Casdoor, create an OAuth provider with type WeChat and set APPID and APPSECRET from the WeChat Mini Program admin. WeChat_MiniProgram.png
  2. Create or edit a Casdoor application and add that WeChat provider.
Casdoor uses the first WeChat-type provider in the application as the Mini Program IdP. Use only one WeChat provider per app if you use Mini Program.

Step 3: Mini program code

The mini program calls wx.login() to get a login code, then sends that code to Casdoor. Casdoor exchanges it with WeChat for OpenID and SessionKey. Example:

// Login in mini program
wx.login({
success: res => {
// This is the login code that needs to be sent to Casdoor
console.log(res.code)

wx.request({
url: `${CASDOOR_HOSTNAME}/api/login/oauth/access_token`,
method: "POST",
data: {
"tag": "wechat_miniprogram", // Required
"client_id": "6825f4f0af45554c8952",
"code": res.code,
"username": this.data.userInfo.nickName, // Update user profile when you log in.
"avatar": this.data.userInfo.avatarUrl,
},
header:{
"content-type": "application/x-www-form-urlencoded",
},
success: res => {
console.log(res)
this.globalData.accessToken = res.data.access_token // Get Casdoor's access token
}
})
}
})

tagパラメータは、これがWeChatミニプログラムからのリクエストであることをCasdoorに通知するために必須であることに注意してください。

上記のコードには、ログイン時のWeChatミニプログラムユーザーのユーザー名とアバターURIが含まれています。 これら2つのパラメータを別々に渡し、成功したログインとアクセストークンの取得後にCasdoorに渡すことができます:

wx.getUserProfile({
desc: 'share your info to Casdoor',
success: (res) => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
console.log(app.globalData.accessToken)
wx.request({
url: `${CASDOOR_HOSTNAME}/api/update-user`, // Casdoor URL
method: "POST",
data: {
"owner": "test",
"name": "wechat-oGk3T5tIiMFo3SazCO75f0HEiE7Q",
"displayName": this.data.userInfo.nickName,
"avatar": this.data.userInfo.avatarUrl
},
header: {
"Authorization": "Bearer " + app.globalData.accessToken, // Bearer token
"content-type": "application/json"
},
success: (res) => {
console.log(res)
}
})
}
})

さらに、必要なCasdoor操作に対してアクセストークンをベアラートークンとして使用することができます。

Tips

現在、Casdoorは既存のアカウントをWeChatミニプログラムユーザーにバインドすることはできません。 CasdoorがWeChatからOpenIDを取得した後、IDが存在しない場合は新しいユーザーを作成し、存在する場合は既存のユーザーを使用します。