Micro-channel service notification applet development

Micro-channel notification service similar to SMS, but the development is relatively simple, the following must get to know several parameters before it is sent off, for several parameters related to the development of your success.
1: Parameter
here to say that the meaning of the parameters, how to obtain a detailed explanation below.
openid: Each micro-channel unique id, service notification Its role is to inform who you want, who openid give you sent in the past, which is similar to your phone number, you send text messages, you must know your phone number.
access_token: Because how micro-channel service announcements, we do not know the bottom, micro-channel to the port, want to use this interface must have access_token parameter. Because the micro-channel is still relatively strict confidentiality do, so you need to get a variety of parameters.
form_id: I understand this is not a place, it seems to me that triggered this micro-channel service notification function parameters; the first idea is that you know it has to get on it.
template_id: template id, this is the micro-channel public platform inside, you choose what format notification template, then the corresponding template_id pasted.
appid, secret: the micro-channel public platform inside, we should all be familiar with this, I will not say more.
Next, I explain your message template:
enter the micro-channel public platform:
(1) Click on the arrow pointing to the picture message template:
Here Insert Picture Description
(2) there are a lot of message templates, select the one for you.
Here Insert Picture Description
(3) Remember your template_id, in the next development you to use
Here Insert Picture Description
2: Next, to explain the process to obtain the above parameters
(1) to obtain access_token
micro letter applet code

 //获取access_token
    wx.request({
      url: 'https://www.lined5530.top/lg/wxsendmesController/at',
      success:function(res){
        var at=wx.setStorageSync("at", res.data.mes)
        console.log(res.data.mes)
      }
    })

Java code behind

String accessToken;//因为用到的地方很多,所以我写成全局变量了
	//获取accessToken
	@RequestMapping("at")
	@ResponseBody
	public JSONObject at() {
        // 微信小程序ID
        String appid = "你自己的appid";
        // 微信小程序秘钥
        String secret = "你自己的秘钥";

        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
        // 发送请求,返回Json字符串
        String str = WeChatUtil.httpRequest(url, "GET", null);
        // 转成Json对象 获取openid
        Map<String,String> map=new HashMap<String,String>();
        //转化成json
        JSONObject fromObject = JSONObject.fromObject(str);
        //获取at
        accessToken = fromObject.getString("access_token");
        System.out.println("后台获取的"+accessToken);
        //给小程序端返回at
        map.put("mes", accessToken);
    	JSONObject json=JSONObject.fromObject(map);
		return json;
        //JSONObject jsonObject = JSONObject.parseObject(str);
        //System.out.println("access_token---"+jsonObject.toJSONString());
        // 我们需要的openid,在一个小程序中,openid是唯一的
//        String access_token = jsonObject.get("access_token").toString();
//        return access_token;	
	}

Not surprisingly, the first parameter you successfully acquired
(2) to obtain openid
at the time of acquisition openid, you must first get code. Login you can get through this interface is relatively simple, you look at the code should be able to understand.

  //获取openid
    wx.login({
      success: function (res) {
        var code1 = res.code//获取openid需要code
        var appid1 = "自己的aappid"
        var secret1 = "自己的秘钥"
        var ul = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid1 + '&secret=' + secret1 + '&js_code=' + code1 + '&grant_type=authorization_code'
        //获取openid
        wx.request({
          url: ul,
          method: 'GET',
          success: function (e) {
            var openid = e.data.openid
            console.log('获取登录身份的唯一openid', openid)
            wx.setStorageSync('openid', openid)
          }
        })
      }
    })

Many people may see others get openid in the background, in fact, not necessary, can be obtained directly in the js, not surprisingly, the second most important parameter you get successful.
(3) obtaining form_id
This contact can be done in the applet
wxml micro-letter code for the applet

 <form bind:submit="sendMessage" report-submit="true">
      <button formType="submit">发送模板消息</button>
 </form>```

Get fromid going to start micro-code is sent to the notification letter sent
js code

 sendMessage: function (e) {
    var today = new Date();
    var year = today.getFullYear();
    var m1 = today.getMonth();
    var month = m1 + 1
    var day = today.getDate();
    var h = today.getHours();
    var m = today.getMinutes();
    var etime = year + "-" + month + "-" + day 
    var time=h+":"+m
    console.log("formId");
    console.log(e);
    //对应通知服务的格式,你在选取模板的时候,用到几个参数,就设置几个参数
    let _jsonData =
    {
      "touser": "对应给谁发送就写谁的openid",
      "weapp_template_msg": {
        "template_id": "公众平台里边模板id",
        //服务通知中进入小程序的入口
        "page": "pages/index/index",
        "form_id": e.detail.formId,
        "data": {
          "keyword1": {
            "value": wx.getStorageSync("name")
          },
          "keyword2": {
            "value": etime
          },
          "keyword3": {
            "value": time
          },
          "keyword4": {
            "value": "内蒙古师范大学大数据楼316"
          }
        },
        "emphasis_keyword": "keyword1.DATA"
      }
    }
    // wx.showModal({
    //   title: 'formdID',
    //   content: e.detail.formId,
    // })
    //向后台请求,把刚才设置好的参数发送到后台
    wx.request({
      url: 'https://www.lined5530.top/lg/wxsendmesController/sendMsg',
      data:_jsonData,//直接发送的json数据格式
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log("res")
        console.log(res)
      }
    })
    console.log("faxiaox")
  },

The code corresponding to the background

//发送消息
	@RequestMapping("addsenddata")
    @ResponseBody
      public void sendMessage(@RequestBody String _jsonData){
        System.out.println("sendMesg传入参数"+_jsonData);
        // 微信小程序ID
        String appid = "自己appid";
        // 微信小程序秘钥
        String secret = "自己的秘钥";

        String ACCESS_TOKEN=accessToken;
        // 根据小程序穿过来的code想这个url发送请求
        String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token="+ACCESS_TOKEN;
        // 发送请求,返回Json字符串
        String str = WeChatUtil.httpRequest(url, "POST", _jsonData);
        // 转成Json对象 获取openid
        JSONObject fromObject = JSONObject.fromObject(str);
        
        //JSONObject jsonObject = JSONObject.parseObject(str);
        System.out.println("jsonObject____"+fromObject.toString());
        // 我们需要的openid,在一个小程序中,openid是唯一的
    }

Finally, you might use this method WeChatUtil

public class WeChatUtil {
    public static String httpRequest(String requestUrl,String requestMethod,String output){
        try{
            URL url = new URL(requestUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            if(null != output){
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(output.getBytes("utf-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null){
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            connection.disconnect();
            return buffer.toString();
        }catch(Exception e){
            e.printStackTrace();
        }
        return "";
    }
}

The final effect is as follows
Here Insert Picture Description
over the whole course of my learning, study a good job in the afternoon, hope to help you.
Undertake graduation: micro-channel applets, ssm Raspberry Pi hardware and
have developed a good graduation can buy cheaper prices.
Scanning micro-channel two-dimensional code plus the following (You Are):
Here Insert Picture Description

Published 33 original articles · won praise 14 · views 10000 +

Guess you like

Origin blog.csdn.net/baidu_38978508/article/details/102690123