网页登录实现qq和微信扫码登录

实现网页登录实现qq和微信扫码登录可以分为以下步骤:

  1. 获取qq或微信开放平台的APPID和APPSECRET,创建应用,并获取授权域名。

  2. 在后台创建接口,用于前端发送请求获取qq或微信登陆二维码。二维码生成后,将数据返回给前端。

  3. 前端获取到二维码后,将其展示在页面上。

  4. 用户使用qq或微信扫描二维码,授权登陆并获取登陆凭证code。

  5. 将code发送到后端接口,后台使用code获取access_token和openid。

  6. 使用openid判断用户是否已经在系统中注册,如果没有,则根据获取的用户信息创建新用户,并生成本地用户凭证token。

  7. 将token存储在系统中,通过cookie或localStorage等方式返回给前端。

  8. 前端在后续请求中发送token,后台验证token是否有效,并通过token获取用户信息。

以下是基于springboot和vue的示例:

后台实现:

  1. 在pom.xml文件中添加spring-boot-starter-web和spring-boot-starter-thymeleaf依赖:
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
   </dependency>
</dependencies>
  1. 创建控制器QQController和WechatController,分别用于处理qq和微信登陆请求:
@RestController
@RequestMapping("/qq")
public class QQController {

    @Autowired
    private QQAuthService qqAuthService;

    @RequestMapping("/login")
    public String qqLogin() {
        String state = UUID.randomUUID().toString().replaceAll("-", "");
        String url = qqAuthService.getAuthorizationUrl(state);
        return url;
    }

}

@RestController
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private WechatAuthService wechatAuthService;

    @RequestMapping("/login")
    public String wechatLogin() {
        String state = UUID.randomUUID().toString().replaceAll("-", "");
        String url = wechatAuthService.getAuthorizationUrl(state);
        return url;
    }

}
  1. 创建QQAuthService和WechatAuthService,用于获取授权链接和access_token:
@Service
public class QQAuthService {
    private static final String QQ_AUTHORIZATION_URL = 
"https://graph.qq.com/oauth2.0/authorize?response_type=code
&client_id=%s&redirect_uri=%s&state=%s";
    private static final String QQ_ACCESS_TOKEN_URL = 
"https://graph.qq.com/oauth2.0/token?grant_type=authorization_code
&client_id=%s&client_secret=%s&code=%s&redirect_uri=%s";
    private static final String QQ_OPENID_URL = 
"https://graph.qq.com/oauth2.0/me?access_token=%s";

    private String appId = "your_appid";
    private String appSecret = "your_appsecret";
    private String redirectUri = "your_redirect_uri";

    public String getAuthorizationUrl(String state) {
        String url = String.format(QQ_AUTHORIZATION_URL, appId, redirectUri, state);
        return url;
    }

    public String getAccessToken(String code) {
        String url = String.format(QQ_ACCESS_TOKEN_URL, appId, 
        appSecret, code, redirectUri);
        String response = HttpUtil.get(url);
        String accessToken = StringUtil.getParamFromUrl(response, "access_token");
        return accessToken;
    }

    public String getOpenId(String accessToken) {
        String url = String.format(QQ_OPENID_URL, accessToken);
        String response = HttpUtil.get(url);
        String openid = StringUtil.getParamFromUrl(response, "openid");
        return openid;
    }

}

@Service
public class WechatAuthService {
    private static final String WECHAT_AUTHORIZATION_URL =
    "https://open.weixin.qq.com/connect/qrconnect?
    appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_login&state=%s#
    wechat_redirect";
    private static final String WECHAT_ACCESS_TOKEN_URL =
    "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&
    secret=%s&code=%s&grant_type=authorization_code";
    private static final String WECHAT_USERINFO_URL =
    "https://api.weixin.qq.com/sns/userinfo?access_token=%s&
    openid=%s";

    private String appId = "your_appid";
    private String appSecret = "your_appsecret";
    private String redirectUri = "your_redirect_uri";

    public String getAuthorizationUrl(String state) {
        String url = String.format(WECHAT_AUTHORIZATION_URL, appId, 
        redirectUri, state);
        return url;
    }

    public String getAccessToken(String code) {
        String url = String.format(WECHAT_ACCESS_TOKEN_URL, appId, appSecret, code);
        String response = HttpUtil.get(url);
        String accessToken = StringUtil.getParamFromUrl(response, "access_token");
        return accessToken;
    }

