欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java调用微信支付功能的方法示例代码

程序员文章站 2022-07-03 17:43:51
java 使用微信支付前言百度搜了一下微信支付,都描述的不太好,于是乎打算自己写一个案例,希望以后拿来直接改造使用。因为涉及二维码的前端显示,所以有前端的内容一. 准备工作所需微信公众号信息配置 a...

java 使用微信支付

前言百度搜了一下微信支付,都描述的不太好,于是乎打算自己写一个案例,希望以后拿来直接改造使用。
因为涉及二维码的前端显示,所以有前端的内容

一. 准备工作

所需微信公众号信息配置

  • appid:绑定支付的appid(必须配置)
  • mchid:商户号(必须配置)
  • key:商户支付密钥,参考开户邮件设置(必须配置)
  • appsecret:公众帐号secert(仅jsapi支付的时候需要配置)

我这个案例用的是尚硅谷一位老师提供的,这里不方便提供出来,需要大家自己找,或者公司提供

二. 构建项目架构

1.新建maven项目

Java调用微信支付功能的方法示例代码

2.导入依赖

<parent>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-parent</artifactid>
  <version>2.2.1.release</version>
 </parent>
 <dependencies>
  <!--spring boot -->
  <dependency>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-starter-web</artifactid>
  </dependency>
  <!--微信提供的sdk-->
  <dependency>
   <groupid>com.github.wxpay</groupid>
   <artifactid>wxpay-sdk</artifactid>
   <version>0.0.3</version>
  </dependency>
  <!--发送http请求-->
  <dependency>
   <groupid>org.apache.httpcomponents</groupid>
   <artifactid>httpclient</artifactid>
  </dependency>
  <!--模板引擎-->
  <dependency>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-starter-freemarker</artifactid>
  </dependency>
 </dependencies>

Java调用微信支付功能的方法示例代码

依赖中需要注意的是我导入了微信提供的sdk,以及freemarker模板引擎

3.编写配置文件application.properties

# 服务端口
server.port=8081
# 微信开放平台 appid
wx.pay.app_id=
#商户号
wx.pay.partner=
#商户key
wx.pay.partnerkey=
#回调地址
wx.pay.notifyurl:

spring.freemarker.tempalte-loader-path=classpath:/templates
#  关闭缓存,及时刷新,上线生产环境需要修改为true
spring.freemarker.cache=false
spring.freemarker.charset=utf-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl
spring.mvc.static-path-pattern: /static/**

Java调用微信支付功能的方法示例代码

4.编写启动类

@springbootapplication
@componentscan(basepackages = {"com.haiyang.wxpay"})
public class application {

 public static void main(string[] args) {
  springapplication.run(application.class, args);
 }
}

Java调用微信支付功能的方法示例代码

5.创建常用包controller,service,impl,utils

Java调用微信支付功能的方法示例代码

6.创建两个前端需要的文件夹 static和templates

Java调用微信支付功能的方法示例代码

三. 代码实现

1. 创建工具类读取配置文件的参数

@component
public class wxpayutils implements initializingbean {

 @value("${wx.pay.app_id}")
 private string appid;

 @value("${wx.pay.partner}")
 private string partner;

 @value("${wx.pay.partnerkey}")
 private string partnerkey;
 @value("${wx.pay.notifyurl}")
 private string notifyurl;


 public static string wx_pay_app_id;
 public static string wx_pay_partner;
 public static string wx_pay_partner_key;
 public static string wx_open_notify_url;

 @override
 public void afterpropertiesset() throws exception {
  wx_pay_app_id = appid;
  wx_pay_partner = partner;
  wx_pay_partner_key = partnerkey;
  wx_open_notify_url = notifyurl;
 }

}

Java调用微信支付功能的方法示例代码

2. 构建工具类发送http请求

/**
 * http请求客户端
 * 
 * @author qy
 * 
 */
public class httpclient {
	private string url;
	private map<string, string> param;
	private int statuscode;
	private string content;
	private string xmlparam;
	private boolean ishttps;

	public boolean ishttps() {
		return ishttps;
	}

	public void sethttps(boolean ishttps) {
		this.ishttps = ishttps;
	}

	public string getxmlparam() {
		return xmlparam;
	}

	public void setxmlparam(string xmlparam) {
		this.xmlparam = xmlparam;
	}

	public httpclient(string url, map<string, string> param) {
		this.url = url;
		this.param = param;
	}

	public httpclient(string url) {
		this.url = url;
	}

	public void setparameter(map<string, string> map) {
		param = map;
	}

	public void addparameter(string key, string value) {
		if (param == null)
			param = new hashmap<string, string>();
		param.put(key, value);
	}

	public void post() throws clientprotocolexception, ioexception {
		httppost http = new httppost(url);
		setentity(http);
		execute(http);
	}

