search
HomeJavajavaTutorialWhat to use to write the backend of the mini program?

Here this article uses Java to write the back-end of the mini program. Since the company has to do mini program payment some time ago, so here I record the back-end payment controller of the mini program I wrote. For the document, please refer to the official WeChat payment document, address: https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_3&index=1.

Recommended course: Java Tutorial.

What to use to write the backend of the mini program?

Without further ado, let’s go straight to the code:

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> 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>"
                    + ""
                    + "<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> response = new HashMap<string>();//返回给小程序端需要的参数
            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> 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></return_code>"
                        + "<return_msg></return_msg>" + "</xml> ";
            }
        } else {
            resXml = "<xml>" + "<return_code></return_code>"
                    + "<return_msg></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 <p>The above code uses PayUtil and WechatConfig has two classes, one is the configuration class and the other is the tool class. The code is as follows: </p>
<p><strong>PayUtil</strong></p>
<pre class="brush:php;toolbar:false">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 = 'A' && ch = 'a' && ch = 0x4e00 && ch = 0x8000 && ch  paraFilter(Map<string> sArray) {        Map<string> result = new HashMap<string>();        if (sArray == null || sArray.size()  params) {
        List<string> keys = new ArrayList(params.keySet());
        Collections.sort(keys);        String prestr = "";        for (int i = 0; i ");                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());
    }
}</string></string></string></string>

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";
}

When I first came into contact with mini program payment, I also found it tricky because I had never written any payment-related code. Later, I searched for information through Baidu and read official documents, and finally completed the payment controller. Finally, be sure to read the official documentation several times, and then combine it with the code of PayController, and you will find that payment is not difficult.

The above is the detailed content of What to use to write the backend of the mini program?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software