当前位置:   article > 正文

基于java后台的微信小程序之微信支付前后端代码(详细过程)_微信小程序实现微信支付,前后端代码

微信小程序实现微信支付,前后端代码

在这里插入图片描述

首先是微信支付的配置类:WxPayConfig

public class WxPayConfig {
    //小程序appid
    public static final String appid = "wx9eb0dffa5de476ba";
    //微信支付的商户id
    public static final String mch_id = "xxxxxx";//商户号
    //微信支付的商户密钥
    public static final String key = "xxxxxxxxxxxxxxxxxxxx";//商户的key
    //支付成功后的服务器回调url,回调函数的地址(就是自己写在Controller里的回调函数)但是不许外网能访问(可以进行内网穿透)
    public static final String notify_url = "https://live.tinyshark.com.cn/wxNotify";
    //签名方式
    public static final String SIGNTYPE = "MD5";
    //交易类型
    public static final String TRADETYPE = "JSAPI";
    //微信统一下单接口地址
    public static final String pay_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

这个类很简单只要将里面的相应的值改成自己的就可以直接复制粘贴

然后写我们微信支付的接口和回调函数的接口:PayController

package com.lbm.controller;

import com.lbm.config.WxPayConfig;
import com.lbm.pojo.Invite;
import com.lbm.pojo.Order;
import com.lbm.pojo.YuZhiFu;
import com.lbm.service.Impl.InviteServiceImpl;
import com.lbm.service.Impl.OrderServiceImpl;
import com.lbm.service.Impl.YuZhiFuServiceImpl;
import com.lbm.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
public class PayController {
    /**
     * @param openid
     * @param request
     * @author: 龙
     * @date:2020/12/23/10:04 Description:发起微信支付
     */

    @Autowired
    YuZhiFuServiceImpl yuZhiFuService;

    YuZhiFu yuZhiFu=new YuZhiFu();

    @Autowired
    InviteServiceImpl inviteService;

    Invite invite=new Invite();

