龙空技术网

java实现微信支付

小杜everyday生活 141

前言:

眼前小伙伴们对“微信用户java”大约比较关注,我们都需要剖析一些“微信用户java”的相关内容。那么小编也在网络上网罗了一些对于“微信用户java””的相关内容,希望朋友们能喜欢,我们快快来了解一下吧!

以下是Java实现微信支付的代码示例:

// 导入所需的类和包

import java.util.HashMap;

import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;

import org.apache.http.client.methods.CloseableHttpResponse;

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;

public class WechatPay {

// 微信支付API密钥

private static final String API_KEY = "your_api_key";

// 统一下单接口URL

private static final String UNIFIED_ORDER_URL = ";;

public static void main(String[] args) {

String appId = "your_app_id"; // 公众账号ID或者应用APPID等

String mchId = "your_mch_id"; // 微信支付分配的商户号

String nonceStr = "123456"; // 随机字符串

String body = "test"; // 商品描述

String outTradeNo = "order_no123"; // 商户订单号

Integer totalFee = 100; // 订单总金额,单位为分

String spbillCreateIp = "192.168.0.1"; // 用户端实际ip

String notifyUrl = ";; // 支付成功后的回调地址

try {

// 生成签名

String sign = generateSign(appId, mchId, nonceStr, body, outTradeNo, totalFee, spbillCreateIp, notifyUrl);

// 组装请求参数

Map<String, Object> paramMap = new HashMap<>();

paramMap.put("appid", appId);

paramMap.put("mch_id", mchId);

paramMap.put("nonce_str", nonceStr);

paramMap.put("body", body);

paramMap.put("out_trade_no", outTradeNo);

paramMap.put("total_fee", totalFee);

paramMap.put("spbill_create_ip", spbillCreateIp);

paramMap.put("notify_url", notifyUrl);

paramMap.put("sign", sign);

// 发送请求

String xmlData = mapToXml(paramMap); // 组装XML格式的数据

CloseableHttpClient httpClient = HttpClients.createDefault();

HttpPost httpPost = new HttpPost(UNIFIED_ORDER_URL);

httpPost.setEntity(new StringEntity(xmlData, "UTF-8"));

CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

String responseXmlData = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");

// 解析响应参数

Map<String, Object> responseMap = xmlToMap(responseXmlData);

// 判断返回结果

if ("SUCCESS".equals(responseMap.get("return_code")) && "SUCCESS".equals(responseMap.get("result_code"))) {

String prepayId = (String) responseMap.get("prepay_id");

System.out.println("prepayId: " + prepayId);

} else {

String errorMsg = (String) responseMap.get("err_code_des");

System.err.println("支付失败,错误信息:" + errorMsg);

}

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 生成签名

*/

private static String generateSign(String appId, String mchId, String nonceStr, String body, String outTradeNo,

Integer totalFee, String spbillCreateIp, String notifyUrl) {

Map<String, Object> paramMap = new HashMap<>();

paramMap.put("appid", appId);

paramMap.put("mch_id", mchId);

paramMap.put("nonce_str", nonceStr);

paramMap.put("body", body);

paramMap.put("out_trade_no", outTradeNo);

paramMap.put("total_fee", totalFee);

paramMap.put("spbill_create_ip", spbillCreateIp);

paramMap.put("notify_url", notifyUrl);

// 将参数名按照ASCII码从小到大排序

StringBuilder sb = new StringBuilder();

for (String key : paramMap.keySet()) {

sb.append(key).append("=").append(paramMap.get(key)).append("&");

}

sb.append("key=").append(API_KEY);

// 生成签名

return DigestUtils.md5Hex(sb.toString()).toUpperCase();

}

/**

* 将Map转为XML字符串

*/

private static String mapToXml(Map<String, Object> paramMap) {

StringBuilder sb = new StringBuilder();

sb.append("<xml>");

for (String key : paramMap.keySet()) {

sb.append("<").append(key).append(">")

.append(paramMap.get(key))

.append("</").append(key).append(">");

}

sb.append("</xml>");

return sb.toString();

}

/**

* 将XML字符串转为Map

*/

private static Map<String, Object> xmlToMap(String xmlData) throws Exception {

Map<String, Object> resultMap = new HashMap<>();

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

InputStream inputStream = new ByteArrayInputStream(xmlData.getBytes());

org.w3c.dom.Document document = documentBuilder.parse(inputStream);

org.w3c.dom.Element rootElement = document.getDocumentElement();

NodeList nodeList = rootElement.getChildNodes();

for (int i = 0; i < nodeList.getLength(); i++) {

Node node = nodeList.item(i);

if (node.getNodeType() == Node.ELEMENT_NODE) {

org.w3c.dom.Element element = (org.w3c.dom.Element) node;

resultMap.put(element.getNodeName(), element.getTextContent());

}

}

return resultMap;

}

}

以下是完整的Java实现微信支付的代码:

// 导入所需的类和包

import java.io.ByteArrayInputStream;

import java.io.InputStream;

import java.util.HashMap;

import java.util.Map;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.codec.digest.DigestUtils;

import org.apache.http.client.methods.CloseableHttpResponse;

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.w3c.dom.Node;

import org.w3c.dom.NodeList;

public class WechatPay {

// 微信支付API密钥

private static final String API_KEY = "your_api_key";

// 统一下单接口URL

private static final String UNIFIED_ORDER_URL = ";;

/**

* 微信支付统一下单

*

* @param appId 公众账号ID或者应用APPID等

* @param mchId 微信支付分配的商户号

* @param nonceStr 随机字符串

* @param body 商品描述

* @param outTradeNo 商户订单号

* @param totalFee 订单总金额,单位为分

* @param spbillCreateIp 用户端实际ip

* @param notifyUrl 支付成功后的回调地址

* @return 返回微信支付接口的响应结果

*/

public static Map<String, Object> unifiedOrder(String appId, String mchId, String nonceStr, String body,

String outTradeNo, Integer totalFee, String spbillCreateIp, String notifyUrl) {

try {

// 生成签名

String sign = generateSign(appId, mchId, nonceStr, body, outTradeNo, totalFee, spbillCreateIp, notifyUrl);

// 组装请求参数

Map<String, Object> paramMap = new HashMap<>();

paramMap.put("appid", appId);

paramMap.put("mch_id", mchId);

paramMap.put("nonce_str", nonceStr);

paramMap.put("body", body);

paramMap.put("out_trade_no", outTradeNo);

paramMap.put("total_fee", totalFee);

paramMap.put("spbill_create_ip", spbillCreateIp);

paramMap.put("notify_url", notifyUrl);

paramMap.put("sign", sign);

// 发送请求

String xmlData = mapToXml(paramMap); // 组装XML格式的数据

CloseableHttpClient httpClient = HttpClients.createDefault();

HttpPost httpPost = new HttpPost(UNIFIED_ORDER_URL);

httpPost.setEntity(new StringEntity(xmlData, "UTF-8"));

CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

String responseXmlData = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");

// 解析响应参数

Map<String, Object> responseMap = xmlToMap(responseXmlData);

return responseMap;

} catch (Exception e) {

e.printStackTrace();

return null;

}

}

/**

* 生成签名

*/

private static String generateSign(String appId, String mchId, String nonceStr, String body, String outTradeNo,

Integer totalFee, String spbillCreateIp, String notifyUrl) {

Map<String, Object> paramMap = new HashMap<>();

paramMap.put("appid", appId);

paramMap.put("mch_id", mchId);

paramMap.put("nonce_str", nonceStr);

paramMap.put("body", body);

paramMap.put("out_trade_no", outTradeNo);

paramMap.put("total_fee", totalFee);

paramMap.put("spbill_create_ip", spbillCreateIp);

paramMap.put("notify_url", notifyUrl);

// 将参数名按照ASCII码从小到大排序

StringBuilder sb = new StringBuilder();

for (String key : paramMap.keySet()) {

sb.append(key).append("=").append(paramMap.get(key)).append("&");

}

sb.append("key=").append(API_KEY);

// 生成签名

return DigestUtils.md5Hex(sb.toString()).toUpperCase();

}

/**

* 将Map转为XML字符串

*/

private static String mapToXml(Map<String, Object> paramMap) {

StringBuilder sb = new StringBuilder();

sb.append("<xml>");

for (String key : paramMap.keySet()) {

sb.append("<").append(key).append(">")

.append(paramMap.get(key))

.append("</").append(key).append(">");

}

sb.append("</xml>");

return sb.toString();

}

/**

* 将XML字符串转为Map

*/

private static Map<String, Object> xmlToMap(String xmlData) throws Exception {

Map<String, Object> resultMap = new HashMap<>();

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

InputStream inputStream = new ByteArrayInputStream(xmlData.getBytes());

org.w3c.dom.Document document = documentBuilder.parse(inputStream);

org.w3c.dom.Element rootElement = document.getDocumentElement();

NodeList nodeList = rootElement.getChildNodes();

for (int i = 0; i < nodeList.getLength(); i++) {

Node node = nodeList.item(i);

if (node.getNodeType() == Node.ELEMENT_NODE) {

org.w3c.dom.Element element = (org.w3c.dom.Element) node;

resultMap.put(element.getNodeName(), element.getTextContent());

}

}

return resultMap;

}

}

使用方式:

// 调用微信支付统一下单接口,获取预支付交易会话标识

Map<String, Object> result = WechatPay.unifiedOrder(appId, mchId, nonceStr, body, outTradeNo, totalFee, spbillCreateIp, notifyUrl);

if ("SUCCESS".equals(result.get("return_code")) && "SUCCESS".equals(result.get("result_code"))) {

String prepayId = (String) result.get("prepay_id");

// TODO:通过prepayId调起微信支付(前端实现)

} else {

String errorMsg = (String) result.get("err_code_des");

System.err.println("支付失败,错误信息:" + errorMsg);

}

标签: #微信用户java