生活随笔
收集整理的這篇文章主要介紹了
微信小程序推送功能最新版本(推送到服务通知java+微信小程序代码块)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
微信小程序的消息推送簡單的說就是發送一條微信通知給用戶,用戶點開消息可以查看消息內容,可以鏈接進入到小程序的指定頁面。
一、準備工作
首先,在微信公眾平臺開通消息推送功能,并添加消息模板。可以從模板庫選擇模板也可以創建一個模板,模板添加之后,模板ID我們接下來要用的。
然后拿到小程序的APPID和秘鑰
二~打開微信開發工具
加一個按鈕就可以,用這個按鈕去觸發這個函數方法
,sendDYMsg
: function(e
) {wx
.requestSubscribeMessage({tmplIds
: ['ooaZWfK6liHpqDAcnR2hgObdQuh2JqQP2Z_UR6vvraU'],success(res
) {console
.log("可以給用戶推送一條中獎通知了。。。");}})}
tmplIds是你小程序的模板id,觸發這個函數會彈出下面的方框
三、服務端(java)代碼開發:
1、老規矩先查看官網騰訊api文檔:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html
2、給大家介紹一個關于微信開發的工具類(個人感覺非常優秀,可以自己去看看。):
git地址:https://github.com/Wechat-Group/WxJava
小程序文檔地址:http://binary.ac.cn/weixin-java-miniapp-javadoc/
3.集成pom文件:
<!-- 小程序開發包
--><dependency><groupId>com
.github
.binarywang
</groupId
><artifactId>weixin
-java
-miniapp
</artifactId
><version>3.6.0</version
></dependency
><dependency><groupId>org
.projectlombok
</groupId
><artifactId>lombok
</artifactId
><optional>true</optional
></dependency
><dependency><groupId>cn
.hutool
</groupId
><artifactId>hutool
-all
</artifactId
><version>4.1.21</version
></dependency
>
4.根據code獲取openid:
code:(重點)只能使用一次,并且只有5分鐘有效期。
private static String
getOpenid(String code
){String URL
= "https://api.weixin.qq.com/sns/jscode2session?appid="+APPID1
+"&secret="+AppSecret1
+"&js_code="+code
+"&grant_type=authorization_code";String openId
=interfaceUtil(URL
, "");return openId
;};
這個openid必須是小程序的openid其他的openid不可以
5.最終環節進行小程序訂閱消息推送
訂閱消息傳參和模板消息是不一樣的,需要根據人家規則進行填寫,加了正則校驗了
推送代碼
@GetMapping(value
= "/messagePush")@ResponseBodypublic Object
sendDYTemplateMessage(String openId
) throws Exception
{System
.err
.println("openId:"+openId
);wxsmallTemplate tem
= new wxsmallTemplate();tem
.setPage("pages/index/index");tem
.setTemplate_id("-UBAuupYlK2RAbxYvhk6UvK48ujQD72RpEOdkF-sJ2s");tem
.setToUser(openId
);List
<wxsmallTemplateParam> paras
= new ArrayList<wxsmallTemplateParam>();wxsmallTemplateParam templateParam
= new wxsmallTemplateParam("thing2", "紅包已到賬", "#DC143C");paras
.add(templateParam
);paras
.add(new wxsmallTemplateParam("phrase3", "劉騫", ""));tem
.setData(paras
);tem
.setToken(getAccessToken());try {
if(sendTemplateMsg1(getAccess_token(APPID1
,AppSecret1
), tem
)){return "推送成功";}else{JSONObject jsonObject
= new JSONObject(); jsonObject
.put("buTie",tem
);return jsonObject
;}} catch (Exception e
) {e
.printStackTrace();}return "推送失敗";}public static boolean sendTemplateMsg1(String token
,wxsmallTemplate template
) {System
.err
.println("token:"+token
);boolean flag
= false;String requestUrl
= "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
requestUrl
= requestUrl
.replace("ACCESS_TOKEN", token
);JSONObject jsonResult
=JSON
.parseObject(post(JSON
.parseObject(template
.toJSON()) ,requestUrl
)) ;if (jsonResult
!= null
) {Integer errorCode
= jsonResult
.getInteger("errcode");String errorMessage
= jsonResult
.getString("errmsg");if (errorCode
== 0) {flag
= true;} else {System
.out
.println("模板消息發送失敗:" + errorCode
+ "," + errorMessage
);flag
= false;}}return flag
;}public String
getAccess_token(String appid
, String appsecret
) {String url
="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid
+"&secret="+appsecret
;
JSONObject jsonObject
= doGet1(url
);System
.out
.println(jsonObject
.toString());String errCode
= jsonObject
.getString("expires_in");if (!StringUtils
.isEmpty(errCode
) && !StringUtils
.isEmpty(jsonObject
.getString("access_token").toString())) {String token
= jsonObject
.get("access_token").toString();return token
;} else {return null
;}}public static JSONObject
doGet1(String url
) {CloseableHttpClient client
= HttpClients
.createDefault();HttpGet httpGet
= new HttpGet(url
);JSONObject jsonObject
= null
;try {HttpResponse httpResponse
= client
.execute(httpGet
);HttpEntity entity
= httpResponse
.getEntity();if (entity
!= null
) {String result
= EntityUtils
.toString(entity
, "UTF-8");jsonObject
= JSONObject
.parseObject(result
);}} catch (Exception e
) {e
.printStackTrace();} finally {try {httpGet
.releaseConnection();client
.close();} catch (IOException e
) {e
.printStackTrace();}}return jsonObject
;}
public static String
post(JSONObject json
,String URL
) {HttpClient client
= new DefaultHttpClient();HttpPost post
= new HttpPost(URL
);post
.setHeader("Content-Type", "application/json");post
.addHeader("Authorization", "Basic YWRtaW46");String result
= "";try {StringEntity s
= new StringEntity(json
.toString(), "utf-8");s
.setContentEncoding(new BasicHeader(HTTP
.CONTENT_TYPE
,"application/json"));post
.setEntity(s
);HttpResponse httpResponse
= client
.execute(post
);InputStream inStream
= httpResponse
.getEntity().getContent();BufferedReader reader
= new BufferedReader(new InputStreamReader(inStream
, "utf-8"));StringBuilder strber
= new StringBuilder();String line
= null
;while ((line
= reader
.readLine()) != null
)strber
.append(line
+ "\n");inStream
.close();result
= strber
.toString();System
.out
.println(result
);if (httpResponse
.getStatusLine().getStatusCode() == HttpStatus
.SC_OK
) {System
.out
.println("請求服務器成功,做相應處理");} else {System
.out
.println("請求服務端失敗");}} catch (Exception e
) {System
.out
.println("請求異常");throw new RuntimeException(e
);}return result
;}
到現在微信小程序訂閱消息推送就到此結束了,是不是超級簡單那種。
給大家分享一個,只給用戶提示一次,下次就不用提示就可以一直發送通知的方案: 微信設置了總是保持以上選擇,不在詢問按鈕,只要把這對勾給點擊上。下次點擊通知函數,就不會給用戶提示哦。 我給點擊了按鈕,到現在我都沒找到從哪能開啟這個提示。
總結
以上是生活随笔為你收集整理的微信小程序推送功能最新版本(推送到服务通知java+微信小程序代码块)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。