微信公众号消息推送,注册成功,支付成功,积分余额变化

只要能拿到openid,什么都好办,很简单

趁着失业了更新一下代码,做做笔记

支付成功回调开始写,不知道怎么获取openid再看看其他博客

 //支付回调接口(微信异步会通知)notify_url 配置的值
    public void moneysuccess() {
        System.out.println("==============成功!!");
        InputStream is = null;
        try {
            is = this.request.getInputStream();
            String retStr = new String(Util.readInput(is), "utf-8");
            //Map map =WXPayUtil.xmlToMap(retStr);
            Map map = XMLParser.getMapFromXML(retStr);
            //返回的数据
            if (map.get("return_code").equals("SUCCESS")) {
                System.out.println("微信支付返回成功!!");
                if (map.get("result_code").equals("SUCCESS")) {
                    String ordersSn = (String) map.get("out_trade_no");//商户订单号
                    String amountpaid = (String) map.get("total_fee");//实际支付的订单金额:单位 分
                    BigDecimal amountPay = (new BigDecimal(amountpaid).divide(new BigDecimal("100"))).setScale(2);//将分转换成元-实际支付金额:元
                    String openId = (String) map.get("openid");//获取用户的openId,发送公众号提醒消息
                    System.out.println("===========ordersSn=" + ordersSn);
                    System.out.println("支付金额============" + amountpaid);//这个就是支付金额
                    Orders byNo = this.ordersService.findByNo(ordersSn);
                    if (byNo != null) {
                        // 根据订单编号获取订单详情
                        List list = useritemService.UserItemList(byNo.getNo());
                        // 如果订单时虚拟产品即不用发货
                        if (0 == byNo.getOrderTypeId()) {
                            try {
                                ordersService.virtual_order(byNo, byNo.getUser(), openId);
                                // 根据订单编号获取订单详情
                                if (list.size() > 0) {
                                    for (Useritem useritem : list) {
                                        ProductPackage productPackage = useritem.getProductPackage();
                                        if (productPackage.getLevel() == 1) {
                                            //待收货
                                            byNo.setStatus(1);
                                        } else {
                                            // 已完成
                                            byNo.setStatus(3);
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                byNo.setStatus(1);
                            }
                        }
                        if (1 == byNo.getOrderTypeId()) {
                            byNo.setStatus(1);
                            String sql = "from Product WHERE deleted = 0";
                            List productList = productService.list(sql);
                            if (list.size() > 0) {
                                for (Useritem useritem : list) {
                                    for (int i = 0; i < productList.size(); i++) {
                                        if (useritem.getProduct().getId() .equals(productList.get(i).getId())){
                                            productList.get(i).setSoldNumber(productList.get(i).getSoldNumber() + 1);
//                                            productList.get(i).setSoldNumber(productList.get(i).getInventory() - 1);
                                            productService.saveOrUpdate(productList.get(i));
                                        }
                                    }
                                }
                            }
                        }
                        //下面开始判断,然后发送消息
                        boolean b = this.ordersService.saveOrUpdate(byNo);
                        if (b) {
                            //用户是否订阅该公众号标识 (0代表此用户没有关注该公众号 1表示关注了该公众号)
                            Integer state = WX_UserUtil.subscribeState(openId);
                            System.out.println("state:" + state);
                            // 绑定了微信并且关注了服务号的用户 , 支付成功-推送成功短信
                            if (state.equals(1)) {
                                // System.out.println("进来==");
                                Map param = new HashMap<>();
                                param.put("first", new TemplateData("恭喜您下单成功!", "#696969"));
                                param.put("keyword1", new TemplateData(byNo.getNo(), "#696969"));
                                param.put("keyword2", new TemplateData(byNo.getMoney() + "", "#696969"));
                                param.put("keyword3", new TemplateData(byNo.getConsignee(), "#696969"));
                                param.put("keyword4", new TemplateData(byNo.getConsigneeAddress(), "#696969"));
                                param.put("remark", new TemplateData("感谢您的支持!", "#696969"));
                                //注册的微信-模板Id
                                // String regTempId =  WX_TemplateMsgUtil.getWXTemplateMsgId("ywBb70467vr18");
                                JSON.toJSONString(param);
                                JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(param));
                                //调用发送微信消息给用户的接口
                                String s = WX_TemplateMsgUtil.sendWechatMsgToUser(openId, "hDU1M85QoI82GhS-ivIQGK4ChMUhoYvPzVQUM3YC3L4", "", "#000000", jsonObject);

                                if (s.equals("success")) {
                                    System.out.println("发送成功");
                                } else {
                                    System.out.println("发送失败");
                                }
                                //获取公众号的自动回复规则
                             /*   String urlinfo = "https://api.weixin.qq.com/cgi-bin/get_current_autoreply_info?access_token=" + WX_TokenUtil.getWXToken().getAccessToken();
                                JSONObject joinfo = WX_HttpsUtil.httpsRequest(urlinfo, "GET", null);
                                Object o = joinfo.get("is_add_friend_reply_open");
                                // System.out.println("o:"+joinfo);
                                String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxefec2885eea59367&secret=3471cfc5d501a5f517f1c2998accebcb";
                                JSONObject Token = WX_HttpsUtil.httpsRequest(getTokenUrl, "GET", null);
                                System.out.println("Token:" + Token);*/
                            } else {
                                System.out.println("没进来!!");
                            }

                            System.out.println("修改成功!!!");
                        } else {
                            System.out.println("修改失败!!");
                        }
                    } else {
                        System.out.println("查询不到订单编号!!");
                    }
//                        String id = this.request.getParameter("id");
//                        System.out.println("moneysuccessid======="+id);
                }
            }
            //高数微信,支付返回成功
            this.response.setContentType("text/xml");
            String xml = ""
                    + ""
                    + ""
                    + "";
            this.response.getWriter().print(xml);
            this.response.getWriter().flush();
            this.response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2.下面是一些工具类

/**
 * @author li
 * @date 2019/2/15-9:31
 */

public class WX_UserUtil {
    private static Logger log = LoggerFactory.getLogger(WX_UserUtil.class);
    /**
     * 根据微信openId 获取用户是否订阅
     * @param openId 微信openId
     * @return 是否订阅该公众号标识
     */
    public static Integer subscribeState(String openId){
        String tmpurl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+WX_TokenUtil.getWXToken().getAccessToken() +"&openid="+openId;
        JSONObject result = WX_HttpsUtil.httpsRequest(tmpurl, "GET",null);
        JSONObject resultJson = new JSONObject(result);
        log.error("获取用户是否订阅 errcode:{} errmsg:{}", resultJson.getInteger("errcode"), resultJson.getString("errmsg"));
        String errmsg = (String) resultJson.get("errmsg");
        if(errmsg==null){
            //用户是否订阅该公众号标识(0代表此用户没有关注该公众号 1表示关注了该公众号)。
            Integer subscribe = (Integer) resultJson.get("subscribe");
            return subscribe;
        }
        return -1;
    }

    public static WX_Userinfo HeadImgUrl(String openId){
        WX_Userinfo wx=new WX_Userinfo();
        String tmpurl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+WX_TokenUtil.getWXToken().getAccessToken() +"&openid="+openId+"&&lang=zh_CN";
        JSONObject result = WX_HttpsUtil.httpsRequest(tmpurl, "GET",null);
        JSONObject resultJson = new JSONObject(result);
        log.error("获取用户头像 errcode:{} errmsg:{}", resultJson.getInteger("errcode"), resultJson.getString("errmsg"));
        String errmsg=(String)resultJson.get("errmsg");
        if(errmsg==null){//不报错情况下
            //获取头像
            wx.setHeadimgurl(resultJson.getString("headimgurl"));

            //获取名字
            wx.setNickname(resultJson.getString("nickname"));

            //获取性别
            return wx;
        }else{
            return null;
        }

    }



}
/**
 * 模板信息
 * @author li
 * @date 2019/2/15-9:20
 */
public class TemplateData {

    private String value;
    private String color;
    public TemplateData(String value,String color){
        this.value = value;
        this.color = color;
    }
    /**
     * @return the value
     */
    public String getValue() {
        return value;
    }
    /**
     * @param value the value to set
     */
    public void setValue(String value) {
        this.value = value;
    }
    /**
     * @return the color
     */
    public String getColor() {
        return color;
    }
    /**
     * @param color the color to set
     */
    public void setColor(String color) {
        this.color = color;
    }

}
/**
 * 信息通知模板消息实体类
 * @author li
 * @date 2019/2/15-9:22
 */

import java.util.Map;

public class TemplateMessage {
    private String touser; //用户OpenID
    private String template_id; //模板消息ID
    private String url; //URL置空,在发送后,点模板消息进入一个空白页面(ios),或无法点击(android)。
    private String topcolor; //标题颜色
    private Map templateData; //模板详细信息

    public static TemplateMessage New() {
        return new TemplateMessage();
    }

    /**
     * @return the touser
     */
    public String getTouser() {
        return touser;
    }
    /**
     * @param touser the touser to set
     */
    public void setTouser(String touser) {
        this.touser = touser;
    }
    /**
     * @return the template_id
     */
    public String getTemplate_id() {
        return template_id;
    }
    /**
     * @param template_id the template_id to set
     */
    public void setTemplate_id(String template_id) {
        this.template_id = template_id;
    }
    /**
     * @return the url
     */
    public String getUrl() {
        return url;
    }
    /**
     * @param url the url to set
     */
    public void setUrl(String url) {
        this.url = url;
    }
    /**
     * @return the topcolor
     */
    public String getTopcolor() {
        return topcolor;
    }
    /**
     * @param topcolor the topcolor to set
     */
    public void setTopcolor(String topcolor) {
        this.topcolor = topcolor;
    }
    /**
     * @return the templateData
     */
    public Map getTemplateData() {
        return templateData;
    }
    /**
     * @param templateData the templateData to set
     */
    public void setTemplateData(Map templateData) {
        this.templateData = templateData;
    }

}

/**
 * @author li
 * @date 2019/2/15-9:24
 */
public class WX_HttpsUtil {

    private static Logger log = LoggerFactory.getLogger(WX_HttpsUtil.class);
    /**
     * 发送https请求
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式(GET、POST)
     * @param outputStr 提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        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 conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            conn.setRequestMethod(requestMethod);
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException ce) {
            log.error("连接超时:{}", ce);
        } catch (Exception e) {
            log.error("https请求异常:{}", e);
        }
        return jsonObject;
    }

}


public class WX_TokenUtil {

    private static Logger log = LoggerFactory.getLogger(WX_TokenUtil.class);
    /**
     *  获得微信 AccessToken
     * access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。
     * 开发者需要access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取
     * 的access_token失效。
     * (此处我是把token存在Redis里面了)
     */

    public static AccessToken getWXToken() {

        String appId="wxd8c9ea3c6057842c";
        String appSecret="f3ad7b677658c1ed854984ee39c4f4e5";
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appId+"&secret="+ appSecret;
        JSONObject jsonObject = WX_HttpsUtil.httpsRequest(tokenUrl, "GET", null);
        System.out.println("jsonObject:"+jsonObject);
        AccessToken access_token = new AccessToken();
        if (null != jsonObject) {
            try {
                access_token.setAccessToken(jsonObject.getString("access_token"));
                access_token.setExpiresin(jsonObject.getInteger("expires_in"));
            } catch (JSONException e) {
                access_token = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
            }
        }

        return access_token;
    }

}
/**
 * AccessToken 对象
 * @author li
 * @date 2019/2/15-9:14
 */
public class AccessToken implements Serializable {
    //获取到的凭证
    private String accessToken;
    //凭证有效时间,单位:秒
    private int expiresin;
    /**
     * @return the accessToken
     */
    public String getAccessToken() {
        return accessToken;
    }
    /**
     * @param accessToken the accessToken to set
     */
    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }
    /**
     * @return the expiresin
     */
    public int getExpiresin() {
        return expiresin;
    }
    /**
     * @param expiresin the expiresin to set
     */
    public void setExpiresin(int expiresin) {
        this.expiresin = expiresin;
    }
    public AccessToken() {
        // TODO Auto-generated constructor stub
    }

}
/**
 * 微信请求 - 信任管理器
 * @author li
 * @date 2019/2/15-9:18
 */

public class MyX509TrustManager implements X509TrustManager {

    public MyX509TrustManager() {
        // TODO Auto-generated constructor stub
    }
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    }
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        //        return new X509Certificate[0];
        return  null;
    }

}

你可能感兴趣的:(微信开发)