微信支付java代码示例

微信支付是一种非常方便和流行的电子支付方式,它可以在手机端进行快速的支付操作。在Java编程中,我们可以通过调用微信支付接口来实现支付功能。下面我将为您提供一个详细的微信支付的Java代码示例。

首先,我们需要导入相关的包,包括HTTP请求库和XML解析库等:

```

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

import java.security.MessageDigest;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.HashMap;

import java.util.Map;

import java.util.Random;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

```

然后,我们定义一个微信支付工具类,包含以下几个方法:

1. 创建微信支付订单:

```java

public static String createPayOrder(String appId, String mchId, String apiKey, String body, String outTradeNo,

int totalFee, String notifyUrl, String tradeType, String openid) {

// 生成随机字符串

String nonceStr = getRandomStringByLength(32);

// 获取当前时间戳

String timeStamp = getCurrentTimestamp();

// 获取客户端ip地址

String spbillCreateIp = getClientIpAddr();

// 构建签名参数

Map params = new HashMap<>();

params.put("appid", appId);

params.put("mch_id", mchId);

params.put("nonce_str", nonceStr);

params.put("body", body);

params.put("out_trade_no", outTradeNo);

params.put("total_fee", String.valueOf(totalFee));

params.put("spbill_create_ip", spbillCreateIp);

params.put("notify_url", notifyUrl);

params.put("trade_type", tradeType);

params.put("openid", openid);

// 生成签名

String sign = getSign(params, apiKey);

// 构建XML请求体

String requestXml = ""

+ "" + appId + ""

+ "" + mchId + ""

+ "" + nonceStr + ""

+ "" + sign + ""

// 其他参数...

+ "";

// 发起HTTP请求并获取响应

String responseXml = sendHttpPostRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXml);

// 解析XML响应,获取prepay_id

String prepayId = parseXmlResponse(responseXml, "prepay_id");

return prepayId;

}

```

2. 生成随机字符串:

```java

private static String getRandomStringByLength(int length) {

String base = "abcdefghijklmnopqrstuvwxyz0123456789";

Random random = new Random();

StringBuilder sb = new StringBuilder();

for (int i = 0; i < length; i++) {

int number = random.nextInt(base.length());

sb.append(base.charAt(number));

}

return sb.toString();

}

```

3. 获取当前时间戳:

```java

private static String getCurrentTimestamp() {

long timeStamp = System.currentTimeMillis() / 1000;

return String.valueOf(timeStamp);

}

```

4. 获取客户端IP地址:

```java

private static String getClientIpAddr() {

String ip = "";

try {

URL url = new URL("http://checkip.amazonaws.com");

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");

connection.setConnectTimeout(5000);

connection.setReadTimeout(5000);

int responseCode = connection.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

ip = reader.readLine();

}

} catch (IOException e) {

e.printStackTrace();

}

return ip;

}

```

5. 生成签名:

```java

private static String getSign(Map params, String apiKey) {

StringBuilder sb = new StringBuilder();

for (Map.Entry entry : params.entrySet()) {

sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");

}

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

try {

MessageDigest md = MessageDigest.getInstance("MD5");

byte[] bytes = md.digest(sb.toString().getBytes("UTF-8"));

StringBuilder result = new StringBuilder();

for (byte b : bytes) {

String hex = Integer.toHexString(b & 0xFF);

if (hex.length() == 1) {

result.append("0");

}

result.append(hex);

}

return result.toString().toUpperCase();

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

```

6. 发起HTTP POST请求:

```java

private static String sendHttpPostRequest(String url, String requestXml) {

try {

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();

connection.setRequestMethod("POST");

connection.setDoOutput(true);

connection.setDoInput(true);

connection.setUseCaches(false);

connection.setRequestProperty("Content-Type", "application/xml");

connection.setRequestProperty("Content-Length", String.valueOf(requestXml.length()));

connection.getOutputStream().write(requestXml.getBytes("UTF-8"));

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

StringBuilder response = new StringBuilder();

String line;

while ((line = reader.readLine()) != null) {

response.append(line);

}

return response.toString();

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

```

7. 解析XML响应:

```java

private static String parseXmlResponse(String xml, String tagName) {

try {

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder = factory.newDocumentBuilder();

Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));

Element root = doc.getDocumentElement();

NodeList nodeList = root.getElementsByTagName(tagName);

if (nodeList != null && nodeList.getLength() > 0) {

Node node = nodeList.item(0);

return node.getTextContent();

}

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

```

上述代码示例中的appId、mchId、apiKey等参数需要替换为真实的值,以便实际使用。

调用示例代码时,可以按照下面的方式调用:

```java

String appId = "your_appId";

String mchId = "your_mchId";

String apiKey = "your_apiKey";

String body = "test";

String outTradeNo = "your_outTradeNo";

int totalFee = 1;

String notifyUrl = "your_notifyUrl";

String tradeType = "JSAPI";

String openid = "your_openid";

String prepayId = createPayOrder(appId, mchId, apiKey, body, outTradeNo, totalFee, notifyUrl, tradeType, openid);

if (prepayId != null) {

// 根据prepayId生成JSAPI支付参数

String payParams = generateJsapiPayParams(appId, apiKey, prepayId);

// 跳转到支付页面

redirect("https://api.weixin.qq.com/sns/jscode2session?" + payParams);

}

```

需要注意的是,微信支付接口的调用需要配置合法的域名,并且需要验证签名等安全机制。此外,在实际生产环境中,还需要考虑异常处理、日志记录等方面的问题,以保证支付过程的可靠性和安全性。

总结:本文通过一个微信支付的Java代码示例,介绍了如何使用Java编程实现微信支付功能。通过调用微信支付接口,可以实现创建支付订单、生成支付参数等功能。此外,还需要注意配置合法的域名和支持安全机制等问题。希望本文对您理解微信支付的实现过程有所帮助。

壹涵网络我们是一家专注于网站建设、企业营销、网站关键词排名、AI内容生成、新媒体营销和短视频营销等业务的公司。我们拥有一支优秀的团队,专门致力于为客户提供优质的服务。

我们致力于为客户提供一站式的互联网营销服务,帮助客户在激烈的市场竞争中获得更大的优势和发展机会!

点赞(10) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿
发表
评论
返回
顶部