Java實現 微信小程序 + 消息推送

 

 實現效果:html

 

下面要顯示五個字段json

 

接下來,參照官方文檔,一步步實現:小程序

https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/template-message/templateMessage.send.htmlapi

 

1、官方給出請求示例、返回示例微信

 

 

 

2、根據上面編寫實體類
url

 (1)請求參數spa

@Data
public class SendTemplateReq {
    /**
     * 接收者(用戶)的 openid
     */
    private String touser;
    /**
     * 所需下發的模板消息的id
     */
    private String template_id;
    /**
     * 點擊模板卡片後的跳轉頁面,僅限本小程序內的頁面。支持帶參數,(示例index?foo=bar)。
     * 該字段不填則模板無跳轉。
     */
    private String page;
    /**
     * 表單提交場景下,爲 submit 事件帶上的 formId;支付場景下,爲本次支付的 prepay_id
     */
    private String form_id;
    /**
     * 模板內容
     * 不填則下發空模板。具體格式請參考示例。
     */
    private DoctorReplyMsgData data;

    /**
     * 模板須要放大的關鍵詞
     * 不填則默認無放大
     */
    private String emphasis_keyword;
}

  

(2)請求參數中的data,如實現效果所示,這是在小程序顯示的五個字段.code

(屬性名就要叫keyword一、二、3,不然推送的消息空白)orm

@Data
public class DoctorReplyMsgData {
   
    private KeyNote keyword1;
 
    private KeyNote keyword2;
 
    private KeyNote keyword3;
 
    private KeyNote keyword4;
  
    private KeyNote keyword5;
}

 

(3)上面五個字段對應的值(data是對象,因此須要這樣)htm

@Data
public class KeyNote {
    private String value;

}

  

(4)請求後,微信返回的消息體

 

@Data
public class SendTemplateResponse { /** * 錯誤碼 * 0 ok * 40037 template_id不正確 * 41028 form_id不正確,或者過時 * 41029 form_id已被使用 * 41030 page不正確 * 45009 接口調用超過限額(目前默認每一個賬號日調用限額爲100萬) */ private int errcode; /** * 錯誤信息 */ private String errmsg; }

 

 

 

 

3、實現代碼

 

public void sendTemplate() { SendTemplateReq sendTemplateReq = new SendTemplateReq(); //一、用戶的 openid
    sendTemplateReq.setTouser("openid"); //二、模板消息的id
    sendTemplateReq.setTemplate_id("小程序啓用模板的模板id"); //三、formid
    sendTemplateReq.setForm_id("小程序傳給後臺的formid,七天有效"); //四、點擊模板跳轉頁面
    sendTemplateReq.setPage(""); //五、Data,按次序,只能叫keyword一、二、3
    DoctorReplyMsgData replyData = new DoctorReplyMsgData(); KeyNote keyword1 = new KeyNote(); keyword1.setValue("小程序顯示的消息字段1"); replyData.setKeyword1(keyword1); KeyNote keyword2 = new KeyNote(); keyword2.setValue("小程序顯示的消息字段2"); replyData.setKeyword2(keyword2); sendTemplateReq.setData(replyData); //如上...總共五個字段 //六、獲取token
    String token = "token,倆小時有效"; //七、模板url拼接上token,最上面的請求的url那樣
    String url = "TemplateUrl" + "token"; //八、請求體轉爲json
    String reqStr=JsonUtil.ModelToGson(sendTemplateReq); //九、發送httpclient請求
    String resultStr = httpRequestUtil.doPost(sb.toString(), reqStr); //十、接收返回的消息體:是否成功,成功返回0
    SendTemplateResponse sendTemplateResponse = (SendTemplateResponse)JsonUtil.GsonToModel(resultStr,SendTemplateResponse.class); if(sendTemplateResponse.getErrcode() == 0){ //"推送成功!"
 } }

 

一、openid:經過jsCode獲取的

二、formid:小程序端傳過來的

三、Template_id:小程序設置模板時帶的

四、data:對象類型

五、token:調用接口獲取token

相關文章
相關標籤/搜索