    @RequestMapping("wxPay")
    @ResponseBody
    //这里面的参数都是我需要的参数你们可以不要(只要HttpServletRequest request)
    public Map<String, Object> wxPay(String money,String oldtoken,String openid, HttpServletRequest request,String kname,String bname,String times,String bsex,String phone){


        try{
            //微信里面的价格是以分为单位

            //生成的随机字符串
            String nonce_str = StringUtils.getRandomStringByLength(32);
            //商户订单号
            String out_trade_no= new RandomUtil().getRandomCode(10);
            //商品名称
            String body = "寒假钜惠抢先购";
            //获取客户端的ip地址
            String spbill_create_ip = IpUtils.getIpAddr(request);
            //组装参数,用户生成统一下单接口的签名
            Map<String, String> packageParams = new HashMap<String, String>();
            packageParams.put("appid", WxPayConfig.appid);
            packageParams.put("mch_id", WxPayConfig.mch_id);
            packageParams.put("nonce_str", nonce_str);
            packageParams.put("body", body);
            packageParams.put("out_trade_no", out_trade_no);//商户订单号
            packageParams.put("total_fee", money);//支付金额,这边需要转成字符串类型,否则后面的签名会失败
            packageParams.put("spbill_create_ip", spbill_create_ip);
            packageParams.put("notify_url", WxPayConfig.notify_url);//支付成功后的回调地址
            packageParams.put("trade_type", WxPayConfig.TRADETYPE);//支付方式
            packageParams.put("openid", openid);

            String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串

            //MD5运算生成签名,这里是第一次签名,用于调用统一下单接口
            String mysign = PayUtil.sign(prestr, WxPayConfig.key, "utf-8").toUpperCase();

            //拼接统一下单接口使用的xml数据,要将上一步生成的签名一起拼接进去
            String xml = "<xml>" + "<appid>" + WxPayConfig.appid + "</appid>"
                    + "<body><![CDATA[" + body + "]]></body>"
                    + "<mch_id>" + WxPayConfig.mch_id + "</mch_id>"
                    + "<nonce_str>" + nonce_str + "</nonce_str>"
                    + "<notify_url>" + WxPayConfig.notify_url + "</notify_url>"
                    + "<openid>" + openid + "</openid>"
                    + "<out_trade_no>" + out_trade_no + "</out_trade_no>"
                    + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
                    + "<total_fee>" + money + "</total_fee>"
                    + "<trade_type>" + WxPayConfig.TRADETYPE + "</trade_type>"
                    + "<sign>" + mysign + "</sign>"
                    + "</xml>";
            System.out.println("调试模式_统一下单接口 请求XML数据:" + xml);
            //调用统一下单接口,并接受返回的结果
            String result = PayUtil.httpRequest(WxPayConfig.pay_url, "POST", xml);

            //这里是我处理的一些逻辑(你们可以自己写自己的逻辑,这里也可以不写)————将预支付状态存入数据库,等支付成功后改支付状态为已支付。这里面的参数就对应上面那些可以不用的参数
            Date date = new Date();
            String trackTime = DateUtils.formateTrackTime(date);
            yuZhiFu.setBody(body);
            yuZhiFu.setOldtoken(oldtoken);
            yuZhiFu.setKname(kname);
            yuZhiFu.setBname(bname);
            yuZhiFu.setTimes(times);
            yuZhiFu.setBsex(bsex);
            yuZhiFu.setStatus("0");//默认支付状态为0,支付成功后在处理微信回调的逻辑中将它改成已支付
            yuZhiFu.setPhone(phone);
            yuZhiFu.setToken(openid);
            yuZhiFu.setOut_trade_no(out_trade_no);
            yuZhiFu.setBuytime(trackTime);
            yuZhiFu.setTotal_fee(Integer.parseInt(money)/100+"");
            yuZhiFuService.insertYuZhiFu(yuZhiFu);


            System.out.println("调试模式_统一下单接口 返回XML数据:" + result);
            // 将解析结果存储在HashMap中
            Map map = PayUtil.doXMLParse(result);
            System.out.println(map);
            String return_code = (String) map.get("return_code");//返回状态码
            Map<String, Object> response = new HashMap<String, Object>();//返回给小程序端需要的参数
            if(return_code.equals("SUCCESS")){
                String prepay_id = String.valueOf(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=" + WxPayConfig.appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id+ "&signType=MD5&timeStamp=" + timeStamp;
                //再次签名,这个签名用于小程序端调用wx.requesetPayment方法
                String paySign = PayUtil.sign(stringSignTemp, WxPayConfig.key, "utf-8").toUpperCase();
                response.put("paySign", paySign);
            }
            response.put("appid", WxPayConfig.appid);
            return response;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }




    /**
     * @Description:微信支付的回调函数
     * @return
     * @throws "Exception"
     */
    @RequestMapping("wxNotify")
    @ResponseBody
    public String wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception{


        System.out.println("进入了回调》》》》》》》》》》》》》》》》》》》》》》》》");
        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)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 = "";
        System.out.println("接收到的报文:" + notityXml);

        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 validStr = PayUtil.createLinkString(validParams);//把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
            String sign = PayUtil.sign(validStr, WxPayConfig.key, "utf-8").toUpperCase();//拼装生成服务器端验证的签名

            //根据微信官网的介绍,此处不仅对回调的参数进行验签,还需要对返回的金额与系统订单的金额进行比对等
            if(sign.equals(map.get("sign"))){
                /**此处添加自己的业务逻辑代码start**/
                System.out.println("开始=================");
                String out_trade_no=(String) map.get("out_trade_no");
                String transaction_id=(String) map.get("transaction_id");
                //买的人token
                String token=(String) map.get("openid");
                Date date = new Date();
                String time_end = DateUtils.formateTrackTime(date);

                HashMap<String, String> stringHashMap = new HashMap<>();
                stringHashMap.put("status","已支付");//这里将微信支付改成已支付
                stringHashMap.put("buytime",time_end);
                stringHashMap.put("transaction_id",transaction_id);
                stringHashMap.put("out_trade_no",out_trade_no);
                yuZhiFuService.updateYuZhiFu(stringHashMap);
                List<Order> orders = yuZhiFuService.queryByTokenCourse(stringHashMap);
                for (Order order : orders) {
                    String oldtoken = order.getOldtoken();
                    String buytime = order.getBuytime();
                    invite.setOldtoken(oldtoken);
                    invite.setToken(token);
                    invite.setBuytime(buytime);
                    invite.setTransaction_id(order.getTransaction_id());
                    inviteService.insert(invite);
                }

                System.out.println("结束=============================");

                /**此处添加自己的业务逻辑代码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> ";
        }

        System.out.println(resXml);
        System.out.println("微信支付回调数据结束");

        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
        Map maps = PayUtil.doXMLParse(resXml);
        String returnCodes = (String) maps.get("return_code");
        return  returnCodes;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232

下面是编写接口遇到的所有工具类

StringUtils
package com.lbm.utils;

import java.util.Random;

/**
 * Created with Intellij IDEA
 *
 * @Auther:龙本淼
 * @date:2020/12/23/9:58 Description:
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils{
    /**
     * StringUtils工具类方法
     * 获取一定长度的随机字符串,范围0-9,a-z
     * @param length:指定字符串长度
     * @return 一定长度的随机字符串
     */
    public static 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();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
RandomUtil
package com.lbm.utils;

/**
 * Created with Intellij IDEA
 *
 * @Auther:龙本淼
 * @date:2020/12/20/16:33 Description:
 */
public class RandomUtil {
    public String getRandomCode(int codeLen) {
        java.util.Random randomCode = new java.util.Random();
        String strCode = "";
        while (codeLen > 0) {
            int charCode = randomCode.nextInt(9);
            strCode += charCode;
            codeLen--;
        }
        return strCode;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
IpUtils
package com.lbm.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with Intellij IDEA
 *
 * @Auther:龙本淼
 * @date:2020/12/23/9:56 Description:
 */

public class IpUtils {
    /**
     * IpUtils工具类方法
     * 获取真实的ip地址
     * @param request
     * @return
     */
    public static 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();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
PayUtil
package com.lbm.utils;

/**
 * Created with Intellij IDEA
 *
 * @Auther:龙本淼
 * @date:2020/12/23/11:11 Description:
 */

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;

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 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<String>(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 JDOMException
     * @throws IOException
     */
    public static Map doXMLParse(String strxml) throws Exception {
        if(null == strxml || "".equals(strxml)) {
            return null;
        }
        /*=============  !!!!注意,修复了微信官方反馈的漏洞,更新于2018-10-16  ===========*/
        try {
            Map<String, String> data = new HashMap<String, String>();
            // TODO 在这里更换
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
            documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
            documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            documentBuilderFactory.setXIncludeAware(false);
            documentBuilderFactory.setExpandEntityReferences(false);

            InputStream stream = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {
            throw ex;
        }
    }
    /**
     * 获取子结点的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());
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
DateUtils
package com.lbm.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with Intellij IDEA
 *
 * @Auther:龙本淼
 * @date:2020/12/18/17:19 Description:
 */
public class DateUtils {
        public static String formateTrackTime(Date trackTime){
            String result = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(trackTime);
//        System.out.println("13位数的时间戳(毫秒)--->Date:" + result);
            return result;
        }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

最后就是小程序端的代码了

js
//提交按钮
  formSubmit:function(e){
    var that = this;
    var info = e.detail.value;
    console.log(info)
    if (info.bname.length < 2) {
      app.alert({
        "content": "请输入正确姓名"
      });
    }else if (info.phone.length < 11) {
      app.alert({
        "content": "请输入正确号码"
      });
    }else{
     
              console.log("tiem"+info.times)
                var openid = app.getCache("token")
                console.log("openid>>>>>" + openid)
                wx.request({
                  url: app.serverUrl + '/wxPay',
                  header: {
                    //设置参数内容类型为x-www-form-urlencoded
                    'content-type': 'application/x-www-form-urlencoded',
                    'Accept': 'application/json'
                  },
                  data: {
                    cid:that.data.cid,
                    oldtoken:that.data.oldtoken,
                    openid: openid,
                    money:that.data.money*100,
                    request: "",
                    kname: info.kname,
                    bname:info.bname,
                    times:info.times,
                    bsex:info.bsex,
                    phone:info.phone
                  },
                  method: 'POST',
                  success: function (res) {
                    console.log(res)
                    var data = res.data;
                    wx.requestPayment({
                      timeStamp: data.timeStamp,
                      nonceStr: data.nonceStr,
                      package: data.package,
                      signType: 'MD5',
                      paySign: data.paySign,
                      success: function (res) {
                        console.log("支付成功")
                      },
                      fail: function (res) {
                        console.log(res)
                      },
                      complete:function(e){
                        wx.navigateBack({
                          delta: 1,
                        })
                      }
                    })
                  },
                  fail: function (res) {
                    console.log(res)
                  },
                })
    }
  },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
wxml
<form bindsubmit="formSubmit" bindreset="formReset">
  <view class="forms">
    <view class="cu-list menu {{menuBorder?'sm-border':''}} {{menuCard?'card-menu margin-top':''}}">

      <view class="cu-item {{menuArrow?'arrow':''}}">
        <view class="content">
          <text class="text-grey">报名课程</text>
        </view>
        <view class="action">
         <picker bindchange="PickerChange1" value="{{picker1[index1]}}" range="{{picker1}}" name="kname">
            <view class="picker">
              {{picker1[index1]}}
            </view>
          </picker>
        </view>
      </view>

      <view class="cu-item">
        <view class="content">
          <text class="text-grey">宝贝姓名</text>
        </view>
        <view class="action">
          <input name="bname" placeholder-style='text-align:right' value="" placeholder="请输入孩子姓名" maxlength="6"></input>
        </view>
      </view>

      <view class="cu-item {{menuArrow?'arrow':''}}">
        <view class="content">
          <text class="text-grey">上课时间</text>
        </view>
        <view class="action">
          <picker bindchange="PickerChange" value="{{picker[index]}}" range="{{picker}}" name="times">
            <view class="picker">
              {{picker[index]}}
            </view>
          </picker>
        </view>
      </view>

      <view class="cu-item {{menuArrow?'arrow':''}}">
        <view class="content">
          <text class="text-grey">宝贝年级</text>
        </view>
        <view class="action">
         <picker bindchange="PickerChange2" value="{{picker2[index2]}}" range="{{picker2}}" name="bsex">
            <view class="picker">
              {{picker2[index2]}}
            </view>
          </picker>
        </view>
      </view>



      <view class="cu-item ">
        <view class="content">
          <text class="text-grey">手机号码:</text>
        </view>
        <view class="action">
          <input name="phone" value="" placeholder-style='text-align:right' placeholder="请输入手机号码" maxlength="11"></input>
        </view>
      </view>
      
      
      
    </view>
  </view>
  <button form-type="submit" class='endbtn'>报名并支付</button>
</form>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
wxss
/* pages/index/XiangQing/BaoMing/BaoMing.wxss */

::-webkit-input-placeholder { /* WebKit browsers */
  float: right;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
  direction: rtl;
}
.endbtn {  
margin-top: 30rpx;
margin-bottom: 20rpx;
width: 300rpx;
height: 70rpx;
right: 0rpx;
font-size: 30rpx;
text-align: center;
color:#fae9b3;
background-color:#373634;
box-shadow: 1rpx 2rpx 10rpx 2rpx #b3c0fa;
}
.page {
height: 100Vh;
width: 100vw;
}

.page.show {
overflow: hidden;
}

.switch-sex::after {
content: "\e716";
}

.switch-sex::before {
content: "\e7a9";
}

.switch-music::after {
content: "\e66a";
}

.switch-music::before {
content: "\e6db";
}
.text-grey{
text-align: center;
font-size: 16px;
color: black;
}
.photo{
margin:20rpx 0; 
}
.datum{
margin-top:20rpx; 
}
.grey-icon{
color: red;
font-size: 25px;
text-align: center
}
.text-sm{
color: rgb(202, 202, 202);
}
input{
text-align: right
}
.forms{
  display: block;

  margin: 20rpx;
  
}
.cu-list.menu {

border-radius: 10rpx;
}
.cu-item{

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80

最后说说我开始写的时候遇到的问题:

  • 后端需要多少个参数微信端就给多少个多了少了都会不成功(我个人是遇到的这种情况,不知道别的人有没有遇到)
  • 而且测试的时候会有SSL证书问题一直调用不成功,如果遇到请不用管,继续一直支付多试几次就会成功
  • 上面要进行内网穿透,详情可以看我的另一篇博客 https://blog.csdn.net/qq_44795116/article/details/112093603
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/593625
推荐阅读
相关标签
  

闽ICP备14008679号