参考公众号支付开发者文档
我们要做的就是上图标红的部分。
理一遍流程:
1.进行js-sdk的验签流程
2.发起请求,对统一下单的传入参数进行参数签名,签名通过后,把签名也封装到参数中
3.调起微信统一下单接口,生成预订单(在公司已经申请了商户号的前提下,商户的申请配置在这里就不讲述了,自行百度。值得注意的是支付的授权目录为支付请求的上一级目录,要请求的全路径)
4.在预订单中取出prepay_id(生成预订单主要目的就是这个prepay_id,能得到prepay_id就已经成功一半了)
5.获得prepay_id后,调起微信支付 wx.chooseWXPay({});(业务逻辑根据项目需求自行处理)
6.支付成功后,回调支付成功通知,通知微信支付结果(业务逻辑根据项目需求自行处理)
具体代码实现如下:
depositPay.jsp(/wechat/jsapisign部分的验签在这里就不讲述了,在微信公众号开发之调起微信扫一扫接口中有详细介绍)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
押金支付
/wechat/paySubmit请求的详细代码,统一下单的请求和返回参数参照微信公众号支付统一下单部分
统一下单接口为:"https://api.mch.weixin.qq.com/pay/unifiedorder"
@RequestMapping(value = "/pay", method = RequestMethod.GET, produces = MEDIATYPE_CHARSET_JSON_UTF8)
public @ResponseBody String pay(HttpSession httpSession, HttpServletRequest request, String totalFee, String openId, String outTradeNo) {
String paramContent = "";
String sign = "";
String nonceStr = CheckUtil.generateNonceStr();
Map param = new HashMap<>();
param.put("appid", appId); //公众号id
param.put("mch_id", mchId);//商户平台id
param.put("device_info", "WEB");
param.put("nonce_str", nonceStr);
param.put("body", "xiaodoujieyue");//订单标题
param.put("out_trade_no", outTradeNo);//订单ID
param.put("total_fee", totalFee); //订单需要支付的金额
param.put("trade_type", "JSAPI");//交易类型 JSAPI 公众号支付 NATIVE 扫码支付 APP APP支付
param.put("notify_url", WXConstants.BASE_SERVER+"/wechat/payNotify");//notify_url 支付成功之后 微信会进行异步回调的地址
param.put("openid", openId);//微信授权获取openId
param.put("sign_type", "MD5");
String spbill_create_ip = CheckUtil.getIpAddr(request);
if (StringUtils.isEmpty(spbill_create_ip)) {
map.put("spbill_create_ip", "192.168.0.1");// 消费IP地址
} else {
map.put("spbill_create_ip", spbill_create_ip);// 消费IP地址
}
sign = CheckUtil.generateSignature(param, key, "MD5");
param.put("sign", sign);
paramContent = CheckUtil.getXMLFromMap(param);
logger.info("预订单参数信息" + paramContent);
String orderInfo = OkHttpUtil.getInstance().doPost("https://api.mch.weixin.qq.com/pay/unifiedorder", paramContent);
logger.info("生成预订单的信息xml" + orderInfo);
String prepay_id;
try {
Map orderInfoMap = CheckUtil.xmlToMap(orderInfo);
if (orderInfoMap.get("return_code").equals("SUCCESS") && orderInfoMap.get("result_code").equals("SUCCESS")) {
//预支付id
prepay_id = orderInfoMap.get("prepay_id");
String timestamp = CheckUtil.create_timestamp();
HashMap pageParam = new HashMap<>();
pageParam.put("appId", appId);
pageParam.put("nonceStr", nonceStr);
pageParam.put("package", "prepay_id=" + prepay_id);
pageParam.put("timeStamp", timestamp);
pageParam.put("signType", "MD5");
String pageSign = CheckUtil.generateSignature(pageParam, key, "MD5");
pageParam.put("paySign", pageSign);
pageParam.put("prepay_id", prepay_id);
logger.info("参与签名的参数:appId:" + appId + "nonceStr:" + nonceStr + "package:prepay_id=" + prepay_id + "timeStamp" + timestamp + "signType:MD5" + "paySign:" + pageSign);
return JSON.toJSONString(pageParam);
}
} catch (Exception e) {
logger.error("生成的预订单格式xml转map异常" + e.getMessage() + "异常原因" + e.getCause());
return null;
}
return null;
}
支付回调
@RequestMapping("/payNotify")
public synchronized String payNotify(HttpServletRequest request, HttpServletResponse response) {
Map returnData = new HashMap<>();
String returnXML = "";
String retStr = "";
try {
retStr = new String(readInput(request.getInputStream()), "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
logger.info("支付回调信息:" + retStr);
try {
Map responseResult = CheckUtil.xmlToMap(retStr);
String localSign = CheckUtil.generateSignature(responseResult, key, "MD5");
String sign = responseResult.get("sign");
String openid = responseResult.get("openid");
logger.info("签名信息:localSign-->" + localSign + "sign:-->" + sign);
if (Objects.equals(sign, localSign)) {
if (!responseResult.get("return_code").toString().equals("SUCCESS") || !responseResult.get("result_code").toString().equals("SUCCESS")) {
returnData.put("return_code", "FAIL");
returnData.put("return_msg", "return_code不正确");
} else {
//todo 你的业务逻辑
returnData.put("return_code", "SUCCESS");
returnData.put("return_msg", "ok");
}
} else {
returnData.put("return_code", "FAIL");
returnData.put("return_msg", "签名错误");
}
} catch (Exception e) {
logger.error("支付回调错误" + e.getMessage());
returnData.put("return_code", "FAIL");
returnData.put("return_msg", "支付回调失败");
returnXML = CheckUtil.getXMLFromMap(returnData);
return returnXML;
}
returnXML = CheckUtil.getXMLFromMap(returnData);
logger.info("支付回调返回的信息" + returnXML);
return returnXML;
}
public static byte[] readInput(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.close();
in.close();
return out.toByteArray();
}
用到的工具类 CheckUtil.java
public class CheckUtil {
/**
* 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。
* @param data 待签名数据
* @param key API密钥
* @param signType 签名方式
* @return 签名
*/
public static String generateSignature(final Map data, String key, SignType signType) throws Exception {
Set keySet = data.keySet();
String[] keyArray = keySet.toArray(new String[keySet.size()]);
Arrays.sort(keyArray);
StringBuilder sb = new StringBuilder();
for (String k : keyArray) {
if (k.equals(WXPayConstants.FIELD_SIGN)) {
continue;
}
if (data.get(k).trim().length() > 0) // 参数值为空,则不参与签名
sb.append(k).append("=").append(data.get(k).trim()).append("&");
}
sb.append("key=").append(key);
if (SignType.MD5.equals(signType)) {
return MD5(sb.toString()).toUpperCase();
}
else if (SignType.HMACSHA256.equals(signType)) {
return HMACSHA256(sb.toString(), key);
}
else {
throw new Exception(String.format("Invalid sign_type: %s", signType));
}
}
/**
* 通过HttpServletRequest返回IP地址
* @param request HttpServletRequest
* @return ip String
* @throws Exception
*/
public static String getIpAddr(HttpServletRequest request) throws Exception {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
public static String generateNonceStr() {
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
}
public static String getXMLFromMap(Map map) throws Exception {
StringBuffer sb = new StringBuffer();
sb.append("");
Set set = map.keySet();
Iterator it = set.iterator();
while (it.hasNext()) {
String key = it.next();
sb.append("<" + key + ">").append(map.get(key)).append("" + key + ">");
}
sb.append(" ");
return sb.toString();
}
/**
* XML格式字符串转换为Map
*
* @param strXML XML字符串
* @return XML数据转换后的Map
* @throws Exception
*/
public static Map xmlToMap(String strXML) throws Exception {
try {
Map data = new HashMap();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
org.w3c.dom.Document doc = documentBuilder.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;
}
}
public static String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
}
OkHttpUtil.java
public class OkHttpUtil {
private static OkHttpUtil okHttpUtil;
private static OkHttpClient okHttpClient;
private OkHttpUtil() {
/**
* OkHttp是一个第三方类库,
* 用于android中请求网络
* 创建OkHttpClient对象
*/
okHttpClient = new OkHttpClient();
}
public static OkHttpUtil getInstance() {
if (okHttpUtil == null) {
okHttpUtil = new OkHttpUtil();
}
return okHttpUtil;
}
public String doGet(String url) {
/**
* 请求接口
* 创建Request对象
*/
Request request = new Request.Builder()
.url(url)
.build();
//得到request对象
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String doPost(String url, Map param) {
FormBody.Builder builder = new FormBody.Builder();
for (Map.Entry entry : param.entrySet()) {
builder.add(entry.getKey(), entry.getValue());
}
RequestBody body = builder.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String doPostParam(String url, Map param) {
FormBody.Builder builder = new FormBody.Builder();
for (Map.Entry entry : param.entrySet()) {
builder.add(entry.getKey(), (String) entry.getValue());
}
RequestBody body = builder.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String doPost(String url, String param) {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, param);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}