java服务端微信小程序订阅消息

小程序端消息订阅接口文档地址:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/subscribe-message/wx.requestSubscribeMessage.html

服务端消息发送接口文档地址:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html

package com.tyg.other;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.mns.common.utils.HttpUtil;
import com.yt.eos.common.utils.HttpUtils;
import com.yt.eos.common.utils.TimeUtil;

/**
 * 微信消息推送
 * @author tyg
 * @date   2019年11月25日下午5:18:40
 */
@Service
public class WechatMsgSend {
	
	private static Logger logger = LoggerFactory.getLogger(WechatMsgSend.class);
	@Resource(name = "redisTemplate")
	protected RedisTemplate<String, String> redisTemplate;
	
	/**
	 * 推送微信消息
	 * 40003	touser字段openid为空或者不正确	
	 * 40037	订阅模板id为空不正确
	 * 43101	用户拒绝接受消息,如果用户之前曾经订阅过,则表示用户取消了订阅关系	
	 * 47003	模板参数不准确,可能为空或者不满足规则,errmsg会提示具体是哪个字段出错	
	 * 41030	page路径不正确,需要保证在现网版本小程序中存在,与app.json保持一致
	 * @param dto
	 * @author tyg
	 * @date   2019年11月25日下午5:00:41
	 */
	public String sendMsgService() {
		try {

            JSONObject json = new JSONObject();
            JSONObject jsonData = new JSONObject();
            json.put("touser", "tmp1687f6781358frg");
            json.put("template_id", "oR8A442jtkQG6tTrGrKyQL31358frg");
            // 跳转地址,没有则不填,如果有:必须是小程序内页面地址,支持带参数
            json.put("page", "http://www.baidu.com/index.html");
            
            jsonData.put("date1", initJson(TimeUtil.parseStr(new Date()))); // 时间
            jsonData.put("thing2", initJson("更新内容")); // 更新内容
            jsonData.put("thing3", initJson("详细内容")); // 详细内容
            jsonData.put("thing4", initJson("点击查看详情!")); // 备注
            json.put("data",jsonData);
            
            // 请求url
            String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
            // 发起请求
            String response = HttpUtil.sendPost(url, json.toJSONString());
logger.info("\n\n================请求参数:{},\n\n================微信消息推送返回值:{}", json.toJSONString(), response);
    		
            JSONObject parse = JSONObject.parseObject(response);
            
            return response;
		} catch (Exception e) {
			logger.info("\n\n====================微信消息推送异常消息:{}", e);
			return e.getMessage();
		}
		return null;
	}
	
	/**
	 * 初始化json数据
	 * @param info
	 * @return
	 * @author tyg
	 * @date   2019年11月25日下午5:05:56
	 */
	private static JSONObject initJson(String info) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("value",info);
//		jsonObject.put("color","#173177");
		return jsonObject;
	}
	
	/**
	 * 获取微信的
	 * @return
	 * @author tyg
	 * @date   2019年12月5日下午2:38:05
	 */
	private String getAccessToken() {
		String access_token = null;
		try {
			JSONObject json = new JSONObject();
			//查询是否还有缓存
			BoundValueOperations<String, String> ops = redisTemplate.boundValueOps("account_token");
			//缓存时长
			if(StringUtils.isBlank(ops.get())) {
				Map<String, String> params = new HashMap<String, String>();
				params.put("grant_type", "client_credential");
				params.put("appid", "wx85f5d4sf5f8f78gf46");
				params.put("secret", "tr4548f87f867g4grg5");
				String respData = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
				System.out.println("getaccess_token=====\n"+respData);
				json = JSON.parseObject(respData);
				ops.set(json.getString("access_token"));
				ops.expire(7100, TimeUnit.SECONDS);
			}
			access_token = ops.get();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return access_token;
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值