微信公众号发送模板消息中文乱码(java)

2019-08-19  本文已影响0人  莫非的老公

使用 restTemplate 发送。

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

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

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

    /**
     * 模板跳转链接
     */
    @JsonSerialize(include= JsonSerialize.Inclusion.NON_EMPTY)
    private String url;

    /**
     * data的数据
     */
    private TreeMap<String, TreeMap<String, String>> data;

    /**
     * data 里的数据
     *
     * @param value :模板参数
     * @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";

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

    /**
     * 通过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);
            // 如果请求成功
            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;
    }

    /**
     * 发送模板消息
     * @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");

            //发送日志

            if (0 == errorCode) {
                log.info("模板消息发送成功");
            } else {
                String errorMsg = jsonObject.getString("errmsg");
                log.info("模板消息发送失败,错误是 "+errorCode+",错误信息是"+ errorMsg);
            }
        }
    }

}

发送时,直接使用bean发送,不要转换成json,本人亲测转换成json串后发送会中文乱码
如果有哪位知道原因请留言,谢谢!

上一篇下一篇

猜你喜欢

热点阅读