微信消息推送 -java

一、获取access_token

public static String getAccess_token(){
String access_token="";
String appid= “”;//获取appid
   String secret=“”;//获取secret
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret+"";
access_token = HttpJSON.loadJSON(url);
JSONObject jsonObject = new JSONObject(access_token);
Iterator iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
if(key.equals("access_token")){
access_token= jsonObject.getString(key);
}
}
return access_token;
}

二、获取openid

1.获取code

 public static String getYtCodeUrl(String uri){
    try {
uri = URLEncoder.encode(uri, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
    String appid= “”;//获取appid
    return "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+uri+"&response_type=code&scope=snsapi_userinfo#wechat_redirect";
    }


2.获取到openid

  
    /**
     * 获取access_token和openid
     * @return
     */
    public static String[] getAccess_tokenBycodeYiting(String code){
String[] res= new String[2];
String appid= “”;//获取appid
    String secret=“”;//获取secret
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
JSONObject jsonObject = new JSONObject(HttpJSON.loadJSON(url));
Iterator iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
if(key.equals("access_token")){
res[0]= jsonObject.getString(key);
}
if(key.equals("openid")){
res[1]= jsonObject.getString(key);
}
}
return res;
}    



三、推送

public static void generateInfo(Map<String,Object> reqMap) {

String access_token =WeixinClient.getAccess_token();

String title="您的店铺:"+reqMap.get("dpName")+"-新订单提醒";

StringBuilder desc = new StringBuilder("下单时间:"+(String)reqMap.get("tm")+"\n");//消息内容

String url = ConfigerUtil.getPropertys("orderReceipt") +"/mobileH5portal/portal/wxOderDetail.action?logindkttype="+ (Integer)reqMap.get("id");//消息链接地址

StringBuilder sb = new StringBuilder("{\"touser\":\"");
System.out.println((String)reqMap.get("openid"));
sb.append((String)reqMap.get("openid"));//openids
sb.append("\",");
sb.append("\"msgtype\":\"news\",");
sb.append("\"news\":{");
sb.append("\"articles\":[{");
sb.append("\"title\":\""+title+"\",");
sb.append("\"description\":\""+desc.toString()+"\",");
sb.append("\"url\":\""+url+"\"");
sb.append("}]}}");
System.out.println(sb.toString());
sendPost("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+access_token,sb.toString());
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值