com.gson.web.WeChatPayNotifyServlet.java Source code

Java tutorial

Introduction

Here is the source code for com.gson.web.WeChatPayNotifyServlet.java

Source

/**
 * ???(JAVA) SDK
 * (c) 2012-2013 ____? <wmails@126.cn>, MIT Licensed
 * http://www.jeasyuicn.com/wechat
 */
package com.gson.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.gson.WeChat;
import com.gson.bean.WeChatBuyPost;
import com.gson.oauth.Pay;
import com.gson.util.Tools;
import com.gson.util.WechatUtil;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * 
 * @author L.cm
 * email: 596392912@qq.com
 * site:  http://www.dreamlu.net
 * @date 2014-4-23 ?10:47:53
 */
public class WeChatPayNotifyServlet extends HttpServlet {

    private static final long serialVersionUID = 6139862236335427037L;

    //   fail success ?
    private static final String STATUC_SUCCESS = "success";
    private static final String STATUC_FAIL = "fail";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // post ?xml
        WeChatBuyPost postData = null;
        String openid = null;
        String appsignature = null;
        try {
            ServletInputStream in = req.getInputStream();
            // ?post?xml
            XStream xs = new XStream(new DomDriver());
            xs.alias("xml", WeChatBuyPost.class);
            String xmlMsg = Tools.inputStream2String(in);
            postData = (WeChatBuyPost) xs.fromXML(xmlMsg);

            System.out.println(postData.toString());
            // OpenId=oOGf-jjDL7Kv-xT6MBD1qoyKtzeU, AppId=wx136bc734aff403df, IsSubscribe=1, TimeStamp=1392628878, NonceStr=54ah1fs5UsTZrf8s, AppSignature=02b5d8f2ccd8ca42cf13c6e44b48513c13294093, SignMethod=sha1
            // 
            long timestamp = postData.getTimeStamp();
            String noncestr = postData.getNonceStr();
            openid = postData.getOpenId();
            int issubscribe = postData.getIsSubscribe();
            appsignature = postData.getAppSignature();
            boolean temp = Pay.verifySign(timestamp, noncestr, openid, issubscribe, appsignature);
            if (!temp) {
                System.out.println("error?");
                writeString(resp, STATUC_FAIL);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // post??
        @SuppressWarnings("unchecked")
        Map<String, String[]> parasMap = req.getParameterMap();
        // ?
        Map<String, String> paraMap = new HashMap<String, String>();
        for (Entry<String, String[]> entry : parasMap.entrySet()) {
            String key = entry.getKey();
            String[] value = entry.getValue();
            System.out.println(key + ":\t" + value);
            if (null == value) {
                continue;
            } else {
                paraMap.put(key, value[0]);
            }
        }
        /*
         paraMap:   {"transport_fee":["0"],"trade_mode":["1"],"trade_state":["0"],"sign_type":["MD5"],"input_charset":["UTF-8"],"fee_type":["1"],"out_trade_no":["7805803"],"transaction_id":["1217484201201402188208911673"],"discount":["0"],"bank_billno":["201402180770175"],"sign":["F06A82B69D7819785478E34A84BE5CA0"],"attach":["yongle"],"total_fee":["1"],"time_end":["20140218095638"],"partner":["1217484201"],"notify_id":["Kl8hcMyrMFtQLMvOl_hfnEOahccJRPEf-tFuN7ctFfxVxRPLeD0kqMf_AU7ADdMF1zsRaW4FZQ9K_kvMQFc62ScV_NvEhL-D"],"bank_type":["0"],"product_fee":["1"]}
         */

        /*
        // ?
        sign_type           ?? ? MD5? RSA
        service_version     ? 1.0
        input_charset       ?,? GBK? UTF-8
        sign_key_index      ???  1
        pay_info            ? ?
        bank_billno         ??
        attach              ?
        transport_fee       ??? 0??transport_fee + product_fee = total_fee
        product_fee         ? ??   ? ? transport_fee + product_fee=total_fee
        discount             ?? ,  total_fee + discount = total_fee ??
        buyer_alias         ?
            
        
        sign                ??
        trade_mode          1-?
        trade_state         0? ??
        partner             ???partnerid, ?10 ? (120XXXXXXX)
        bank_type            WX
        total_fee           ?  ???discount   total_fee+ discount =  total_fee
        fee_type            ??,????, 1-?
        notify_id            id ?? id??
        transaction_id      ? 28??10???8??20090415?10???
        out_trade_no        ?? 
        time_end            ??yyyyMMddhhmmss  GMT+8 beijing
         */
        String trade_state = req.getParameter("trade_state");
        String totalFee = req.getParameter("total_fee");
        String orderId = req.getParameter("out_trade_no");
        String transId = req.getParameter("transaction_id");
        String timeEnd = req.getParameter("time_end");

        System.out.println("trade_state:\t" + trade_state + "totalFee:\t" + totalFee + "orderId:\t" + orderId);

        if (StringUtils.isEmpty(orderId)) {
            writeString(resp, STATUC_FAIL);
            return;
        }

        //  bg
        // ***************
        //  ed

        // ????
        try {
            String accessToken = WechatUtil.getAccessToken();//WeChat.getAccessToken();
            WeChat.message.sendText(accessToken, orderId, "??" + orderId + "???");
            //????????...
            Pay.delivernotify(accessToken, openid, transId, transId, "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        writeString(resp, STATUC_SUCCESS);
    }

    /**
     * 
     * @param response
     * @param msg
     */
    private void writeString(HttpServletResponse response, String msg) {
        try {
            response.getWriter().write(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}