Java開發微信小程序(三)用小程序給用戶推送服務消息

第三篇 用小程序給用戶推送服務消息

1.小程序登錄獲取,小程序的openId和unionId。

2.獲取並解密小程序的加密信息包括用戶和手機信息。

3.用小程序給用戶推送服務消息。

4.給綁定小程序而且又關注微信公衆號的用戶推送公衆號消息。

小程序消息推送機制有兩種一種是統一模板消息推送一種是客服消息,本章主要介紹在Java端向指定用戶推送指定模板的消息。

模板推送又分爲兩種一種是用小程序給用戶推送服務消息,本章主要介紹這個;

一種是給綁定小程序而且又關注微信公衆號的用戶推送公衆號消息;

爲便於開發者對用戶進行服務消息觸達,簡化小程序和公衆號模板消息下發流程,小程序提供統一的服務消息下發接口。

下發條件說明

1. 支付

當用戶在小程序內完成過支付行爲,可允許開發者向用戶在7天內推送有限條數的模板消息(1次支付可下發3條,多次支付下發條數獨立,互相不影響

2. 提交表單

當用戶在小程序內發生過提交表單行爲且該表單聲明爲要發模板消息的,開發者需要向用戶提供服務時,可允許開發者向用戶在7天內推送有限條數的模板消息(1次提交表單可下發1條,多次提交下發條數獨立,相互不影響)

 Java端通過openid推送消息給用戶

1. 小程序端將必要的參數發送給後臺

  onSendWeappMessage: function (e) {
    console.log(e);
    wx.request({
      url: "https://www.test.com/app/interface/miniprogram/miniprogramWeappMessage",
      data: {
        //模板ID
        template_id: "NKeZWyyEkOl4tT6fYwJN90RxCHt_xxxxxxx",
        //需要放大的關鍵詞
        emphasis_keyword:"",
        //放給誰需要用戶的openId,並收集當前用戶在頁面操作產生的formId
        toWeappUser:[
          { openid: "oTJ3H5Vxxxxxxxxxxxx", form_id: e.detail.formId}
        ],
        jsonMessage: {
          keyword1:"2017-12-12 12:24",
          keyword2:"已經滿員了已經滿員了已經滿員了已經滿員了已經滿員了已經滿員了"
        }
      },
      method: "POST",
      header: {
        'content-type': 'application/json',
      },
      success: function (res) {
        console.log(res);
      },
      fail: function (error) {
        console.log(error);
      }
    })
  }

2. Java服務端接收參數,並調用接口調用憑證獲取access_token 
access_token是接口調用的憑證,目前有效期爲兩個小時,需要定時刷新,重複獲取將導致上次獲取的access_token失效。(注:不建議每次調用需要access_token的接口,都去重新獲取access_token,會導致失敗) 
獲取小程序 access_token

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

返回參數格式:

{"access_token": "ACCESS_TOKEN", "expires_in": 7200}
	/**
	 * 獲取小程序 access_token ,每天最多獲取200次,一次2小時失效
	 * https://developers.weixin.qq.com/miniprogram/dev/api/open-api/access-token/getAccessToken.html
	 * <p/>
	 * Date 2018年9月29日 下午5:03:15
	 * <p/>
	 * 
	 * @author 網行天下
	 */
	public static synchronized MiniprogramResult getAccessTockenResult() {
		MiniprogramResult miniprogramResult = null;
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<String> responseEntity = null;
		Object sessionAttribute = EnvManager.getSessionAttribute(MINIPROGRAM_MINIPROGRAM_RESULT);
          // access_token會保存在本地服務器需要的時候去微信遠程獲取
		if (sessionAttribute != null) {
			miniprogramResult = (MiniprogramResult) sessionAttribute;
			if (StringUtils.isNotEmpty(miniprogramResult.getAccess_token())) {
				logger.debug("緩存中獲取小程序ACCESS_TOKEN成功返回數據:" + miniprogramResult);
				return miniprogramResult;
			}
		}
		String appid = "xxxxxxxxxxxxxxxx";
		String secret = "xxxxxxxxxxxxxxxx";

		// 微信的接口
		String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET", appid, secret);
		// 進行網絡請求,訪問url接口
		responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
		logger.debug("進行網絡請求獲取小程序ACCESS_TOKEN成功返回數據:" + responseEntity);
		// errcode 的合法值0
		// 根據返回值進行後續操作
		if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
			String sessionData = responseEntity.getBody();
			// 解析從微信服務器獲得的ACCESS_TOKEN;
			miniprogramResult = FastJsonUtils.getJavaBean(sessionData, MiniprogramResult.class);
            // access_token會保存在本地服務器保存100分鐘
			EnvManager.setSessionAttribute(MINIPROGRAM_MINIPROGRAM_RESULT, miniprogramResult, 6000);
			logger.info("遠程獲取小程序ACCESS_TOKEN成功返回數據:" + miniprogramResult);
		}
		return miniprogramResult;

	}


2. 發送模板消息 
先在微信公衆平臺選用怒需要的模板id,例如 
選用模板消息:

3. 發送模板的消息,接口地址:

https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=ACCESS_TOKEN
	/**
	 * 發送統一模板消息
	 * 
	 * @param token
	 * @param template
	 * @return
	 * 
	 */
	public static String sendUniformMessage(String json) {
		logger.info("發送統一模板消息:" + json);
		String sendResult = "";
        //獲取到服務器中的access_tocken
		MiniprogramResult result = getAccessTockenResult();
		if (result == null) {
			return sendResult;
		}
		String requestUrl = String.format("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=ACCESS_TOKEN",
				result.getAccess_token());
		logger.info("發送統一模板消息到:" + requestUrl);
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		// 請勿輕易改變此提交方式,大部分的情況下,提交方式都是表單提交
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

		HttpEntity<String> requestEntity = new HttpEntity<String>(json, headers);

		// 進行網絡請求,訪問url接口
		ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, HttpMethod.POST, requestEntity,
				String.class);
		logger.info("發送統一模板消息後接受數據:" + responseEntity);
		if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
			String sessionData = responseEntity.getBody();
			MiniprogramResult miniprogramResult = FastJsonUtils.getJavaBean(sessionData, MiniprogramResult.class);
			int errorCode = miniprogramResult.getErrcode();
			String errorMessage = miniprogramResult.getErrmsg();
			if (errorCode == 0) {
				sendResult = SEND_SUCCESS;
			} else {
				sendResult = SEND_FAIL;
				logger.error("模板消息發送失敗:" + errorCode + "," + errorMessage);
			}
		}
		return sendResult;
	}

本文參考文獻有

http://www.51xuediannao.com/xiaochengxu/0cba78ba.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章