java向微信公众号---后台获取授权用户的openId

其他操作

书接上文:测试号申请步骤和调试.
书接上文:微信发送模板和图文消息.

项目搭建前两篇都有写这里不过多赘述

controller

/**
     * 获取code换取openId
     * @param vxReq
     * @return
     */
    @PostMapping("/authorize")
    public String authorize(@RequestBody VxReq vxReq) {
        //构建参数
        String uri = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +
                appSecret.getAppId() +
                "&secret=" +
                appSecret.getSecret() +
                "&code=" +
                vxReq.getCode() +
                "&grant_type=" +
                "authorization_code";
        ResponseEntity<String> res = null;
        try {
            //调用微信方法获取openId
            res = restTemplate.getForEntity(uri, String.class);
        }catch (Exception e){
            return null;
        }
        if(res == null){
            return null;
        }
        String body = res.getBody();
        System.out.println(body);
        Map<String,String> map = JSONObject.parseObject(body, Map.class);
        System.out.println(map.get("openid"));
        return map.get("openid");
    }

这是使用 restTemplate 发送get请求

restTemplate配置

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
    }

**SpringBoot 可以扫描到的包下注入 RestTemplate **

restTemplate maven

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
        </dependency>

这需要前端在js中调用微信获取用户授权接口得到code然后在 调用这个接口

配置前端调用js

在这里插入图片描述

nginx

service{
	listen 80;
	service_name *******域名******;
	location /{
		root /user/local/nginx/html;
		index index.html index.htm;
	}
}

文件放在 /user/local/nginx/html/文件.txt

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值