最近项目中需要用到微信小程序转发动态消息的功能,遇到了一些坑,最终测试成功了,现在分享给大家。
微信官方的动态消息参考文档在这里:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share/updatable-message.html
一,实现效果
转发小程序之后可以看到:"成员正在加入,当前 {member_count}/{room_limit} 人"动态效果。

二,测试环境
1)微信基础库为2.6.6,在微信开发工具中详情栏目可以设置

2)转发动态消息的效果必须使用真机才能看到,模拟器看不到提示信息。
三,参数准备
wx.updateShareMenu({withShareTicket: true,isUpdatableMessage: true,activityId: '你的activityid', // 活动 IDtargetState: 0,templateInfo: {parameterList: [{name: 'member_count',value: '3'}, {name: 'room_limit',value: '5'}]}}); 
当targetState设置为0时,必须填member_counth和room_limit的值。
activityId的值需要通过调用后台接口得到,activityid的默认有效时间是24小时。现在给出我的实现代码
    /*** 获取Access_token* @return* @throws Exception* @throws IOException*/public String getAccess_token()throws Exception,IOException {HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appid + "&secret="+ appsecret);HttpClient httpClient = HttpClients.createDefault();HttpResponse res = httpClient.execute(httpGet);HttpEntity entity = res.getEntity();String result = EntityUtils.toString(entity, "UTF-8");JSONObject jsons = JSONObject.parseObject(result);///fromObject(result);String expires_in = jsons.getString("expires_in");//缓存String access_token = null;if (Integer.parseInt(expires_in) == 7200) {//okaccess_token = jsons.getString("access_token");} else {System.out.println("出错获取token失败!");logger.info("出错获取token失败!");}System.out.println("access_token:"+access_token);return access_token;}/*** 获取Activity_id* @return* @throws Exception* @throws IOException*/@RequestMapping("getActivity_id")//返回json格式,@ResponseBodypublic String getActivity_id()throws Exception,IOException{String access_token = this.getAccess_token();HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/message/wxopen/activityid/create?access_token="+ access_token );HttpClient httpClient = HttpClients.createDefault();HttpResponse res = httpClient.execute(httpGet);HttpEntity entity = res.getEntity();String result = EntityUtils.toString(entity, "UTF-8");JSONObject jsons = JSONObject.parseObject(result);///fromObject(result);String errcode = jsons.getString("errcode");//缓存String activity_id = null;if (Integer.parseInt(errcode) == 0) {//okactivity_id = jsons.getString("activity_id");} else{System.out.println("出错获取activity_id失败!errcode:"+errcode);logger.info("出错获取activity_id失败!errcode:"+errcode);}System.out.println("activity_id:"+activity_id);return activity_id;} 
现在就可以上传一个体验版测试一下了,在手机上转发给微信好友应该可以看到前面的效果。
如果这是在服务器调用下面的代码,activityid和access_token要换成刚才小程序里面使用的
curl -d '{"activity_id": "966_NGiqxxxxxxxxx...xxxxxxxxE33BlwX", "target_state": 0, "template_info": {"parameter_list": [{"name": "member_count", "value": "2"}, {"name":"room_limit", "value": "6"} ] } }' \
'https://api.weixin.qq.com/cgi-bin/message/wxopen/updatablemsg/send?access_token=ACCESS_TOKEN' 
这是就会发现,手机里面刚刚转发的提示信息内容改变了。