    public JSONObject getUserInfo(String accessToken, String openid) {
        String url = String.format(WECHAT_USERINFO_URL, accessToken, openid);
        String response = HttpUtil.get(url);
        JSONObject jsonObject = JSON.parseObject(response);
        return jsonObject;
    }
}
  1. 创建拦截器TokenInterceptor,用于拦截请求并验证token:
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, 
    HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StringUtil.isNullOrEmpty(token)) {
            throw new Exception("token不能为空");
        }

        UserDTO userDTO = userService.getUserByToken(token);
        if (userDTO == null) {
            throw new Exception("token无效");
        }

        request.setAttribute("user", userDTO);
        return true;
    }
}
  1. 在WebMvcConfigurer中添加TokenInterceptor拦截器:
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private TokenInterceptor tokenInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor);
    }
}
  1. 创建UserService,用于根据token获取用户信息:
@Service
public class UserService {

    public UserDTO getUserByToken(String token) {
        // 根据token获取用户信息
        return new UserDTO();
    }
}

前端实现:

  1. 在index.html页面中添加登陆按钮并绑定点击事件:
<button class="btn btn-primary" @click="qqLogin">QQ登陆</button>
<button class="btn btn-primary" @click="wechatLogin">微信登陆</button>
  1. 创建vue组件Login.vue,用于处理登陆流程:
<template>
    <div class="container">
        <div class="row">
            <div class="col-md-6">
                <h3>QQ登陆</h3>
                <img :src="qqQrcode" alt="">
            </div>
            <div class="col-md-6">
                <h3>微信登陆</h3>
                <img :src="wechatQrcode" alt="">
            </div>
        </div>
    </div>
</template>

<script>
    import axios from "axios";

    export default {
        name: "Login",
        data() {
            return {
                qqQrcode: "",
                wechatQrcode: "",
                intervalId: 0,
            };
        },
        created() {
            this.getQQQrCode();
            this.getWechatQrCode();
        },
        methods: {
            getQQQrCode() {
                axios.get("/qq/login").then((response) => {
                    this.qqQrcode = response.data;
                });
            },
            getWechatQrCode() {
                axios.get("/wechat/login").then((response) => {
                    this.wechatQrcode = response.data;
                });
            },
        },
    };
</script>

<style scoped>
    img {
        width: 200px;
        height: 200px;
    }
</style>
  1. 在路由配置文件中添加Login组件对应的路由:
import Login from "../views/Login.vue";

const routes = [
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  // other routes
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});
  1. 创建main.js文件,并在其中引入相关依赖:
import Vue from "vue";
import App from "./App.vue";
import VueRouter from "vue-router";
import axios from "axios";

Vue.config.productionTip = false;

Vue.use(VueRouter);

Vue.prototype.$axios = axios;

new Vue({
  router,
  render: (h) => h(App),
}).$mount("#app");

以上就是基于springboot和vue实现网页登录实现qq和微信扫码登录的示例

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要PC网站上实现微信扫码登录功能,可以按照以下步骤进行: 1. 注册微信开放平台账号:访问微信开放平台(https://open.weixin.qq.com/),使用微信账号登录并注册一个开放平台账号。 2. 创建应用并获取应用ID和密钥:在微信开放平台上创建一个应用,并获取对应的应用ID(AppID)和密钥(AppSecret)。 3. 引入微信登录SDK:下载并引入微信登录Java SDK,可以使用官方提供的SDK或第三方库,例如weixin-java-tools。 4. 配置回调URL:在微信开放平台上配置回调URL,该URL用于接收微信授权回调的code。 5. 实现扫码登录页面:在PC网站上创建一个扫码登录页面,可以使用HTML和CSS进行布局和样式设计。 6. 发起微信授权请求:在扫码登录页面中,通过调用微信登录SDK提供的接口,生成带有应用ID和回调URL的二维码图片,并显示在页面上供用户扫码。 7. 处理微信授权回调:在设置的回调URL对应的接口中,获取微信授权回调的code,并使用该code调用微信登录SDK提供的接口,获取access_token和openid等用户信息。 8. 实现登录逻辑:根据获取到的用户信息,可以选择将用户信息保存到数据库中,或者进行其他逻辑处理。 需要注意的是,微信授权登录涉及到用户隐私和安全,建议在实施过程中加强安全验证和保护用户信息。 以上是一个大致的步骤,具体实现过程可以参考微信开放平台的文档和示例代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只java小菜鸡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值