	public void put() throws clientprotocolexception, ioexception {
		httpput http = new httpput(url);
		setentity(http);
		execute(http);
	}

	public void get() throws clientprotocolexception, ioexception {
		if (param != null) {
			stringbuilder url = new stringbuilder(this.url);
			boolean isfirst = true;
			for (string key : param.keyset()) {
				if (isfirst)
					url.append("?");
				else
					url.append("&");
				url.append(key).append("=").append(param.get(key));
			}
			this.url = url.tostring();
		}
		httpget http = new httpget(url);
		execute(http);
	}

	/**
	 * set http post,put param
	 */
	private void setentity(httpentityenclosingrequestbase http) {
		if (param != null) {
			list<namevaluepair> nvps = new linkedlist<namevaluepair>();
			for (string key : param.keyset())
				nvps.add(new basicnamevaluepair(key, param.get(key))); // 参数
			http.setentity(new urlencodedformentity(nvps, consts.utf_8)); // 设置参数
		}
		if (xmlparam != null) {
			http.setentity(new stringentity(xmlparam, consts.utf_8));
		}
	}

	private void execute(httpurirequest http) throws clientprotocolexception,
			ioexception {
		closeablehttpclient httpclient = null;
		try {
			if (ishttps) {
				sslcontext sslcontext = new sslcontextbuilder()
						.loadtrustmaterial(null, new truststrategy() {
							// 信任所有
							public boolean istrusted(x509certificate[] chain,
									string authtype)
									throws certificateexception {
								return true;
							}
						}).build();
				sslconnectionsocketfactory sslsf = new sslconnectionsocketfactory(
						sslcontext);
				httpclient = httpclients.custom().setsslsocketfactory(sslsf)
						.build();
			} else {
				httpclient = httpclients.createdefault();
			}
			closeablehttpresponse response = httpclient.execute(http);
			try {
				if (response != null) {
					if (response.getstatusline() != null)
						statuscode = response.getstatusline().getstatuscode();
					httpentity entity = response.getentity();
					// 响应内容
					content = entityutils.tostring(entity, consts.utf_8);
				}
			} finally {
				response.close();
			}
		} catch (exception e) {
			e.printstacktrace();
		} finally {
			httpclient.close();
		}
	}

	public int getstatuscode() {
		return statuscode;
	}

	public string getcontent() throws parseexception, ioexception {
		return content;
	}

}

额~有点长就不放图片了 代码都一样

3. 新建controller

@controller
@requestmapping("/wxpay")
public class wxpaycontroller {
 @requestmapping("/pay")
 public string createpayqrcode(model model) throws exception{

  string price = "0.01";
  string no = getorderno();
  map m = new hashmap();
  m.put("appid", wxpayutils.wx_pay_app_id);
  m.put("mch_id", wxpayutils.wx_pay_partner);
  m.put("nonce_str", wxpayutil.generatenoncestr());
  m.put("body","微信支付测试"); //主体信息
  m.put("out_trade_no", no); //订单唯一标识
  m.put("total_fee", getmoney(price));//金额
  m.put("spbill_create_ip", "127.0.0.1");//项目的域名
  m.put("notify_url", wxpayutils.wx_open_notify_url);//回调地址
  m.put("trade_type", "native");//生成二维码的类型

  //3 发送httpclient请求,传递参数xml格式,微信支付提供的固定的地址
  httpclient client = new httpclient("https://api.mch.weixin.qq.com/pay/unifiedorder");
  //设置xml格式的参数
  //把xml格式的数据加密
  client.setxmlparam(wxpayutil.generatesignedxml(m, wxpayutils.wx_pay_partner_key));
  client.sethttps(true);
  //执行post请求发送
  client.post();
  //4 得到发送请求返回结果
  //返回内容,是使用xml格式返回
  string xml = client.getcontent();
  //把xml格式转换map集合,把map集合返回
  map<string,string> resultmap = wxpayutil.xmltomap(xml);
  //最终返回数据 的封装
  map map = new hashmap();
  map.put("no", no);
  map.put("price", price);
  map.put("result_code", resultmap.get("result_code"));
  map.put("code_url", resultmap.get("code_url"));

  model.addattribute("map",map);
  return "pay";

 }

 @getmapping("queryorder/{no}")
 @responsebody
 public string querypaystatus(@pathvariable string no) throws exception{
  //1、封装参数
  map m = new hashmap<>();
  m.put("appid", wxpayutils.wx_pay_app_id);
  m.put("mch_id", wxpayutils.wx_pay_partner);
  m.put("out_trade_no", no);
  m.put("nonce_str", wxpayutil.generatenoncestr());

  //2 发送httpclient
  httpclient client = new httpclient("https://api.mch.weixin.qq.com/pay/orderquery");
  client.setxmlparam(wxpayutil.generatesignedxml(m, wxpayutils.wx_pay_partner_key));
  client.sethttps(true);
  client.post();

  //3.得到订单数据
  string xml = client.getcontent();
  map<string, string> resultmap = wxpayutil.xmltomap(xml);

  //4.判断是否支付成功
  if(resultmap.get("trade_state").equals("success")) {
   /*
     改变数据库中的数据等操作
    */
   return "支付成功";
  }
  return "支付中";
 }

