【微信公众号网页项目】Vue+Spring Boot,微信公众号网页项目,授权微信并获取用户个人信息

微信网页项目,授权微信并获取用户个人信息

准备工作

一、注册公众号

https://mp.weixin.qq.com/ 这里我们使用的个人用户,使用公众平台测试账号进行开发。(注:实际企业开发项目中,需要认证企业并使用实际公众号开发)

二、设置相关内容

1、进入公众平台测试账号页面,如图所示

在这里插入图片描述2、牢记appID以及appsecret数据,是发起请求接口的重要参数

在这里插入图片描述3、JS接口安全域名修改,这里是本地测试,所以直接填本地前端的地址,比如192.168.3.28:8080(查看本机ip地址:win+R 输入cmd 回车 打开控制台窗口,输入ipconfig查看本机ip地址)

4、页面下拉查看网页授权获取用户基本信息,点击修改,本地测试的话,和上面JS接口安全域名填写一致就可以
在这里插入图片描述在这里插入图片描述

开始开发

一、查看开发文档

确定基本步骤:

 - 引导用户进入授权页面同意授权,获取code
 - 通过code换取网页授权access_token(与基础支持中的access_token不同)
 - 如果需要,开发者可以刷新网页授权access_token,避免过期
 - 通过网页授权access_token和openid获取用户基本信息(支持UnionID机制)

1、用户打开微信链接,微信客户端会自动跳转到回掉地址并且地址栏会携带code参数
2、开发者需要获取code并使用code请求接口,获取access_token信息,access_token参数尽量存在服务器中,该参数存在有效时长,超时需要重新授权
3、通过access_token获取用户基本信息

二、代码实现

1、后端
UserController.java


	private String appid = "*******************";
	private String secret = "*******************";

	@GetMapping("/get_access_token") //获取access_token
    public Map<String, Object> get_access_token(@RequestParam String code) throws IOException, SignatureException, NoSuchAlgorithmException, InvalidKeyException {
        Map<String, Object> map = new HashMap<>();

        HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code");

        httpGet.setHeader("Accept", "application/json;charset=utf-8");

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = httpClient.execute(httpGet);
        // 获取响应状态码
        int statusCode = response.getStatusLine().getStatusCode();
        // 获取响应内容
        String responseBody = EntityUtils.toString(response.getEntity());
        
        // 关闭响应对象
        response.close();
        map.put("code", statusCode);
        map.put("response", new String(responseBody.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));

        return map;
    }

	@GetMapping("/get_user_info") //获取userinfo
    public Map<String, Object> get_user_info(@RequestParam String access_token,@RequestParam String openid) throws IOException, SignatureException, NoSuchAlgorithmException, InvalidKeyException {
        Map<String, Object> map = new HashMap<>();

        HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + oppenid + "&lang=zh_CN");

        httpGet.setHeader("Accept", "application/json;charset=utf-8");

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = httpClient.execute(httpGet);
        // 获取响应状态码
        int statusCode = response.getStatusLine().getStatusCode();
        // 获取响应内容
        String responseBody = EntityUtils.toString(response.getEntity());
        // 关闭响应对象
        response.close();
        map.put("code", statusCode);
        map.put("response", new String(responseBody.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
        return map;
    }
    

前端:
index.vue

...
import { get_access_token,get_user_info } from "@/api/http.js"

export default {
	mouted(){
		this.get_userinfo()
	},
	method:{
		async get_userinfo(){
			const code = this.$route.query.code
			await obj = get_access_token(code)
			const response = JSON.parse(obj.response)
			console.log(response) // 控制台查看数据
			await res = get_user_info(response.access_token,response.openid)
			console.log(JSON.parse(res.response)) // 控制台查看数据
		}
	}
}

http.js

//将拦截器整体导入
import request from "./Interceptor.js"; //导入已经写好的拦截器,拦截器代码可私聊我获取
// 封装所有的API接口

export function get_access_token(code) {
  return request({
    url: "/get_access_token",
    method: "get",
    params: {
      code: code
    }
  });
}

export function get_user_info(access_token,openid) {
  return request({
    url: "/get_user_info",
    method: "get",
    params: {
      access_token: access_token,
      openid:openid
    }
  });
}

三、测试结果

使用微信或者PC微信开发者工具打开网页:https://open.weixin.qq.com/connect/oauth2/authorize?appid=*********&redirect_uri=http://192.168.3.28:8080/demo&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
微信开发文档给出的测试图片

在这里插入图片描述

注意事项⚠️

1、网页链接格式:https://open.weixin.qq.com/connect/oauth2/authorize?appid=&redirect_uri=&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect,redirect_url必须和授权回调页面域名一致

2、该链接只能在微信客户端打开,PC端可以使用微信开发者工具调试

3、博主只实现了正向没有错误的授权方式,如果正式项目中,需要将access_token存入redis或者缓存中并判断过期时间,如果过期需使用refresh_token接口刷新;并且接口中会存在错误情况,微信开发文档中给出了相关错误码所对应的错误情况,请根据实际情况修改

4、本文章仅仅展示了微信开发以及初级后端开发的冰山一角,也请各位大佬提出宝贵意见

  • 45
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值