生成java对接web端微信支付的demo
时间: 2023-02-20 17:27:56 浏览: 134
微信支付后端demo(java)
我可以提供一个参考实现:
```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class WeChatPayDemo {
public static void main(String[] args) throws IOException {
// 微信支付接口地址
String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
// 组装请求参数
Map<String, String> params = getParams();
// 发起请求
String result = sendPost(url, params);
// 解析响应结果
JSONObject jsonObject = JSON.parseObject(result);
String return_code = jsonObject.getString("return_code");
String return_msg = jsonObject.getString("return_msg");
if (return_code.equals("SUCCESS")) {
String result_code = jsonObject.getString("result_code");
if (result_code.equals("SUCCESS")) {
// 微信支付订单号
String prepay_id = jsonObject.getString("prepay_id");
// 构建微信支付参数
Map<String, String> payParams = buildPayParams(prepay_id);
// 调起微信支付
invokeWeChatPay(payParams);
}
}
}
/**
* 发送post请求
*
* @param url
* 请求地址
* @param params
* 请求参数
* @return
* @throws IOException
*/
public static String sendPost(String url, Map<String, String> params) throws IOException {
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
String param = buildParams(params);
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result.toString();
}
/**
* 组装请求参数
*
* @return
*/
public static Map<String, String> getParams() {
// TODO 组装请求参数
return null;
}
/**
* 构建请求参数字符串
*
* @param params
* 请求参数
* @return
*/
public static String buildParams(Map<String, String> params) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
return sb.substring(0, sb.length() - 1);
}
/**
* 构建微信支付参数
*
* @param prepay_id
* 预支付订单号
* @return
*/
public static Map<String, String> buildPayParams(String prepay_id) {
// TODO 构建微信支付参数
return null;
}
/**
* 调起微信支付
*
* @param payParams
* 微信支付参数
*/
public static void invokeWeChatPay(Map<String, String> payParams) {
// TODO 调起微信支付
}
}
```
阅读全文