微信公眾號(hào)發(fā)送模板消息中文亂碼(java)

使用 restTemplate 發(fā)送。

/**
 * 微信模板類
 */
@Data
public class WeChatTemplate implements Serializable {

    private static final long serialVersionUID = 612571563869874653L;
    /**
     * 模板id
     */
    private String template_id;

    /**
     * 接收者 openId
     */
    private String touser;

    /**
     * 模板跳轉(zhuǎn)鏈接
     */
    @JsonSerialize(include= JsonSerialize.Inclusion.NON_EMPTY)
    private String url;

    /**
     * data的數(shù)據(jù)
     */
    private TreeMap<String, TreeMap<String, String>> data;

    /**
     * data 里的數(shù)據(jù)
     *
     * @param value :模板參數(shù)
     * @param color :顏色 可選
     * @return
     */
    public static TreeMap<String, String> item(String value, String color) {
        TreeMap<String, String> params = new TreeMap<String, String>();
        params.put("value", value);
        params.put("color", color==null?"#173177":color);
        return params;
    }
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.company.platform.base.config.wxpay.sdk.MyWXPayConfig;
import com.company.platform.restapi.dao.hfss.WechatTemplateMessageLogMapper;
import com.company.platform.restapi.model.hfss.WechatTemplateMessageLogWithBLOBs;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.entity.StringEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

@Component
@Slf4j
public class WeChatTemplateMessageService {

    @Autowired
    private RestTemplate restTemplate;

    private static AccessToken accessToken = null;

    @Resource
    private MyWXPayConfig wxPayConfig;

    @Resource
    private WechatTemplateMessageLogMapper templateMessageLogMapper;

    /**
     * 獲取access_token的接口地址
     */
    public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    /**發(fā)送模板消息*/
    public static final String SEND_TEMPLATE_MESSAGE = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";

    /**
     * 通過(guò)APPID 和 APPSECRET
     * 獲取assess_token
     * @return
     */
    public AccessToken getAccessToken() {

        String appid = wxPayConfig.getAppID();
        String appsecret = wxPayConfig.getAppsecret();

        if(accessToken == null
            || DateUtils.addSeconds(accessToken.getReceiveTime(), accessToken.getExpires_in()).before(new Date())) {
            String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
            JSONObject jsonObject = restTemplate.getForObject(requestUrl,JSONObject.class);
            // 如果請(qǐng)求成功
            if (null != jsonObject) {
                try {
                    accessToken = new AccessToken();
                    accessToken.setAccess_token(jsonObject.getString("access_token"));
                    accessToken.setExpires_in(jsonObject.getInteger("expires_in"));
                    accessToken.setReceiveTime(new Date());
                } catch (JSONException e) {
                    accessToken = null;
                    // 獲取token失敗
                    log.error("獲取token失敗 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
                }
            }
        }

        return accessToken;
    }

    /**
     * 發(fā)送模板消息
     * @param accessToken
     * @param template
     * @return
     */
    public void sendTemplateMsg(String accessToken, WeChatTemplate template){

        String requestUrl =SEND_TEMPLATE_MESSAGE.replace("ACCESS_TOKEN",accessToken);
        JSONObject jsonObject = restTemplate.postForObject(requestUrl,template,JSONObject.class);
        log.info("返回jsonObject值:"+jsonObject);
        if (null != jsonObject) {
            int errorCode = jsonObject.getIntValue("errcode");

            //發(fā)送日志

            if (0 == errorCode) {
                log.info("模板消息發(fā)送成功");
            } else {
                String errorMsg = jsonObject.getString("errmsg");
                log.info("模板消息發(fā)送失敗,錯(cuò)誤是 "+errorCode+",錯(cuò)誤信息是"+ errorMsg);
            }
        }
    }

}

發(fā)送時(shí),直接使用bean發(fā)送,不要轉(zhuǎn)換成json,本人親測(cè)轉(zhuǎn)換成json串后發(fā)送會(huì)中文亂碼。
如果有哪位知道原因請(qǐng)留言,謝謝!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容