方法 1: ユーザーによるアクティブな承認
1. Web ページで承認されたドメイン名を公式アカウントに追加します (公式アカウントの設定で構成);
2. ユーザーを関連リンクまたはボタンをクリックするように誘導します;
3. ユーザーがクリックすると、設定した Web ページにジャンプします ;
4. WeChat Web ページ認証インターフェイスを通じてユーザーの openid を取得できます。
方法 2: 中間変換による
1. ユーザーが公式アカウントに指示を入力するか、関連するボタンをクリックする;
2. 公式アカウントがユーザーにカスタム リンクを送信し、ユーザーを中間ページにリダイレクトする;
3. 中間ページが通過するコード認証を使用してユーザーの openid を取得し、その openid をバックエンド サーバーに渡します。
方法 3: ミニ プログラムを使用する
1. 公式アカウントに関連付けられたミニ プログラムを提供します;
2. ユーザーがミニ プログラムでログインすると、ミニ プログラムはユーザーの openid を返します;
3. OpenID をバックグラウンド サーバーに渡すことができます。
方法 1 のコード例
<template>
<div>
<button @click="redirectToAuth">点击授权</button>
</div>
</template>
<script>
export default {
methods: {
redirectToAuth() {
const appid = 'YOUR_APP_ID';
const redirectUri = encodeURIComponent('http://yourwebsite.com/callback.html');
const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
window.location.href = authUrl;
},
},
mounted() {
const code = (new URLSearchParams(window.location.search)).get('code');
if (code) {
const appid = 'YOUR_APP_ID';
const requestUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=YOUR_APP_SECRET&code=${code}&grant_type=authorization_code`;
fetch(requestUrl)
.then(response => response.json())
.then(data => {
if (data && data.openid) {
const openid = data.openid;
// 在这里可以存储或使用用户的openid
// ...
}
})
.catch(error => {
console.error(error);
});
}
}
}
</script>