旗下导航:搜·么
当前位置:网站首页 > JAVA教程 > 正文

小顺序后端用什么写【JAVA教程】,java

作者:搜教程发布时间:2019-11-27分类:JAVA教程浏览:62评论:0


导读:这里本篇文章运用Java举行小顺序后端编写,由于公司前段时刻要做小顺序付出,所以这里把本身写的小顺序后端付出controller记录下来,文档参考微信付出官方文档,地点:https...
这里本篇文章运用Java举行小顺序后端编写,由于公司前段时刻要做小顺序付出,所以这里把本身写的小顺序后端付出controller记录下来,文档参考微信付出官方文档,地点:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_3&index=1。

引荐课程:Java教程。

空话不多说,直接上代码:

PayController

@Api(tags = "付出模块")
@RestController
@RequestMapping("")
public class PayController {

    @ApiOperation(value = "要求付出接口")
    @RequestMapping(value = "/wxPay", method = RequestMethod.POST)
    public JSONObject wxPay(HttpServletRequest request) {        try {            //生成的随机字符串
            String nonce_str = getRandomStringByLength(32);            //商品名称
            String body = "测试商品名称";            //猎取客户端的ip地点
            String spbill_create_ip = getIpAddr(request);            //组装参数,用户生成一致下单接口的署名
            Map<String, String> packageParams = new HashMap<>();
            packageParams.put("appid", WechatConfig.appid);
            packageParams.put("mch_id", WechatConfig.mch_id);
            packageParams.put("nonce_str", nonce_str);
            packageParams.put("body", body);
            packageParams.put("out_trade_no", payOrderId + "");//商户定单号,本身的定单ID
            packageParams.put("total_fee", 100 + "");//付出金额,这边须要转成字符串范例,不然背面的署名会失利
            packageParams.put("spbill_create_ip", spbill_create_ip);
            packageParams.put("notify_url", WechatConfig.notify_url);//付出胜利后的回调地点
            packageParams.put("trade_type", WechatConfig.TRADETYPE);//付出体式格局
            packageParams.put("openid", openId + "");//用户的openID,本身猎取

            String prestr = PayUtil.createLinkString(packageParams); // 把数组一切元素,依据“参数=参数值”的形式用“&”字符拼接成字符串

            //MD5运算生成署名,这里是第一次署名,用于挪用一致下单接口
            String mysign = PayUtil.sign(prestr, WechatConfig.key, "utf-8").toUpperCase();            //拼接一致下单接口运用的xml数据,要将上一步生成的署名一同拼接进去
            String xml = "<xml>" + "<appid>" + WechatConfig.appid + "</appid>"
                    + "<body><![CDATA[" + body + "]]></body>"
                    + "<mch_id>" + WechatConfig.mch_id + "</mch_id>"
                    + "<nonce_str>" + nonce_str + "</nonce_str>"
                    + "<notify_url>" + WechatConfig.notify_url + "</notify_url>"
                    + "<openid>" + openid + "</openid>"
                    + "<out_trade_no>" + payOrderId + "</out_trade_no>"
                    + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
                    + "<total_fee>" + 100 + "</total_fee>"//付出的金额,单元:分
                    + "<trade_type>" + WechatConfig.TRADETYPE + "</trade_type>"
                    + "<sign>" + mysign + "</sign>"
                    + "</xml>";            //挪用一致下单接口,并接收返回的效果
            String result = PayUtil.httpRequest(WechatConfig.pay_url, "POST", xml);            // 将剖析效果存储在HashMap中
            Map map = PayUtil.doXMLParse(result);            String return_code = (String) map.get("return_code");//返回状况码
            String result_code = (String) map.get("result_code");//返回状况码

            Map<String, Object> response = new HashMap<String, Object>();//返回给小顺序端须要的参数
            if (return_code == "SUCCESS" && return_code.equals(result_code)) {                String prepay_id = (String) map.get("prepay_id");//返回的预支单信息
                response.put("nonceStr", nonce_str);
                response.put("package", "prepay_id=" + prepay_id);
                Long timeStamp = System.currentTimeMillis() / 1000;
                response.put("timeStamp", timeStamp + "");//这边要将返回的时刻戳转化成字符串,不然小顺序端挪用wx.requestPayment要领会报署名毛病
                //拼接署名须要的参数
                String stringSignTemp = "appId=" + WechatConfig.appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp;                //再次署名,这个署名用于小顺序端挪用wx.requesetPayment要领
                String paySign = PayUtil.sign(stringSignTemp, WechatConfig.key, "utf-8").toUpperCase();

                response.put("paySign", paySign);
            }

            response.put("appid", WechatConfig.appid);            return Response.succ(response);
        } catch (Exception e) {
            e.printStackTrace();
        }        return null;
    }    //这里是付出回调接口,微信付出胜利后会自动挪用
    @RequestMapping(value = "/wxNotify", method = RequestMethod.POST)
    public void wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));        String line = null;
        StringBuilder sb = new StringBuilder();        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();        //sb为微信返回的xml
        String notityXml = sb.toString();        String resXml = "";        Map map = PayUtil.doXMLParse(notityXml);        String returnCode = (String) map.get("return_code");        if ("SUCCESS".equals(returnCode)) {            //考证署名是不是准确
            Map<String, String> validParams = PayUtil.paraFilter(map);  //回调验签时须要去除sign和空值参数
            String prestr = PayUtil.createLinkString(validParams); 
            //依据微信官网的引见,此处不仅对回调的参数举行验签,还须要对返回的金额与体系定单的金额举行比对等
            if (PayUtil.verify(prestr, (String) map.get("sign"), WechatConfig.key, "utf-8")) {                /**此处增加本身的营业逻辑代码start**/
                
                //注重要推断微信付出反复回调,付出胜利后微信会反复的举行回调
                
                /**此处增加本身的营业逻辑代码end**/
                //关照微信服务器已付出胜利
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
            }
        } else {
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }

        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }    //猎取随机字符串
    private String getRandomStringByLength(int length) {        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }        return sb.toString();
    }    //猎取IP
    private String getIpAddr(HttpServletRequest request) {        String ip = request.getHeader("X-Forwarded-For");        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {            //屡次反向代办后会有多个ip值,第一个ip才是实在ip
            int index = ip.indexOf(",");            if (index != -1) {                return ip.substring(0, index);
            } else {                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {            return ip;
        }        return request.getRemoteAddr();
    }
}

上面代码用到了PayUtil和WechatConfig这两个类,一个是设置类,一个是东西类,代码以下:

PayUtil

public class PayUtil {    /**
     * 署名字符串
     *
     * @param text          须要署名的字符串
     * @param key           密钥
     * @param input_charset 编码花样
     * @return 署名效果
     */
    public static String sign(String text, String key, String input_charset) {
        text = text + "&key=" + key;        return DigestUtils.md5Hex(getContentBytes(text, input_charset));
    }    /**
     * 署名字符串
     *
     * @param text          须要署名的字符串
     * @param sign          署名效果
     * @param key           密钥
     * @param input_charset 编码花样
     * @return 署名效果
     */
    public static boolean verify(String text, String sign, String key, String input_charset) {
        text = text + key;        String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));        if (mysign.equals(sign)) {            return true;
        } else {            return false;
        }
    }    /**
     * @param content
     * @param charset
     * @return
     * @throws java.security.SignatureException
     * @throws UnsupportedEncodingException
     */
    public static byte[] getContentBytes(String content, String charset) {        if (charset == null || "".equals(charset)) {            return content.getBytes();
        }        try {            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {            throw new RuntimeException("MD5署名过程当中涌现毛病,指定的编码集不对,您现在指定的编码集是:" + charset);
        }
    }

    private static boolean isValidChar(char ch) {        if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))            return true;        if ((ch >= 0x4e00 && ch <= 0x7fff) || (ch >= 0x8000 && ch <= 0x952f))            return true;// 简体中文汉字编码     
        return false;
    }    /**
     * 撤除数组中的空值和署名参数
     *
     * @param sArray 署名参数组
     * @return 去掉空值与署名参数后的新署名参数组
     */
    public static Map<String, String> paraFilter(Map<String, String> sArray) {        Map<String, String> result = new HashMap<String, String>();        if (sArray == null || sArray.size() <= 0) {            return result;
        }        for (String key : sArray.keySet()) {            String value = sArray.get(key);            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
                    || key.equalsIgnoreCase("sign_type")) {                continue;
            }
            result.put(key, value);
        }        return result;
    }    /**
     * 把数组一切元素排序,并依据“参数=参数值”的形式用“&”字符拼接成字符串
     *
     * @param params 须要排序并介入字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);        String prestr = "";        for (int i = 0; i < keys.size(); i++) {            String key = keys.get(i);            String value = params.get(key);            if (i == keys.size() - 1) {// 拼接时,不包括末了一个&字符     
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }        return prestr;
    }    /**
     * @param requestUrl    要求地点
     * @param requestMethod 要求要领
     * @param outputStr     参数
     */
    public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {        // 建立SSLContext     
        StringBuffer buffer = null;        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(requestMethod);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();            //往服务器端写内容     
            if (null != outputStr) {
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }            // 读取服务器端返回的内容     
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            buffer = new StringBuffer();            String line = null;            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }        return buffer.toString();
    }

    public static String urlEncodeUTF8(String source) {        String result = source;        try {
            result = java.net.URLEncoder.encode(source, "UTF-8");
        } catch (UnsupportedEncodingException e) {            // TODO Auto-generated catch block
            e.printStackTrace();
        }        return result;
    }    /**
     * 剖析xml,返回第一级元素键值对。假如第一级元素有子节点,则此节点的值是子节点的xml数据。
     *
     * @param strxml
     * @return
     * @throws org.jdom2.JDOMException
     * @throws IOException
     */
    public static Map doXMLParse(String strxml) throws Exception {        if (null == strxml || "".equals(strxml)) {            return null;
        }        Map m = new HashMap();
        InputStream in = String2Inputstream(strxml);
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();        while (it.hasNext()) {
            Element e = (Element) it.next();            String k = e.getName();            String v = "";
            List children = e.getChildren();            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = getChildrenText(children);
            }

            m.put(k, v);
        }        //封闭流
        in.close();        return m;
    }    /**
     * 猎取子结点的xml
     *
     * @param children
     * @return String
     */
    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();        if (!children.isEmpty()) {
            Iterator it = children.iterator();            while (it.hasNext()) {
                Element e = (Element) it.next();                String name = e.getName();                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");                if (!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }        return sb.toString();
    }

    public static InputStream String2Inputstream(String str) {        return new ByteArrayInputStream(str.getBytes());
    }
}

WechatConfig

public class WechatConfig {    //小顺序appid
    public static final String appid = "";    //微信付出的商户id
    public static final String mch_id = "";    //微信付出的商户密钥
    public static final String key = "";    //付出胜利后的服务器回调url,这里填PayController里的回调函数地点
    public static final String notify_url = "";    //署名体式格局,固定值
    public static final String SIGNTYPE = "MD5";    //交易范例,小顺序付出的固定值为JSAPI
    public static final String TRADETYPE = "JSAPI";    //微信一致下单接口地点
    public static final String pay_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
}

在刚刚开始打仗小顺序付出的时刻,也以为比较的辣手,由于本身并没有写过付出相干的代码。厥后经由过程百度查找材料和浏览官方文档,末了把这个付出的controller完成了。末了,一定要多读几遍官方文档,然后连系PayController的代码去看,就会发明实在付出也不是很难。

以上就是小顺序后端用什么写的细致内容,更多请关注ki4网别的相干文章!

标签:java


欢迎 发表评论: