一、具体业务流程
1. 用户下单
- 前端操作:
- 用户在应用中选择商品、填写订单信息(如地址、联系方式等),并点击“下单”按钮。
- 前端将订单信息(商品id、数量、价格等)发送到后端。
- 后端处理:
- 接收到订单请求后,生成唯一的订单号(`out_trade_no`)。
- 将订单信息存储到数据库中,设置订单状态为“待支付”。
2. 后端创建订单
- 构建请求参数:
- 使用商户号、应用id、随机字符串、订单描述、商户订单号、金额(单位:分)、ip 地址等构建 xml 格式的请求数据。
- 发送请求:
- 使用 http post 方法将请求数据发送到微信的统一下单 api(`https://api.mch.weixin.qq.com/pay/unifiedorder`)。
- 处理响应:
- 接收微信返回的响应数据(xml 格式),解析响应内容。
- 检查返回的 `return_code` 和 `result_code`,确保请求成功。
- 获取 `prepay_id`,并根据它生成支付签名等信息。
3. 返回支付信息
- 返回给前端:
- 将 `prepay_id` 和其他必要参数(如时间戳、随机字符串、签名等)封装成 json 响应返回给前端。
- 前端支付:
- 前端使用微信支付 sdk,调用支付接口启动支付流程。
- 用户确认支付后,微信客户端处理支付。
4. 用户确认支付
- 用户行为:
- 用户在微信中查看支付信息,确认后进行支付。
- 支付结果:
- 微信处理支付请求,完成后将结果异步通知你的服务器。
5. 微信支付回调
- 回调 url 配置:
- 在微信商户平台配置你的回调 url(如 `https://yourdomain.com/wechat/notify`)。
- 处理回调请求:
- 接收到来自微信的 post 请求,读取请求体中的 xml 数据。
- 验证签名:
- 提取回调数据中的签名字段,使用相同的参数生成新的签名,与返回的签名进行比较,确保数据的完整性和有效性。
- 更新订单状态:
- 根据回调数据中的 `result_code` 更新数据库中的订单状态。如果支付成功,修改订单状态为“已支付”,并进行相应的业务处理(如发货)。
- 返回处理结果:
- 向微信返回处理结果,通常是 `<xml><return_code>success</return_code></xml>`。
6. 返回处理结果
- 响应微信:
- 确保响应格式正确,避免微信因无法解析而重发通知。
7. 订单状态查询(可选)
- 查询订单状态:
- 在用户支付后的一段时间内,可以调用微信的订单查询 api(`https://api.mch.weixin.qq.com/pay/orderquery`)来确认订单的状态。
- 处理结果:
- 根据查询结果更新本地订单状态,确保数据一致性。
8. 订单完成
- 后续处理:
- 一旦订单支付成功并发货,可以根据业务需求进行后续操作,例如发送确认邮件、更新库存等。
二、代码具体实现
1. 商户参数配置
在 application.properties 中配置微信支付的相关参数:
# 微信支付配置 wechat.pay.appid=your_app_id wechat.pay.mchid=your_mch_id wechat.pay.apikey=your_api_key wechat.pay.notifyurl=https://yourdomain.com/wechat/notify
2. 创建 spring boot 项目
确保你的项目引入了必要的依赖。在 pom.xml 中添加以下内容:
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>
<dependency>
<groupid>org.apache.httpcomponents</groupid>
<artifactid>httpclient</artifactid>
</dependency>
<dependency>
<groupid>com.thoughtworks.xstream</groupid>
<artifactid>xstream</artifactid>
<version>1.4.18</version>
</dependency>3. 创建微信支付服务类
创建一个服务类 wechatpayservice,用于处理订单的创建和签名等操作。
import org.apache.http.client.methods.httppost;
import org.apache.http.entity.stringentity;
import org.apache.http.impl.client.closeablehttpclient;
import org.apache.http.impl.client.httpclients;
import org.apache.http.util.entityutils;
import org.springframework.beans.factory.annotation.value;
import org.springframework.stereotype.service;
import java.util.hashmap;
import java.util.map;
@service
public class wechatpayservice {
@value("${wechat.pay.appid}")
private string appid;
@value("${wechat.pay.mchid}")
private string mchid;
@value("${wechat.pay.apikey}")
private string apikey;
@value("${wechat.pay.notifyurl}")
private string notifyurl;
private static final string unified_order_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
public string createorder(string orderno, double amount) throws exception {
string noncestr = string.valueof(system.currenttimemillis());
string xmldata = "<xml>"
+ "<appid>" + appid + "</appid>"
+ "<mch_id>" + mchid + "</mch_id>"
+ "<nonce_str>" + noncestr + "</nonce_str>"
+ "<body>product description</body>"
+ "<out_trade_no>" + orderno + "</out_trade_no>"
+ "<total_fee>" + (int) (amount * 100) + "</total_fee>"
+ "<spbill_create_ip>127.0.0.1</spbill_create_ip>"
+ "<notify_url>" + notifyurl + "</notify_url>"
+ "<trade_type>app</trade_type>"
+ "</xml>";
// 生成签名并添加到请求数据
string sign = wechatpayutil.generatesign(xmldata, apikey);
xmldata = xmldata.replace("</xml>", "<sign>" + sign + "</sign></xml>");
try (closeablehttpclient client = httpclients.createdefault()) {
httppost post = new httppost(unified_order_url);
post.setentity(new stringentity(xmldata, "utf-8"));
post.setheader("content-type", "text/xml");
string response = entityutils.tostring(client.execute(post).getentity(), "utf-8");
return response; // 解析并返回需要的信息
}
}
}4. 创建微信支付控制器
创建一个控制器 wechatpaycontroller,处理用户的下单请求(@postmapping("/createorder"))和回调@postmapping("/notify")。
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.httpservletrequest;
@restcontroller
@requestmapping("/wechat")
public class wechatpaycontroller {
@autowired
private wechatpayservice wechatpayservice;
@postmapping("/createorder")
public string createorder(@requestparam string orderno, @requestparam double amount) {
try {
return wechatpayservice.createorder(orderno, amount);
} catch (exception e) {
e.printstacktrace();
return "error creating order";
}
}
@postmapping("/notify")
public string handlecallback(httpservletrequest request) {
stringbuilder sb = new stringbuilder();
try (bufferedreader reader = new bufferedreader(new inputstreamreader(request.getinputstream()))) {
string line;
while ((line = reader.readline()) != null) {
sb.append(line);
}
} catch (ioexception e) {
e.printstacktrace();
}
string xmldata = sb.tostring();
map<string, string> data = wechatpayutil.parsexml(xmldata); // 解析 xml 数据
// 验证签名
string sign = data.get("sign");
if (wechatpayutil.generatesign(xmldata, apikey).equals(sign)) {
// 处理业务逻辑,例如更新订单状态
string resultcode = data.get("result_code");
if ("success".equals(resultcode)) {
string orderno = data.get("out_trade_no");
// 更新订单状态为已支付
// updateorderstatus(orderno, "paid");
}
return "<xml><return_code>success</return_code></xml>";
} else {
return "<xml><return_code>fail</return_code></xml>";
}
}
}5. 签名和 xml 处理工具类
创建一个工具类 wechatpayutil,负责签名和 xml 解析。
import com.thoughtworks.xstream.xstream;
import java.security.messagedigest;
import java.util.hashmap;
import java.util.map;
import java.util.treemap;
public class wechatpayutil {
public static string generatesign(string xmldata, string apikey) {
// 将 xml 转换为 map
map<string, string> data = parsexml(xmldata);
treemap<string, string> sortedmap = new treemap<>(data);
stringbuilder stringbuilder = new stringbuilder();
for (map.entry<string, string> entry : sortedmap.entryset()) {
if (!entry.getkey().equals("sign") && entry.getvalue() != null) {
stringbuilder.append(entry.getkey()).append("=").append(entry.getvalue()).append("&");
}
}
stringbuilder.append("key=").append(apikey);
return md5(stringbuilder.tostring()).touppercase();
}
public static string md5(string input) {
try {
messagedigest md = messagedigest.getinstance("md5");
byte[] digest = md.digest(input.getbytes());
stringbuilder hexstring = new stringbuilder();
for (byte b : digest) {
string hex = integer.tohexstring(0xff & b);
if (hex.length() == 1) hexstring.append('0');
hexstring.append(hex);
}
return hexstring.tostring();
} catch (exception e) {
throw new runtimeexception(e);
}
}
public static map<string, string> parsexml(string xml) {
// 使用 xstream 解析 xml
xstream xstream = new xstream();
xstream.alias("xml", hashmap.class);
return (map<string, string>) xstream.fromxml(xml);
}
}三、参数配置及获取
一、回调函数的配置步骤
在微信商户平台配置回调地址:
- 登录微信商户平台。
- 找到“账户设置”或“api安全”选项。
- 在“支付结果通知 url”中填写你的回调地址(如
https://yourdomain.com/wechat/notify)。
二、商户参数获取
商户参数主要包括微信支付的相关信息,这些信息可以在微信商户平台上获取。
商户参数
- appid: 公众账号id,由微信开放平台或微信支付商户平台提供。
- mchid: 商户号,由微信支付商户平台提供。
- apikey: api 密钥,在微信支付商户平台设置,用于签名请求。
- notifyurl: 支付结果通知地址,即微信支付成功后,微信服务器将异步通知该地址。
到此这篇关于springboot实现微信支付接口调用及回调函数(商户参数获取)的文章就介绍到这了,更多相关springboot微信支付接口调用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论