微信公众号授权获取用户OpenID和UnionId然后发生消息通知

1 篇文章 0 订阅
1 篇文章 0 订阅

1.获取微信公众号code

1.微信公众拿取公众号appid和appSecret


图片里的ip白名单是html所在的服务器ip

2.网页域名授权,这里的域名拼接上html所在位置即可访问html

在这里插入图片描述

3.设置公众号开发者

在这里插入图片描述
在这里插入图片描述

公众号与小程序不同,所以公众号授权需要通过h5页面进行授权

4.java代码获取code(这里可以获取code但是前端截取不太方便)
@RequestMapping("/getCode")
    public String getCode() {
        // 官方地址
        String urlFir = "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=";
        // 微信申请的域名(提前准备)
        String domain = "http://pay.xxx.cn";
        // 自定义跳转方法 这个路径是html放在服务器上的位置
        String redirectMethod = "/wx/index.html";
        // 地址进行encode转译 (未转译的地址是:http://pay.xxx.cn/wx/index.html)//
        //复制此地址到浏览器上可以直接访问
        // 转译后的地址是: http%3A%2F%2Fpay.xxx.cn%2Fwxpay%2Fweixinoauth
        String encoderUrl = getURLEncoderString(domain + redirectMethod);
        String url = urlFir +appId + "&redirect_uri=" +
        encoderUrl+"&response_type=code&scope=snsapi_base"
         + "&state=STATE" + "#wechat_redirect";
        log.info(url);
        return url;
    }
    /**
     * 编码
     * @param str
     * @return
     */
    public static String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
5.html中获取code
const { origin } = window.location //获取域名
//const currentUrl = encodeURIComponent(`${origin}/wx/index.html`)这个方式我没法使用
const currentUrl = decodeURIComponent(`${origin}/wx/index.html`)//对域名进行转码
//获取微信公众号code
const redirectUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=微信公众号id&&redirect_uri=${currentUrl}&response_type=code&scope=snsapi_userinfo#wechat_redirect`;
const code = this.getQueryString('code')

2.获取openID

java代码获取公众号openID
@ResponseBody
    @GetMapping("/getOpenId")
    public Map<String, String> getOpenId(@RequestParam("code") String code ) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid="+appId+"&secret="+appIdSecret+"&code="+code+"&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        String wxResult = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSON.parseObject(wxResult);
        log.info(jsonObject.toString());
        String access_token = jsonObject.getObject("access_token", String.class);
        String openid = jsonObject.getObject("openid", String.class);
        String unionid = jsonObject.getObject("unionid", String.class);
        map.put("url", url);
        map.put("access_token", access_token);
        map.put("unionid", unionid);
        map.put("openid", openid);
        log.info(url);
        return map;
    }

3.获取UnionId

1.获取unionId需要access_token
@GetMapping("/getToken")
@ResponseBody
 public String getAccessToken() throws Exception{
     String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appId +"&secret=" + appIdSecret;
     String res = HttpUtil.get(url);
     JSONObject jsonObject = JSONObject.parseObject(res);
     String accessToken = jsonObject.getString("access_token");
     return accessToken;
 }
2.获取unionId
@ResponseBody
@GetMapping("/getUnionid")
public Map<String, String> getUnionid(@RequestParam("token") String token) throws Exception {
    //获取unionid
    String unionIdUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token
            + "&openid="+openid+"&lang=zh_CN";
    RestTemplate unionIdTemplate = new RestTemplate();
    String unionIdResult = unionIdTemplate.getForObject(unionIdUrl, String.class);
    JSONObject unionIdJson = JSON.parseObject(unionIdResult);
    log.info(unionIdJson.toString());
    String unionid = unionIdJson.getObject("unionid", String.class);
    map.put("unionid", unionid);
    log.info(unionIdUrl );
    return map;
}

4.发送消息通知

1.建立消息模板

在这里插入图片描述

2.java实现发送消息通知

java代码实现公众号发送消息通知

@GetMapping("/sendMessage")
@ResponseBody
public  String sendMessage(@RequestParam("openId") String openId, @RequestParam("accessToken")String accessToken) {
    // 模板参数
    Map<String, WeChatTemplateMsg> sendMag = new HashMap<String, WeChatTemplateMsg>();
    // openId代表一个唯一微信用户,即微信消息的接收人
    String openId1 = "XXX";
    // 公众号的模板id(也有相应的接口可以查询到)
    String templateId = "XXXXX";
    // 微信的基础accessToken
    String accessToken1 = "XXXX";
    String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
    /**
     *  其他模板可以从模板库中自己添加
     */
    sendMag.put("first", new WeChatTemplateMsg("您有一天新的设备通知"));
    sendMag.put("keyword1", new WeChatTemplateMsg("生产进度异常请及时查看!"));
    sendMag.put("keyword2", new WeChatTemplateMsg("2023-01-05"));
//        sendMag.put("keyword3", new WeChatTemplateMsg("333"));
//        sendMag.put("keyword4", new WeChatTemplateMsg("444"));
    sendMag.put("remark", new WeChatTemplateMsg("请及时查看。"));
    RestTemplate restTemplate = new RestTemplate();
    //拼接base参数
    Map<String, Object> sendBody = new HashMap<>();
    sendBody.put("touser", openId);               // openId
    sendBody.put("url", "www.baidu.com");         // 点击模板信息跳转地址
    sendBody.put("topcolor", "#FF0000");          // 顶色
    sendBody.put("data", sendMag);                   // 模板参数
    sendBody.put("template_id", templateId);      // 模板Id
    ResponseEntity<String> forEntity = restTemplate.postForEntity(url, sendBody, String.class);
    log.info("结果是: {}",forEntity.getBody());
    JSONObject jsonObject = JSONObject.parseObject(forEntity.getBody());
    String messageCode = jsonObject.getString("errcode");
    String msgId = jsonObject.getString("msgid");
    System.out.println("messageCode : " + messageCode + ", msgId: " +msgId);
    return forEntity.getBody();
}

下面附上详细代码,有需要的的可以下载一波
微信公众发送消息通知,java代码
https://download.csdn.net/download/qq_39095085/87448456
公众号消息通知授权html
https://download.csdn.net/download/qq_39095085/87448461

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值