微信公众号推送小程序模板消息的实现

微信公众号推送小程序模板消息的实现

准备:
微信小程序认证
微信公众号认证
微信开发平台认证(绑定微信小程序和公众号(unionid))
unionid:同一用户,对同一个微信开放平台下的不同应用,unionid是相同的
思路:
1. 获取小程序信息(用户openid小程序用户唯一ID)
将小程序与公众号绑定(绑定后才可获取unionid)

    /**
     * 小程序用户登录授权
     */
    @GetMapping("/getUserOpenId")
    public AjaxResult getUserOpenId(String code){
        if (StringUtils.isEmpty(code)){
            return AjaxResult.error("请输入code");
        }
        Map<String, Object> result = new LinkedHashMap();
        String oAuth = WxAppletUserInfo.getOAuth(code, userAppId, userSecret);
        JSONObject jsonObject = JSONObject.fromObject(oAuth);
        //获取openId和sessionKey
        String openid = jsonObject.get("openid").toString();
        String session_key = jsonObject.get("session_key").toString();
        String unionid= jsonObject.get("unionid").toString();
		......
    }
获取小程序信息:WxAppletUserInfo 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.LoggerFactory;
/**
 * @description: 获取小程序信息
 **/
public class WxAppletUserInfo {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(WxAppUserInfo.class);

    //获取小程序登录信息
    private final static String GET_CODE_SESSION_URL="https://api.weixin.qq.com/sns/jscode2session";

    // 算法名
    public static final String KEY_NAME = "AES";
    // 加解密算法/模式/填充方式
    // ECB模式只用密钥即可对数据进行加密解密,CBC模式需要添加一个iv
    public static final String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";

    /**
     * @Title: getOAuth
     * @Description: 获取小程序用户登陆信息
     * @param @param code
     * @throws
     */
    public static String getOAuth(String code,String appId,String secret) {
        StringBuffer url = new StringBuffer(GET_CODE_SESSION_URL);
        url.append("?appid="+appId).append("&secret="+secret)
                .append("&js_code="+code)
                .append("&grant_type=authorization_code");
        return HttpUtils.get(url.toString());
    }
}

2.获取公众号的openid(公众号用户唯一ID)

  @GetMapping("/getCode")
    public AjaxResult getCode(String code){
        if (null == code || code.trim().equals("")){
            return AjaxResult.error("code为空");
        }
        //根据code获取token
        String accessTokenCode = WxAppUserInfo.getAccessTokenCode(code, wxAppId, wxAppSecret, wxAuthLoginUrl);
        //获取openid
        JSONObject jsonObject = JSONObject.fromObject(accessTokenCode);
        //获取openid和session_key
        String openid = jsonObject.get("openid").toString();
        String accessToken = jsonObject.get("access_token").toString();
        //获取用户信息
        String wxUserInfo = WxAppUserInfo.getWxUserInfo(accessToken, openid);
        String userInfo = HttpUtils.get(wxUserInfo);
        JSONObject fromObject = JSONObject.fromObject(userInfo);
        String openId = fromObject.getString("openid");
        String nickName = fromObject.getString("nickname");
        String sex = fromObject.getString("sex");
        String province = fromObject.getString("province");
        String city = fromObject.getString("city");
        String country = fromObject.getString("country");
        String headImgUrl = fromObject.getString("headimgurl");
        String privilege = fromObject.getString("privilege");
        String unionId = fromObject.getString("unionid");
        .....
       }

获取公众号信息

import net.sf.json.JSONObject;
import org.slf4j.LoggerFactory;

/**
 * @description: 获取微信公众号信息
 **/
public class WxAppUserInfo {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(WxAppUserInfo.class);

    /**
     * 获取模板消息所需要的access_token(获取微信公众号的access_token(7200秒有效))
     * @param urlToken
     * @param appId
     * @param appSecret
     * @return
     */
    public static String getAccessToken(String urlToken,String appId,String appSecret) {
        StringBuffer url = new StringBuffer(urlToken);
        url.append("?appid="+appId)
                .append("&secret="+appSecret)
                .append("&grant_type=client_credential");
        String token = HttpUtils.get(url.toString());
        log.info("获取模板消息所的认证参数access_token:{}",token);
        JSONObject Json = JSONObject.fromObject(token);
        String access_token = String.valueOf(Json.get("access_token").toString());
        return access_token;
    }

