关于解密openid参考我的另一篇博客:
testSubmit:function(e){console.log(e);varself=this;letmethod='GET';letopenid='obk-W5Fq76sHfAnnC_8L_6xEew0M';let_access_token='14_Z_mmRqZ8F0LSoYphxhXLcY1qYQbiArASnTyRChBQtKnWDL3co46eXwQsL8Qr58yZ01XmE6shkLGNGkz1zhX0zqPNNsXJlGljdLejCR_qerPP76H-4ZodZT4XTPqEAywHtNB_m-djIzoN3AyHZZJjAFASSC';leturl='https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='+_access_token;let_jsonData={access_token:_access_token,touser:'oK_7b4mGyt6L9DRXWINxjEeCb_no',template_id:'PZ-QULr4atCAgBacoMjh09u0bAVA_St-lNCp5jV7Pcs',form_id:e.detail.formId,page:"pages/index/index",data:{"keyword1":{"value":"测试数据一","color":"#173177"},"keyword2":{"value":"测试数据二","color":"#173177"},"keyword3":{"value":"测试数据三","color":"#173177"},"keyword4":{"value":"测试数据四","color":"#173177"},"keyword5":{"value":"测试数据五","color":"#173177"},"keyword6":{"value":"测试数据六","color":"#173177"}}};wx.request({url:"https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+_access_token,data:_jsonData,method:method,success:function(res){console.log(res)wx.showToast({title:'发送成功',})},fail:function(err){console.log('requestfail',err);},complete:function(res){console.log("requestcompleted!");}})}java代码后台发送模板消息:后端发送模板消息需要获取前端表单提交的formid
controller:@GetMapping("/publishModelMessage")publicStringpublishModelMessage(@RequestParam(required=false)StringformId,@RequestParam(required=false)StringopenId,HttpServletResponseresponse){openId="oK_7b4mGyt6L9DRXWINxjEeCb_no";Tokentoken=CommonUtil.getToken("你的小程序appid","你的小程序密钥");System.out.println(token.getAccessToken());WxMssVowxMssVo=newWxMssVo();wxMssVo.setTemplate_id("PZ-QULr4atCAgBacoMjh09u0bAVA_St-lNCp5jV7Pcs");wxMssVo.setTouser(openId);wxMssVo.setPage("pages/index/index");wxMssVo.setRequest_url("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+token.getAccessToken());wxMssVo.setForm_id(formId);ListTemplateDatalist=newArrayList();list.add(newTemplateData("通知","#ffffff"));list.add(newTemplateData("李银龙","#ffffff"));list.add(newTemplateData("发布成功","#ffffff"));list.add(newTemplateData(newDate().toString(),"#ffffff"));list.add(newTemplateData("日常加班","#ffffff"));list.add(newTemplateData("深圳市方寸科技服务有限公司","#ffffff"));wxMssVo.setParams(list);CommonUtil.sendTemplateMessage(wxMssVo);returnnull;}工具类CommonUtil:publicclassCommonUtil{publicfinalstaticStringtoken_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";//获取小程序tokenpublicstaticTokengetToken(Stringappid,Stringappsecret){Tokentoken=null;StringrequestUrl=token_url.replace("APPID",appid).replace("APPSECRET",appsecret);//发起GET请求获取凭证JSONObjectjsonObject=httpsRequest(requestUrl,"GET",null);if(null!=jsonObject){try{token=newToken();token.setAccessToken(jsonObject.getString("access_token"));token.setExpiresIn(jsonObject.getInteger("expires_in"));}catch(JSONExceptione){token=null;//获取token失败e.printStackTrace();}}returntoken;}//发送模板消息publicstaticStringsendTemplateMessage(WxMssVowxMssVo){Stringinfo="";try{//创建连接URLurl=newURL(wxMssVo.getRequest_url());HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();connection.setDoOutput(true);connection.setDoInput(true);connection.setRequestMethod("POST");connection.setUseCaches(false);connection.setInstanceFollowRedirects(true);connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");connection.setRequestProperty("Content-Type","utf-8");connection.connect();//POST请求DataOutputStreamout=newDataOutputStream(connection.getOutputStream());JSONObjectobj=newJSONObject();obj.put("access_token",wxMssVo.getAccess_token());obj.put("touser",wxMssVo.getTouser());obj.put("template_id",wxMssVo.getTemplate_id());obj.put("form_id",wxMssVo.getForm_id());obj.put("page",wxMssVo.getPage());JSONObjectjsonObject=newJSONObject();for(inti=0;iwxMssVo.getParams().size();i++){JSONObjectdataInfo=newJSONObject();dataInfo.put("value",wxMssVo.getParams().get(i).getValue());dataInfo.put("color",wxMssVo.getParams().get(i).getColor());jsonObject.put("keyword"+(i+1),dataInfo);}obj.put("data",jsonObject);out.write(obj.toString().getBytes());out.flush();out.close();//读取响应BufferedReaderreader=newBufferedReader(newInputStreamReader(connection.getInputStream()));Stringlines;StringBuffersb=newStringBuffer("");while((lines=reader.readLine())!=null){lines=newString(lines.getBytes(),"utf-8");sb.append(lines);}info=sb.toString();System.out.println(sb);reader.close();//断开连接connection.disconnect();}catch(Exceptione){e.printStackTrace();}returninfo;}publicstaticJSONObjecthttpsRequest(StringrequestUrl,StringrequestMethod,StringoutputStr){JSONObjectjsonObject=null;try{//创建SSLContext对象,并使用我们指定的信任管理器初始化TrustManager[]tm={newMyX509TrustManager()};SSLContextsslContext=SSLContext.getInstance("SSL","SunJSSE");sslContext.init(null,tm,newjava.security.SecureRandom());//从上述SSLContext对象中得到SSLSocketFactory对象SSLSocketFactoryssf=sslContext.getSocketFactory();URLurl=newURL(requestUrl);HttpsURLConnectionconn=(HttpsURLConnection)url.openConnection();conn.setSSLSocketFactory(ssf);conn.setDoOutput(true);conn.setDoInput(true);conn.setUseCaches(false);//设置请求方式(GET/POST)conn.setRequestMethod(requestMethod);//当outputStr不为null时,向输出流写数据if(null!=outputStr){OutputStreamoutputStream=conn.getOutputStream();//注意编码格式outputStream.write(outputStr.getBytes("UTF-8"));outputStream.close();}//从输入流读取返回内容InputStreaminputStream=conn.getInputStream();InputStreamReaderinputStreamReader=newInputStreamReader(inputStream,"utf-8");BufferedReaderbufferedReader=newBufferedReader(inputStreamReader);Stringstr=null;StringBufferbuffer=newStringBuffer();while((str=bufferedReader.readLine())!=null){buffer.append(str);}//释放资源bufferedReader.close();inputStreamReader.close();inputStream.close();inputStream=null;conn.disconnect();jsonObject=JSONObject.parseObject(buffer.toString());}catch(ConnectExceptionce){ce.printStackTrace();}catch(Exceptione){e.printStackTrace();}returnjsonObject;}}Token类:publicclassToken{//接口访问凭证privateStringaccessToken;//接口有效期,单位:秒privateintexpiresIn;publicStringgetAccessToken(){returnaccessToken;}publicvoidsetAccessToken(StringaccessToken){this.accessToken=accessToken;}publicintgetExpiresIn(){returnexpiresIn;}publicvoidsetExpiresIn(intexpiresIn){this.expiresIn=expiresIn;}}模板消息请求参数封装类WxMssVo:publicclassWxMssVo{privateStringtouser;privateStringtemplate_id;privateStringpage;privateStringform_id;privateStringaccess_token;privateStringrequest_url;privateListTemplateDataparams=newArrayList();}模板消息详细参数封装TemplateData:publicclassTemplateData{privateStringkey;privateStringvalue;privateStringcolor;publicTemplateData(Stringvalue,Stringcolor){this.value=value;this.color=color;}}最终效果:
关注公众号回复091可获取项目源码














