Ejemplo de código del método 2

// 第一步:用户在公众号中点击按钮,触发事件调用中间页面接口
function redirectToMiddlePage() {
  const appid = 'YOUR_APP_ID';
  const middlePageUrl = encodeURIComponent('http://yourwebsite.com/middle.html');
  const redirectUri = encodeURIComponent('http://yourwebsite.com/callback.html');
  const middleUrl = `http://yourwebsite.com/middle-api?appid=${appid}&redirect_uri=${redirectUri}`;

  // 向后台发送请求,获取中间页面的URL
  fetch(middleUrl)
    .then(response => response.json())
    .then(data => {
      if (data && data.middlePageUrl) {
        // 重定向到中间页面
        window.location.href = `${data.middlePageUrl}&state=${middlePageUrl}`;
      }
    })
    .catch(error => {
      console.error(error);
    });
}
// 第二步
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Middle Page</title>
</head>
<body>
  <script>
    (function() {
      const code = (new URLSearchParams(window.location.search)).get('code');
      const state = decodeURIComponent((new URLSearchParams(window.location.search)).get('state'));

      // 向你的后台服务器发送请求,传递code和state参数
      fetch('http://yourbackend.com/auth', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ code, state })
      })
        .then(response => response.json())
        .then(data => {
          if (data && data.openid) {
            // 在这里可以存储或使用用户的openid
            // ...
          }
        })
        .catch(error => {
          console.error(error);
        });

      // 重定向回前端页面
      window.location.href = state;
    })();
  </script>
</body>
</html>

 

Supongo que te gusta

Origin blog.csdn.net/qq_43314341/article/details/131228043
Recomendado
Clasificación