 @getmapping("success")
 public string success(){
  return "success";
 }
 @requestmapping("test")
 public string test(){
  return "pay";
 }
 /**
  * 生成订单号
  * @return
  */
 public static string getorderno() {
  simpledateformat sdf = new simpledateformat("yyyymmddhhmmss");
  string newdate = sdf.format(new date());
  string result = "";
  random random = new random();
  for (int i = 0; i < 3; i++) {
   result += random.nextint(10);
  }
  return newdate + result;
 }
 /**
  * 元转换成分
  * @param amount
  * @return
  */
 public static string getmoney(string amount) {
  if(amount==null){
   return "";
  }
  // 金额转化为分为单位
  // 处理包含, ¥ 或者$的金额
  string currency = amount.replaceall("\\$|\\¥|\\,", "");
  int index = currency.indexof(".");
  int length = currency.length();
  long amlong = 0l;
  if(index == -1){
   amlong = long.valueof(currency+"00");
  }else if(length - index >= 3){
   amlong = long.valueof((currency.substring(0, index+3)).replace(".", ""));
  }else if(length - index == 2){
   amlong = long.valueof((currency.substring(0, index+2)).replace(".", "")+0);
  }else{
   amlong = long.valueof((currency.substring(0, index+1)).replace(".", "")+"00");
  }
  return amlong.tostring();
 }
}

Java调用微信支付功能的方法示例代码
Java调用微信支付功能的方法示例代码
Java调用微信支付功能的方法示例代码
Java调用微信支付功能的方法示例代码
Java调用微信支付功能的方法示例代码

值得一提的是 这里我们用的是controller而不是restcontroller,因为我们需要展示二维码

4. 在templates文件中新建 订单支付页面(二维码生成的页面)

注意:文件名必须和生成二维码方法中返回的字符串名称一样 我这里叫 pay

先新建html页面,然后再将后缀改成ftl(freemarker模板引擎的后缀名)

<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>title</title>
 <script src="/static/qrcode.js"></script>
 <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>
<center>
 <div id="qrcode"></div>
</center>
<script type="text/javascript">
 new qrcode(document.getelementbyid("qrcode"), "${map.code_url}"); // 设置要生成二维码的链接
</script>
<script type="text/javascript">
 var int=self.setinterval("querystatus()",3000);
 function querystatus() {
  $.get("/wxpay/queryorder/${map.no}",function(data,status){
   if (data==="支付中"){
    console.log("支付中");
   } else {
    clearinterval(int)
    window.location.href="/wxpay/success" rel="external nofollow" 
   }
  })
 }
</script>
</body>
</html>

Java调用微信支付功能的方法示例代码

再创建支付成功跳转的页面 文件名要与支付成功方法返回的文件名一样

<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>title</title>
</head>
<body>
<h1>支付成功</h1>
</body>
</html>

Java调用微信支付功能的方法示例代码

引入 qrcode 生成二维码的依赖,放入static文件中
这里我提供下载链接
链接: https://pan.baidu.com/s/15-e3kprcenaewh0zablnjq 提取码: xhs9 复制这段内容后打开百度网盘手机app,操作更方便哦

引入完成后

Java调用微信支付功能的方法示例代码

最后 我们启动项目来测试一下

浏览器输入地址
http://localhost:8081/wxpay/pay
发现二维码生成成功,并且定时器也没问题

Java调用微信支付功能的方法示例代码

之后我们扫码支付
成功跳转到支付成功页面 ~nice

Java调用微信支付功能的方法示例代码

四. 总结

  • 首先就是生成二维码,需要的几个主要的参数,订单号,金额,购买的信息(主体信息),其余的参数除了一些可以不写的都是固定的
  • 生成二维码然后展示在页面上,用的qrcode插件,生成
  • 然后设置定时器,来实时查询订单是否支付
  • 查询订单信息的写法和生成二维码的方式差不多 无非就是请求时少了几个参数,必须得带上订单号
  • 微信提供的查询订单接口返回数据中 trade_state 代表支付状态 notpay没有支付,seccess表示已成功
  • 定时器检测到订单支付成功就清除定时器,并且执行支付成功之后的操作

实际项目中远没有这么简单,并且所有的数据都要从数据库中获取,在这里我为了方便把价格固定写死的

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

相关标签: Java 微信支付