    /**
     * 根据code获取到网页授权access_token
     * @param code
     * @return  微信回调后带有的参数code值
     */
    public static String getAccessTokenCode(String code,String wxAuthLoginUrl,String appId,String appSecret) {
        StringBuffer url = new StringBuffer(wxAuthLoginUrl);
        url.append("?appid="+appId)
                .append("&secret="+appSecret)
                .append("&code="+code)
                .append("&grant_type=authorization_code");
        log.info("根据code获取到网页授权access_token:{}",url.toString());
        return HttpUtils.get(url.toString());
    }

    /**
     * 获取微信用户
     * @param accessToken
     * @param openId
     * @return
     */
    public static String getWxUserInfo(String accessToken,String openId) {
        StringBuffer url = new StringBuffer();
        url.append("?access_token="+accessToken)
                .append("&openid="+openId);
        log.info("根据access_token和openId获取微信用户信息:{}",url.toString());
        return HttpUtils.get(url.toString());
    }
}

3.推送消息服务
公众号模板申请:一个月只能有三次,审核7-15个工作日

//1.获取access_token
https请求方式: GET 
urlToken = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET'
  
String TemplateId = "";  

//2.模板消息类
//openid 是用户公众号的openid
  public static JSONObject packJsonDoctorMsg(String openid,String AppId,String pagePath){
        //医生发送公众号模板消息
        WechatTemplate wechatTemplate = new WechatTemplate();
        wechatTemplate.setTouser(openid);
        wechatTemplate.setTemplate_id(TemplateId);
        MiniprogramData miniprogramData = new MiniprogramData();
        miniprogramData.setAppid(AppId);
        miniprogramData.setPagepath(pagePath);//所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar),要求该小程序已发布,暂不支持小游戏
        wechatTemplate.setMiniprogram(miniprogramData);
        Map<String,TemplateData> dataMap = new HashMap<>();
        TemplateData title = new TemplateData();
        title.setValue("所发送消息内容");
        title.setColor("#000000");
        dataMap.put("title",title);
        TemplateData first = new TemplateData();
        first.setValue("所发送消息内容";
        first.setColor("#000000");
        dataMap.put("first",first);
        TemplateData keyword = new TemplateData();
        keyword.setValue("所发送消息内容");
        keyword.setColor("#000000");
        dataMap.put("keyword",keyword);
        TemplateData keyword = new TemplateData();
        keyword.setValue("所发送消息内容");
        keyword.setColor("#000000");
        dataMap.put("keyword", keyword);
        TemplateData keyword = new TemplateData();
        keyword.setValue("所发送消息内容");
        keyword.setColor("#000000");
        dataMap.put("keyword", keyword);
        TemplateData keyword = new TemplateData();
        keyword.setValue("所发送消息内容");
        keyword.setColor("#000000");
        dataMap.put("keyword", keyword);
        TemplateData remark = new TemplateData();
        remark.setValue("所发送消息内容");
        remark.setColor("#000000");
        dataMap.put("remark", remark);
        wechatTemplate.setData(dataMap);
        JSONObject json = JSONObject.fromObject(wechatTemplate);
        return json;
    }

//3.用户发送模板消息
JSONObject userMsgDate = MessageModel.packJsonUserMsg(openid, AppId, userPagePath);

JSONObject jsonobjUser = HttpUtils.httpRequest(send+WxAppUserInfo.getAccessToken(urlToken,appId,appSecret),"POST",userMsgDate.toString());
               

over~

上一篇:luogu P3245 [HNOI2016]大数


下一篇:Go + gRPC-Gateway(V2) 构建微服务实战系列,小程序登录鉴权服务:第二篇(内附开发 demo)