当前位置: 代码网 > it编程>编程语言>Java > Java接入微信支付超级详细保姆级教程

Java接入微信支付超级详细保姆级教程

2024年12月26日 Java 我要评论
本文介绍了“二维码付款”的代码。其他微信支付方式的代码都在源码中。一、准备开发所需的账号以及配置信息首先想要接入微信支付我们需要两个玩意:一是公众号/小程序/企业微信(开发用的

本文介绍了“二维码付款”的代码。其他微信支付方式的代码都在源码中。

一、准备开发所需的账号以及配置信息

首先想要接入微信支付我们需要两个玩意:

一是公众号/小程序/企业微信(开发用的)这个是为了获取 appid

一是微信支付商户(收钱用的) 获取 api_key mch_id

1、前往:https://mp.weixin.qq.com/ (微信公众平台)注册一个应用,类型只能是:公众号/小程序/企业微信,注册完成需要完成”微信认证“(微信需要收取300元)。

2、前往:https://pay.weixin.qq.com(微信支付商户平台)注册一个商户,支付成功后的钱就会在这个账号里面。

​ 1、appid:应用id也就是 公众号/小程序的id

​ 2、api_key: 对应的apiv2密钥

​ 3、mch_id:商户id (收钱的商家id)对应的是 【微信支付商户号】

4.将申请的下来的appid绑定到商户号下,添加成功后再次到工作号里面

【广告与服务—>微信支付】这个时候会看到关联申请,同意就可以了。到这一步前置工作就完成了

二、准备环境

项目采用springboot

微信支付有两种版本:v3和v2,本文的接入版本为v2

1、导入jar包

1.1微信支付jar包

<dependency>
  <groupid>com.github.wxpay</groupid>
  <artifactid>wxpay-sdk</artifactid>
  <version>0.0.3</version>
</dependency>

1.2导入hutool工具类jar包

<dependency>
    <groupid>cn.hutool</groupid>
    <artifactid>hutool-all</artifactid>
    <version>5.8.12</version>
</dependency>

2、设置开发参数

如果自己就是商户 那么可以将参数设置到配置文件application.yml中,如果是多商户则建立商户收款配置表 将信息维护到数据库中
在application.yml,设置好开发参数

pay:
  appid: wx123456789a439 #微信公众号appid
  api_key: gwxkjvfewvfabvcrxgrawvgs924ceaxj #公众号设置的api密钥
  mch_id: 1603596731 #微信商户平台 商户id

本文是多商户

  • 数据库参考

  • 微信支付工具类

package com.manage.common.utils;

import javax.net.ssl.httpsurlconnection;
import javax.servlet.http.httpservletrequest;
import java.io.*;
import java.net.url;

/**
 * 微信支付工具类
 *
 */
public class wxchatpaycommonutil {
        /**
         * 发送 http 请求
         * @param requesturl    请求路径
         * @param requestmethod 请求方式(get/post/put/delete/...)
         * @param outputstr     请求参数体
         * @return 结果信息
         */
        public static string httpsrequest(string requesturl, string requestmethod, string outputstr) {
            try {
                url url = new url(requesturl);
                httpsurlconnection conn = (httpsurlconnection) url.openconnection();
                conn.setdooutput(true);
                conn.setdoinput(true);
                conn.setusecaches(false);
                // 设置请求方式(get/post)
                conn.setrequestmethod(requestmethod);
                conn.setrequestproperty("content-type", "application/x-www-form-urlencoded");
                // 当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();
                return buffer.tostring();
            } catch (exception e) {
                e.printstacktrace();
            }
            return null;
        }

        /**
         * 获取ip
         * @param request 请求
         * @return ip 地址
         */
        public static string getip(httpservletrequest request) {
            if (request == null) {
                return "";
            }
            string ip = request.getheader("x-requested-for");
            if (stringutils.isempty(ip) || "unknown".equalsignorecase(ip)) {
                ip = request.getheader("x-forwarded-for");
            }
            if (stringutils.isempty(ip) || "unknown".equalsignorecase(ip)) {
                ip = request.getheader("proxy-client-ip");
            }
            if (stringutils.isempty(ip) || "unknown".equalsignorecase(ip)) {
                ip = request.getheader("wl-proxy-client-ip");
            }
            if (stringutils.isempty(ip) || "unknown".equalsignorecase(ip)) {
                ip = request.getheader("http_client_ip");
            }
            if (stringutils.isempty(ip) || "unknown".equalsignorecase(ip)) {
                ip = request.getheader("http_x_forwarded_for");
            }
            if (stringutils.isempty(ip) || "unknown".equalsignorecase(ip)) {
                ip = request.getremoteaddr();
            }
            return ip;
        }

        /**
         * 从流中读取微信返回的xml数据
         * @param httpservletrequest
         * @return
         * @throws ioexception
         */
        public static string readxmlfromstream(httpservletrequest httpservletrequest) throws ioexception {
            inputstream inputstream = httpservletrequest.getinputstream();
            bufferedreader bufferedreader = new bufferedreader(new inputstreamreader(inputstream));
            final stringbuffer sb = new stringbuffer();
            string line = null;
            try {
                while ((line = bufferedreader.readline()) != null) {
                    sb.append(line);
                }
            } finally {
                bufferedreader.close();
                inputstream.close();
            }

            return sb.tostring();
        }

        /**
         * 设置返回给微信服务器的xml信息
         * @param returncode
         * @param returnmsg
         * @return
         */
        public static string setreturnxml(string returncode, string returnmsg) {
            return "<xml><return_code><![cdata[" + returncode + "]]></return_code><return_msg><![cdata[" + returnmsg + "]]></return_msg></xml>";
        }
}
  • 微信支付接口地址
package com.manage.common.utils;

/**
 * 微信支付接口地址
 *
 */
public class wechatpayurl {
    //统一下单预下单接口url
    public static final string uifiedorder = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    //订单状态查询接口url
    public static final string orderquery = "https://api.mch.weixin.qq.com/pay/orderquery";
    //订单申请退款
    public static final string refund = "https://api.mch.weixin.qq.com/secapi/pay/refund";
    //付款码 支付
    public static final string micropay = "https://api.mch.weixin.qq.com/pay/micropay";
    //微信网页授权 获取“code”请求地址
    public static final string gaincodeurl = "https://open.weixin.qq.com/connect/oauth2/authorize";

}
  • 钱 工具类
package com.manage.common.utils;

import com.manage.common.object.younumberutil;

import java.math.bigdecimal;

/**
 * 钱 工具类
 *
 * created by youhan on 2019-06-28 09:12:00
 * copyright © 2019 youhan all rights reserved.
 */
public class moneyutils {
    public static final string yuan = "元";
    public static final string fen = "分";

    /**
     * 元转分
     *
     * @param s
     * @return java.lang.integer
     * @date 2020/9/10 9:03
     * @author youhan
     */
    public static integer yuantofen(string s) {
        if (!younumberutil.isnumber(s)) {
            return 0;
        }

        return new bigdecimal(s).multiply(new bigdecimal(100)).intvalue();
    }

    /**
     * 处理分
     *
     * @param s
     * @return java.lang.integer
     * @author youhan
     * @date 2022/7/23
     */
    public static integer handlefen(string s) {
        if (!younumberutil.isnumber(s)) {
            return 0;
        }

        return new bigdecimal(s).intvalue();
    }

    /**
     * 分转元
     *      可以为正负小数(这里保留2位小数)
     *
     * @param s
     * @return java.lang.string
     * @date 2020/9/10 9:01
     * @author youhan
     */
    public static string fentoyuan(string s) {
        if (!younumberutil.isnumber(s) || "0".equals(s) || "-0".equals(s)) {
            return "0.00";
        }

        return new bigdecimal(s)
                .divide(new bigdecimal(100))
                .setscale(2, bigdecimal.round_down)
                .tostring();
    }

    /**
     * 处理元
     *      可以为正负小数(这里保留2位小数)
     *
     * @param s
     * @return java.lang.string
     * @author youhan
     * @date 2022/7/23
     */
    public static string handleyuan(string s) {
        if (!younumberutil.isnumber(s) || "0".equals(s) || "-0".equals(s)) {
            return "0.00";
        }

        return new bigdecimal(s)
                .setscale(2, bigdecimal.round_down)
                .tostring();
    }

    public static void main(string[] args) {
        system.out.println(yuantofen("10.00"));
    }
}
  • 数字 client
package com.manage.common.object;

import org.apache.commons.lang3.stringutils;
import org.springframework.util.collectionutils;

import java.util.arraylist;
import java.util.list;
import java.util.set;
import java.util.uuid;
import java.util.regex.matcher;
import java.util.regex.pattern;

/**
 * string client
 *
 * created by youhan on 2019-09-11 08:57:56
 * copyright © 2019 youhan all rights reserved.
 */
public class youstringutil {

	/**
	 * 下划线
	 */
	public static final pattern line = pattern.compile("_(\\w)");

	/**
	 * 驼峰
	 */
	public static final pattern hump = pattern.compile("[a-z]");

	/**
	 * 添加内容
	 *
	 * @param content
	 * @param length
	 * @return java.lang.string
	 * @author youhan
	 * @date 2021/6/17 9:59
	 */
	public static string appendcontent(string content, int length) {
		if (length <= 0) {
			return "";
		}

		stringbuilder sb = new stringbuilder();

		for (int i = 0; i < length; i ++) {
			sb.append(content);
		}

		return sb.tostring();
	}

	/**
	 * 添加前缀内容
	 *
	 * @param s
	 * @param content
	 * @param length
	 * @return java.lang.string
	 * @date 2019-08-12 09:53
	 * @author youhan
	 */
	public static string appendprefixcontent(string s, string content, int length) {

		if (length <= 0) {
			return null;
		}

		stringbuilder sb = new stringbuilder(s);
		for (int i = 0; i < length; i ++) {
			sb.append(content, 0, content.length());
		}

		return sb.tostring();
	}

	/**
	 * 添加后缀内容
	 *
	 * @param s
	 * @param content
	 * @param length
	 * @return java.lang.string
	 * @date 2019-08-12 09:56
	 * @author youhan
	 */
	public static string appendsuffixcontent(string s, string content, int length) {
		if (length <= 0) {
			return null;
		}

		stringbuilder sb = new stringbuilder(s);

		for (int i = 0; i < length; i ++) {
			sb.append(content);
		}

		return sb.tostring();
	}

	/**
	 * set 转 string
	 *
	 * @param stringset
	 * @return java.lang.string
	 * @author youhan
	 * @date 2021/6/3 9:26
	 */
	public static string settostring(set<string> stringset) {
		return settostring(stringset, null);
	}

	/**
	 * set 转 string
	 *
	 * @param stringset
	 * @param regex
	 * @return java.lang.string
	 * @date 2021/6/3 9:21
	 * @author youhan
	 */
	public static string settostring(set<string> stringset, string regex) {
		// 参数校验
		if (collectionutils.isempty(stringset)) {
			return null;
		}
		if (stringutils.isblank(regex)) {
			regex = ",";
		}

		// list to string
		stringbuilder sb = new stringbuilder(stringset.size());
		for (string s : stringset) {
			sb.append(s).append(regex);
		}

		// 返回结果
		return sb.substring(0, sb.length() - 1);
	}

	/**
	 *  字符串列表转字符串
	 *
	 * @author youhan
	 * @generateddate: 2018/10/9 17:25
	 * @param stringlist 要转换的字符串列表
	 * @return
	 */
	public static string listtostring(list<string> stringlist) {
		return listtostring(stringlist, null);
	}

	/**
	 *  字符串列表转字符串
	 *
	 * @author youhan
	 * @generateddate: 2018/10/9 17:25
	 * @param stringlist 要转换的字符串列表
	 * @return
	 */
	public static string listtostring(list<string> stringlist, string regex) {
		// 参数校验
		if (collectionutils.isempty(stringlist)) {
			return null;
		}
		if (stringutils.isblank(regex)) {
			regex = ",";
		}

		// list to string
		stringbuilder sb = new stringbuilder(stringlist.size());
		for (string s : stringlist) {
			sb.append(s).append(regex);
		}

		// 返回结果
		return sb.substring(0, sb.length() - 1);
	}

	/**
	 * 字符串转列表
	 *
	 * @param s
	 * @return java.client.list<java.lang.string>
	 * @date 2019-09-11 09:11
	 * @author youhan
	 */
	public static list<string> stringtolist(string s) {
		/**
		 * 参数校验
		 */
		if (stringutils.isblank(s)) {
			return null;
		}

		return stringtolist(s, null);
	}

	/**
	 * 字符串转列表
	 *
	 * @param s
	 * @param regex 分割规则,默认为逗号
	 * @return java.client.list<java.lang.string>
	 * @date 2019-09-11 09:11
	 * @author youhan
	 */
	public static list<string> stringtolist(string s, string regex) {
		/**
		 * 参数校验
		 */
		if (stringutils.isblank(s)) {
			return null;
		}

		/**
		 * 默认逗号隔开
		 */
		if (stringutils.isblank(regex)) {
			regex = ",";
		}

		/**
		 * 去除首尾空格
		 */
		string blankstring = " ";
		while (s.startswith(blankstring)) {
			s = s.substring(1);
		}
		while (s.endswith(blankstring)) {
			s = s.substring(0, s.length() -1);
		}

		/**
		 * 返回结果列表
		 */
		list<string> resultlist = new arraylist<>();

		/**
		 * 只有单个元素
		 */
		if (!s.contains(regex)) {
			resultlist.add(s);
			return resultlist;
		}

		string[] strings = s.split(regex);
		for (string e : strings) {
			resultlist.add(e);
		}

		return resultlist;
	}

	/**
	 * 过滤逗号
	 * @param s
	 * @return
	 */
	public static string filtercommastring(string s) {
		// 数据为空校验
		if (stringutils.isempty(s)) {
			return null;
		}

		// 去除 并列逗号
		s = s.replace(",,", ",");

		// 去除 首逗号
		if (s.startswith(",")) {
			s = s.substring(1, s.length() - 1);
		}

		// 去除 尾逗号
		if (s.endswith(",")) {
			s = s.substring(0, s.length() - 1);
		}

		return s;
	}

	/**
	 * 是否包含中文(包括中文标点符号和空格)
	 *
	 * @param s
	 * @return boolean
	 * @date 2020/9/9 13:30
	 * @author youhan
	 */
	public static boolean iscontainchinese(string s) {
		/**
		 * 参数校验
		 */
		if (stringutils.isblank(s)) {
			return false;
		}

		if (s.contains(" ")) {
			return true;
		}

		/**
		 * 中文正则表达式
		 */
		string regex = "[\u4e00-\u9fa5]";

		if (s.matches(regex)) {
			return boolean.true;
		}

		/**
		 * 中文标点符号处理
		 */
		char[] chars = s.tochararray();
		for (char c : chars) {
			if (ischinesepunctuation(c)) {
				return true;
			}
		}

		return false;
	}

	/**
	 * 过滤中文(包括标点符号和空格)
	 *
	 * @param s
	 * @return java.lang.string
	 * @date 2020/9/9 14:08
	 * @author youhan
	 */
	public static string filterchinese(string s) {
		/**
		 * 参数校验
		 */
		if (stringutils.isblank(s)) {
			return "";
		}

		s = s.replace(" ", "");

		if (!iscontainchinese(s)) {
			return s;
		}

		/**
		 * 过滤中文字符
		 */
		char[] chars = s.tochararray();
		stringbuilder sb = new stringbuilder(chars.length);
		for (char c : chars) {
			if (iscontainchinese(string.valueof(c))) {
				continue;
			}
			sb.append(c);
		}

		return sb.tostring();
	}

	/**
	 * 判断是否为中文标点符号
	 *
	 * @param c
	 * @return java.lang.boolean
	 * @date 2020/9/9 13:43
	 * @author youhan
	 */
	public static boolean ischinesepunctuation(char c) {
		character.unicodeblock ub = character.unicodeblock.of(c);
		if (ub == character.unicodeblock.general_punctuation
				|| ub == character.unicodeblock.cjk_symbols_and_punctuation
				|| ub == character.unicodeblock.halfwidth_and_fullwidth_forms
				|| ub == character.unicodeblock.cjk_compatibility_forms
				|| ub == character.unicodeblock.vertical_forms) {
			return true;
		}

		return false;
	}

	/**
	 * 获取 uuid
	 *
	 * @param
	 * @return java.lang.string
	 * @date 2021/4/9 14:08
	 * @author youhan
	 */
	public static string getuuid() {
		return uuid.randomuuid().tostring().replace("-", "");
	}

	/**
	 * 安全比较(可防止时序攻击 timing attack)
	 */
	public static boolean safeequal(string a, string b) {
		if (stringutils.isblank(a) || stringutils.isblank(b)) {
			return false;
		}
		if (a.length() != b.length()) {
			return false;
		}
		int equal = 0;
		for (int i = 0; i < a.length(); i++) {
			equal |= a.charat(i) ^ b.charat(i);
		}
		return equal == 0;
	}

	/**
	 * 驼峰转下划线
	 *
	 * @param s
	 * @return java.lang.string
	 * @date 2021/5/6 22:20
	 * @author youhan
	 */
	public static string humptoline(string s) {
		matcher matcher = hump.matcher(s);
		stringbuffer sb = new stringbuffer();
		while (matcher.find()) {
			matcher.appendreplacement(sb, "_" + matcher.group(0).tolowercase());
		}
		if (sb.tostring().startswith("_")) {
			sb.deletecharat(0);
		}

		matcher.appendtail(sb);
		return sb.tostring();
	}

	/**
	 * 下划线转驼峰
	 *
	 * @param s
	 * @return java.lang.string
	 * @date 2021/5/6 22:21
	 * @author youhan
	 */
	public static string linetohump(string s) {
		s = s.tolowercase();
		matcher matcher = line.matcher(s);
		stringbuffer sb = new stringbuffer();
		while (matcher.find()) {
			matcher.appendreplacement(sb, matcher.group(1).touppercase());
		}
		matcher.appendtail(sb);
		return sb.tostring();
	}

	/**
	 * 生成加密的内容
	 *
	 * @param s
	 * @return java.lang.string
	 * @author youhan
	 * @date 2021/6/17 10:10
	 */
	public static string hide(string s) {
		/**
		 * 1
		 * 1*
		 * 1**
		 * 1***
		 * 1***5
		 * 12***6
		 * 12***67
		 * 123***78
		 * 123***789
		 * 123****890
		 * 123*****8901
		 */
		if (s.isempty() || s.length() == 1) {
			return s;
		}

		if (s.length() == 2) {
			return s.substring(0, 1) + "*";
		}

		if (s.length() == 3 || s.length() == 4) {
			return s.substring(0, 1) + appendcontent("*", s.length() - 1);
		}

		if (s.length() == 5) {
			return s.substring(0, 1) + "***" + s.substring(4);
		}

		if (s.length() == 6 || s.length() == 7) {
			return s.substring(0, 2) + appendcontent("*", 3) + s.substring(5);
		}

		if (s.length() == 8) {
			return s.substring(0, 3) + "***" + s.substring(6);
		}

		return s.substring(0, 3) + appendcontent("*", s.length() - 6) + s.substring(s.length() - 3);
	}
}
  • string client
package com.manage.common.object;

import org.apache.commons.lang3.stringutils;

import java.util.concurrent.threadlocalrandom;

/**
 * 数字 client
 *
 * created by youhan on 2020-09-09 13:28:40
 * copyright © 2021 youhan all rights reserved.
 */
public class younumberutil {
    /**
     * 整数正则表达式
     */
    public static final string integer_regex = "^[-\\+]?[\\d]*$";

    /**
     * 数字正则表达式
     */
    public static final string number_regex = "^-?\\d+(\\.\\d+)?$";

    /**
     * 是否是整数
     *
     * @param s
     * @return java.lang.boolean
     * @date 2020/9/12 8:38
     * @author youhan
     */
    public static boolean isinteger(string s) {
        if (stringutils.isblank(s)) {
            return false;
        }

        return s.matches(integer_regex);
    }

    /**
     * 判断给定字符串是否为十六进制数
     *
     * @param value 值
     * @return 是否为十六进制
     */
    public static boolean ishex(string value) {
        final int index = (value.startswith("-") ? 1 : 0);
        if (value.startswith("0x", index) || value.startswith("0x", index) || value.startswith("#", index)) {
            try {
                long.decode(value);
            } catch (numberformatexception e) {
                return false;
            }
            return true;
        }

        return false;
    }

    /**
     * 是否是数字(包括小数)
     *
     * @param s
     * @return java.lang.boolean
     * @date 2020/9/9 14:01
     * @author youhan
     */
    public static boolean isnumber(string s) {
        if (stringutils.isblank(s)) {
            return false;
        }

        return s.matches(number_regex);
    }

    /**
     * 十进制转十六进制
     *
     * @param n 十进制数
     * @return java.lang.string
     * @date 2019/4/8 09:22
     * @author youhan
     */
    public static string inttohex(integer n) {
        if (null == n) {
            return null;
        }

        return string.format("%x", n);
    }

    /**
     * 十进制转十六进制
     *
     * @param n 十进制数
     * @return java.lang.string
     * @date 2019/4/8 09:22
     * @author youhan
     */
    public static string longtohex(long n) {
        if (null == n) {
            return null;
        }

        return string.format("%x", n);
    }

    /**
     * 十进制转十六进制
     *
     * @param n
     * @param length
     * @return java.lang.string
     * @date 2019-08-12 09:56
     * @author youhan
     */
    public static string inttohexprefix(integer n, integer length) {
        if (null == n) {
            return null;
        }
        if (null == length || length <= 0) {
            return null;
        }

        string result = string.format("%x", n);
        if (result.length() < length) {
            result = youstringutil.appendprefixcontent(result, "0", length - result.length());
        }

        return result;
    }

    /**
     * 十进制转十六进制
     *
     * @param n
     * @param length
     * @return java.lang.string
     * @date 2019-08-12 09:56
     * @author youhan
     */
    public static string longtohexprefix(long n, integer length) {
        if (null == n) {
            return null;
        }
        if (null == length || length <= 0) {
            return null;
        }

        string result = string.format("%x", n);
        if (result.length() < length) {
            result = youstringutil.appendprefixcontent(result, "0", length - result.length());
        }

        return result;
    }

    /**
     * 十进制转十六进制
     *
     * @param n 十进制数
     * @return java.lang.string
     * @date 2019/4/8 09:22
     * @author youhan
     */
    public static string inttohexsuffix(integer n, integer length) {
        if (null == n) {
            return null;
        }
        if (null == length || length <= 0) {
            return null;
        }

        string result = string.format("%x", n);
        if (result.length() < length) {
            result = youstringutil.appendsuffixcontent(result, "0", length - result.length());
        }

        return result;
    }

    /**
     * 十进制转十六进制
     *
     * @param n 十进制数
     * @return java.lang.string
     * @date 2019/4/8 09:22
     * @author youhan
     */
    public static string longtohexsuffix(long n, integer length) {
        if (null == n) {
            return null;
        }
        if (null == length || length <= 0) {
            return null;
        }

        string result = string.format("%x", n);
        if (result.length() < length) {
            result = youstringutil.appendsuffixcontent(result, "0", length - result.length());
        }

        return result;
    }

    /**
     * 十六进制转十进制
     *
     * @param hex
     * @return java.lang.integer
     * @date 2019/4/8 09:49
     * @author youhan
     */
    public static integer hextoint(string hex) {
        long n = hextolong(hex);
        if (null == n) {
            return null;
        }

        // 超出整数最大值,不予处理
        if (integer.max_value < n) {
            return null;
        }

        return integer.valueof(string.valueof(n));
    }

    /**
     * 十六进制转十进制
     *
     * @param hex
     * @return java.lang.integer
     * @date 2019/4/8 09:49
     * @author youhan
     */
    public static long hextolong(string hex) {
        if (stringutils.isblank(hex)) {
            return null;
        }

        // 去除前缀为 0 的 十六进制
        if (hex.length() > 1 && hex.startswith("0")) {
            hex = hex.substring(1);
        }

        return long.valueof(hex, 16);
    }

    /**
     * 字符串转十六进制
     *
     * @param s
     * @return
     */
    public static string stringtohex(string s) {
        char[] chars = "0123456789abcdef".tochararray();
        stringbuilder sb = new stringbuilder("");
        byte[] bs = s.getbytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
        }
        return sb.tostring().trim();
    }

    /**
     * 十六进制转字符串
     *
     * @param s
     * @return
     */
    public static string hextostring(string s) {
        string str = "0123456789abcdef";
        char[] hexs = s.tochararray();
        byte[] bytes = new byte[s.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexof(hexs[2 * i]) * 16;
            n += str.indexof(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }

        return new string(bytes);
    }

    /**
     * 去除末尾多余的 0
     *
     * @param s
     * @return java.lang.string
     * @author youhan
     * @date 2021/7/2 15:39
     */
    public static string striptrailingzeros(string s) {
        if (stringutils.isblank(s)) {
            return "0";
        }

        if (!isnumber(s)) {
            return "0";
        }

        if (!s.contains(".")) {
            return s;
        }

        while (s.endswith("0")) {
            s = s.substring(0, s.length() - 1);
        }
        if (s.endswith(".")) {
            s = s.substring(0, s.length() - 1);
        }

        return s;
    }

    /**
     * int 转 string
     * 1024以内高效,超出后,正常转换
     */
    static int cachesize = 1024;
    static string[] caches = new string[cachesize];

    static {
        for (int i = 0; i < cachesize; i++) {
            caches[i] = string.valueof(i);
        }
    }

    public static string int2string(int data) {
        if (data < cachesize) {
            return caches[data];
        }
        return string.valueof(data);
    }

    /**
     * 获取几位的 int 随机数
     *
     * @param length
     * @return int
     * @author youhan
     * @date 2021/12/19
     */
    public static int getrandomint(int length) {
        return (int) ((math.random() * 9 + 1) * 10 * length);
    }

    /**
     * 获取几位的 long 随机数
     *
     * @param length
     * @return long
     * @author youhan
     * @date 2021/12/19
     */
    public static long getrandomlong(long length) {
        return (long) ((math.random() * 9 + 1) * 10 * length);
    }

    /**
     * 获取随机数
     *
     * @param
     * @return java.client.concurrent.threadlocalrandom
     * @author youhan
     * @date 2021/6/3 10:29
     */
    public static threadlocalrandom getrandom() {
        return threadlocalrandom.current();
    }

    /**
     * 获取缓存穿透时间(单位秒),最长不超过 5 分钟
     *
     * @param
     * @return java.lang.long
     * @date 2021/4/26 9:50
     * @author youhan
     */
    public static long getcachepenetrationtime() {
        return long.valueof(int2string(getrandom().nextint(300)));
    }

    /**
     * 获取数据库缓存时间(单位秒),最长不超过 1 小时
     *
     * @param
     * @return java.lang.long
     * @date 2021/4/26 9:50
     * @author youhan
     */
    public static long getdbcachetime() {
        return long.valueof(int2string(getrandom().nextint(3600)));
    }

    /**
     * 十六进制高低位转换
     *
     * @param hexstring
     * @return java.lang.string
     * @author youhan
     * @date 2021/12/11
     */
    public static string hexhighlowpositionconvert(string hexstring) {
        if (stringutils.isblank(hexstring) || hexstring.length() % 2 != 0) {
            return null;
        }

        stringbuilder result = new stringbuilder();
        for (int i = hexstring.length() - 2; i >= 0; i = i - 2) {
            result.append(hexstring.substring(i, i + 2));
        }

        return result.tostring();
    }

    public static void main(string[] args) {
        system.out.println(long.max_value);
    }
}
  • 上业务代码

controller

/**
	 * 调用统一下单接口,并组装生成支付所需参数对象.
	 *
	 * @param orderinfovo 统一下单请求参数
	 */
	@operation(summary = "调用统一下单接口")
	@postmapping("/unifiedorder")
	public ajaxresult unifiedorder(httpservletrequest request, @requestbody orderinfovo orderinfovo) {
		return orderinfoservice.unifiedorder(request, orderinfovo);
	}

service

ajaxresult unifiedorder(httpservletrequest request, orderinfovo orderinfovo);

serviceimpl

	@override
    public ajaxresult unifiedorder(httpservletrequest request, orderinfovo orderinfovo) {
		//根据typeid查询支付金额  根据自己的业务逻辑自行处理
        sysfunctiontype sysfunctiontype = sysfunctiontypemapper.selectfunctiontypebyid(orderinfovo.gettypeid());
        //通过customid 查询用户信息  根据自己的业务逻辑自行处理
        syscustom syscustom = syscustommapper.selectsyscustombyid(orderinfovo.getcustomid());
        //根据自己的业务逻辑自行处理 orderinfo为我自己业务中的实体类
        orderinfo orderinfo = new orderinfo();
        orderinfo.setid(orderinfovo.getorderid());
        //支付类型
        orderinfo.setpaymenttype(orderinfovo.getpaytype());
        //交易类型
        orderinfo.settradetype("native");
        //支付金额(bigdecimal 例子:10.00)
        orderinfo.setpaymentprice(sysfunctiontype.getprice());
        orderinfo.setname(syscustom.getname()+"体检报告");
        string body = orderinfo.getname();
        body = body.length() > 40 ? body.substring(0,39) : body;
        //更新编号防止不同终端微信报重复订单号
        orderinfo.setorderno(idutil.getsnowflake(0,0).nextidstr());
        //公众号
        req.put("appid", payconfig.getappid());
        // 商户号
        req.put("mch_id", payconfig.getmchid());
        // 32位随机字符串
        req.put("nonce_str", wxpayutil.generatenoncestr());
        // 商品描述
        req.put("body", body); 
        // 商户订单号
        req.put("out_trade_no", orderinfo.getorderno());
        // 标价金额(分)
        req.put("total_fee", string.valueof(moneyutils.yuantofen(string.valueof(orderinfo.getpaymentprice()))));
        // 终端ip
        req.put("spbill_create_ip", request.getremoteaddr());
        // 回调地址+携带的返回参数  domain 为配置的域名[不可为ip地址]
        req.put("notify_url", domain+"/system/order/info/notify-order-wx"+"/"+sysdevice.gettenantid()+"/"+orderinfo.getid()+"/"+orderinfovo.gettypeid());  
        // 交易类型
        req.put("trade_type", "native");
        // 签名
        req.put("attach", string.valueof(orderinfo.gettenantid()));
            try {
            	// 签名
                req.put("sign", wxpayutil.generatesignature(req, payconfig.getmchkey(), wxpayconstants.signtype.md5));  
                string xmlbody = wxpayutil.generatesignedxml(req, payconfig.getmchkey());
                system.err.println(string.format("微信支付预下单请求 xml 格式:\n%s", xmlbody));
                string result = wxchatpaycommonutil.httpsrequest(wechatpayurl.uifiedorder, "post", xmlbody);
                this.updateorderinfo(orderinfo);
                system.err.println(string.format("%s", result));
                map<string, string> wxresultmap = wxpayutil.xmltomap(result);
                wxresultmap.put("orderno",orderinfo.getorderno());
                if (objectutil.isnotempty(wxresultmap.get("return_code")) && wxresultmap.get("return_code").equals("success")) {
                    if (wxresultmap.get("result_code").equals("success")) {
                        system.out.println("预下单成功");
                        system.out.println("qrcode:"+wxresultmap.get("code_url"));
                        return ajaxresult.success(wxresultmap);
                    }
                }
            } catch (exception e) {
                throw new runtimeexception(e);
            }
	}

参数疑惑解释:
​notify_url:此参数为回调通知地址(公网必须可以访问),当这笔订单用户支付成功之后,”微信“会异步请求你这个地址告诉你 某个订单支付成功了。后面会讲到这个怎么写这个接口 包括如何在本地环境进行测试。

完成上面的代码,简单的一个支付后端接口实现就完成了。

3:题外篇 回调地址

异步回调通知官方文档:https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_7&index=8

简单来说就是:

在一笔订单支付成功之后微信会告诉你的服务器这笔订单支付成功了,然后你就需要根据你的项目业务逻辑进行处理,改变数据库的支付结果,然后发货。所以你需要写一个接口放到你们项目中,让微信来调用你的接口就行了。

回调的接口地址必须是公网可以进行访问的,如果开发中您的项目公网没有办法访问的话,微信是无法调用的。所以我们需要弄一个内网穿透 花生壳:https://hsk.oray.com/(免费)

这个时候把域名地址配置到 application.yml

company:
  domain: https://33q716k372.imdo.co

4.回调方法

controller

/**
	 * 支付回调(微信)
	 *
	 * @param xmldata  微信xml数据
	 * @param tenantid 商家id
	 * @param orderid  订单id
	 * @param typeid   类型id
	 * @return 返回支付结果
	 */
	@operation(summary = "支付回调(微信)")
	@postmapping("/notify-order-wx/{tenantid}/{orderid}/{typeid}")
	public string notifyorderwx(httpservletrequest request, httpservletresponse response,
								@requestbody string xmldata, @pathvariable("tenantid") long tenantid,
								@pathvariable("orderid") long orderid,
								@pathvariable("typeid") long typeid) throws ioexception {
		log.info("支付回调(微信):" + xmldata);
		if(tenantid == null || orderid == null || typeid == null){
			system.out.println("验签失败");
			response.getwriter().write("<xml><return_code><![cdata[fail]]></return_code></xml>");
		}
		string resxml = "";
		try {
			//通过商家id查询支付配置
			payconfig payconfig = payconfigservice.selectpayconfigbytenantid(tenantid,"1");
			map<string, object> resultmap = orderinfoservice.wechatpaycallback(xmldata, payconfig.getmchkey());
			map<string, string> wxresultmapdata = new hashmap<>();
			if (resultmap.get("verify").equals("yes")) {
				//验签成功
				system.out.println("验签成功");
				wxresultmapdata = (map<string, string>) resultmap.get("data");
				system.out.println("wxresultmapdata:" + jsonutil.tojsonstr(wxresultmapdata));
				log.info("收到微信回调:{}", jsonutil.tojsonstr(wxresultmapdata));
				orderinfo orderinfo = orderinfoservice.selectorderinfobyorderno(wxresultmapdata.get("out_trade_no"));
				system.out.println("通知微信验签成功");
				//自信业务逻辑处理
				orderinfoservice.notifyorder(orderinfo,tenantid,orderid,typeid,wxresultmapdata);
				resxml = string.valueof(resultmap.get("returnwechat"));
			} else if (resultmap.get("verify").equals("no")) {
				resxml = "<xml>" + "<return_code><![cdata[fail]]></return_code>" + "<return_msg><![cdata[" + wxresultmapdata.get("err_code_des") + "]]></return_msg>" + "</xml> ";
			}
		}catch (exception e) {
			throw new runtimeexception(e);
		}finally {
			bufferedoutputstream out = new bufferedoutputstream(response.getoutputstream());
			out.write(resxml.getbytes());
			out.flush();
			out.close();
		}
		return wxpaynotifyresponse.success("成功");
	}

service

public map<string, object> wechatpaycallback(string xmldata, string apikey);

serviceimpl

@override
    public map<string, object> wechatpaycallback(string xmldata, string apikey) {
        map<string, object> resultmap = new hashmap<string, object>();
        //解析到微信返回过来的xml数据
        try {
            //xml转map
            map<string, string> wxresultmap = wxpayutil.xmltomap(xmldata);
            //验证签名
            boolean signstatus = wxpayutil.issignaturevalid(wxresultmap, apikey);
            if (signstatus) {
                //验证成功
                //要返回给微信的xml数据
                string returnwechat = wxchatpaycommonutil.setreturnxml("success", "ok");
                resultmap.put("verify", "yes");
                resultmap.put("returnwechat", returnwechat);
                resultmap.put("data", wxresultmap);
            } else {
                //验证失败(表示可能接口被他人调用  需要留意)
                resultmap.put("verify", "no");
                resultmap.put("msg", "验签失败。");
            }
            return resultmap;
        } catch (ioexception e) {
            throw new runtimeexception(e);
        } catch (exception e) {
            throw new runtimeexception(e);
        }
    }

总结 

到此这篇关于java接入微信支付的文章就介绍到这了,更多相关java接入微信支付内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com