1. 程式人生 > >微信公眾號客服介面給指定使用者openid傳送訊息

微信公眾號客服介面給指定使用者openid傳送訊息

微信開發文件:

客服介面-發訊息

介面呼叫請求說明

http請求方式: POST
https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN

各訊息型別所需的JSON資料包如下:

傳送文字訊息

{
    "touser":"OPENID",
    "msgtype":"text",
    "text":
    {
         "content":"Hello World"
    }
}

建立封裝實體類:

import java.util.Map;

/**
 * 客戶介面訊息傳送實體
 *
 * @author 
 * @date 2018-2-6 11:00:30
 */
public class TestMessage {

    //openid
    private String touser;

    //訊息型別
     private String msgtype;

     //訊息內容
     private Map<String,Object> text ;


    public String getTouser() {
        return touser;
    }

    public void setTouser(String touser) {
        this.touser = touser;
    }

    public String getMsgtype() {
        return msgtype;
    }

    public void setMsgtype(String msgtype) {
        this.msgtype = msgtype;
    }

    public Map<String, Object> getText() {
        return text;
    }

    public void setText(Map<String, Object> text) {
        this.text = text;
    }
}

後臺controller程式碼:

/**
 * 狀態修改為測試中
 *
 * @param id 要測試的ID
 * @param request
 * @return 內容展示頁面
 */
@ResponseBody
@RequestMapping(value = "/service/test", method = RequestMethod.PUT)
public ResponseVO ContentTest(Long id, HttpServletRequest request) {

    ResponseVO vo=new ResponseVO();
    if(id!=null){
        //根據接收的ID查詢相應的內容實體
        WeixinContent weixinContent = weixinContentService.selectById(id);
     //判斷查詢到的物件的合法性
    if (weixinContent!=null&&(weixinContent.getState() == 1||weixinContent.getState()==4)) {
        //修改內容實體狀態為測試中
        weixinContent.setState(2);

        //將內容實體進行儲存操作
        weixinContentService.updateById(weixinContent);
        //獲得內容靜態頁面的訪問路徑
       String templatesUrl= weixinContent.getTemplatesUrl();
        //拼接訪問的完整路徑
        String saveUrl =fileuploadPrefix + "/" + templatesUrl;
        //獲得內容資訊標題
        String title = weixinContent.getTitle();
        //拼接傳送的訊息內容
        String content="你好!標題("+title+")<a href='"+saveUrl+"'>點我測試</a>";
        //建立微信使用者查詢條件
        Wrapper<WeixinUser> wrapper=new EntityWrapper<>();
        wrapper.where("tagid_list={0}","[101]");
        //獲得滿足條件的集合
        List<WeixinUser> weixinUsers = weixinUserService.selectList(wrapper);
        //遍歷使用者集合呼叫業務層進行訊息傳送
        for (WeixinUser weixinUser : weixinUsers) {
            String openid = weixinUser.getOpenid();
            //呼叫業務層進行傳送訊息
            wxContentTextService.contentTest(openid,content);
        }

        vo.setSuccess(true);
    } else {
        //不是未測試狀態所以不能進行狀態修改
        vo.setSuccess(false);
    }

    }
    return vo;
}

後臺service程式碼:

/**
 * <p>
 * 選單資訊 服務實現類
 * </p>
 *
 * @author 
 * @date 2018/01/15
 */
@Service
public class WxContentTextService {

    private static Logger log = LoggerFactory.getLogger(WxContentTextService.class);

    /**
     * 客服介面給使用者傳送訊息介面
     */
    public static String  content_openid="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN";

    @Autowired
    private TokenFeignService tokenFeignService;

    @Autowired
    private WeixinPortalService weixinPortalService;

    /**
     *
     * @param openid   openid
     * @param saveUrl   靜態頁面訪問地址
     * @return
     */
    public ResponseVO contentTest(String openid,String saveUrl){
        //獲得令牌
        String accessToken = tokenFeignService.getToken();

        //建立返回實體物件
        ResponseVO vo = new ResponseVO();
        //替換token
        String url=content_openid.replace("ACCESS_TOKEN", accessToken);

        TestMessage testMessage=new TestMessage();
        //設定訊息的型別
        testMessage.setMsgtype("text");
        //設定要傳送的openid集合
        testMessage.setTouser(openid);
        //建立集合
        Map<String,Object> map=new HashMap<>();
        //設定傳送內容
        map.put("content",saveUrl);
        testMessage.setText(map);
        //將測試訊息物件轉成json
        String jsonTestMessage = JSONObject.toJSONString(testMessage);
        //呼叫介面進行傳送
        JSONObject jsonObject = httpRequest(url, "POST", jsonTestMessage);

        log.error("分組群發訊息失敗 errcode:{" + jsonObject.getInteger("errcode")+"} " +
                "errmsg:{"+jsonObject.getString("errmsg")+"} ");
        Integer errcode = jsonObject.getInteger("errcode");
        String errorCodeText = ErrorCodeText.errorMsg(errcode);

        if (errcode == 0){
            vo.setSuccess(true);
        }else{
            vo.setSuccess(false);
        }
        vo.setCode(errcode);
        vo.setText(errorCodeText);
        return vo;

    }
}

獲取token的業務層:

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 進行請求分發
 *
 */
@FeignClient(value = "weixin-2")
public interface TokenFeignService {

    /**
     * 進行token請求
     * @param
     * @return
     */
    @RequestMapping(value = "/getToken",method = RequestMethod.GET)
    String getToken();
}

微信請求工具類utils

public class WeixinHttpUtil {

    private static Logger log = LoggerFactory.getLogger(WeixinHttpUtil.class);

    /**
     * 描述:  發起https請求並獲取結果
     * @param requestUrl 請求地址
     * @param requestMethod 請求方式(GET、POST)
     * @param outputStr 提交的資料
     * @return JSONObject(通過JSONObject.get(key)的方式獲取json物件的屬性值)
     */
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 建立SSLContext物件,並使用我們指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 從上述SSLContext物件中得到SSLSocketFactory物件
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);

            // 設定請求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
            {httpUrlConn.connect();}

            // 當有資料需要提交時
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意編碼格式,防止中文亂碼
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 將返回的輸入流轉換成字串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 釋放資源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException ce) {
            log.error("Weixin server connection timed out.");
        } catch (Exception e) {
            log.error("https request error:{}", e);
        }
        return jsonObject;
    }
}