一、准备材料
- 微信商户参数,例:appid、mch_id...
- 微信SDK,下载地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1
- 去了解一下微信支付的流程
注:下载完sdk mvn install jar包就行了,最后在maven引入或直接复制进lib
二、编代码
/**
* @Description H5调起微信支付微信浏览器外支付
* @param request
* @return Map
*/
@RequestMapping(value="/pay/wap", method = RequestMethod.GET)
@ResponseBody
public Map<String,String> orders_other(HttpServletRequest request) {
try {
//拼接下单地址参数
Map<String, String> paraMap = new HashMap<String, String>();
//获取请求ip地址的方法
String ip = getIpAddr(request);
paraMap.put("appid", "appid");
paraMap.put("mch_id", "mch_id");
paraMap.put("nonce_str", WXPayUtil.generateNonceStr());
paraMap.put("body", "XX商城-测试费用");
// 生成商品订单号
int randomNum = (int) (Math.random() * 1999+5000);
String out_trade_no = TimeUtils.getSysTime("yyyyMMddHHmmss") + randomNum;
paraMap.put("out_trade_no", out_trade_no);//商品的订单号每次要唯一
paraMap.put("total_fee", "1");//微信已分为单位此金额为0.01
paraMap.put("spbill_create_ip", ip);
paraMap.put("notify_url", "填你的通知地址");// 此路径是微信服务器调用支付结果通知路径
paraMap.put("trade_type", "MWEB");
paraMap.put("scene_info", "{\"h5_info\":{\"type\":\"Wap\",\"wap_url\":\"填开通H5支付的域名\",\"wap_name\": \"订单支付\"}}");
String paternerKey = "appkey";
String sign = WXPayUtil.generateSignature(paraMap, paternerKey);
paraMap.put("sign", sign);
String xml = WXPayUtil.mapToXml(paraMap);//将所有参数(map)转xml格式
// 统一下单 https://api.mch.weixin.qq.com/pay/unifiedorder
String unifiedorder_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
System.out.println(xml);
String xmlStr = HttpRequest.sendPost(unifiedorder_url, xml);//发送post请求"统一下单接口"
System.out.println("wx return==>"+xmlStr);
//以下内容是返回前端页面的json数据
String mweb_url = "";//跳转链接
if (xmlStr.indexOf("SUCCESS") != -1) {
Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
for (String key : map.keySet()){
logger.info(key+"=="+map.get(key));
}
mweb_url = (String) map.get("mweb_url");
//支付完返回浏览器跳转的地址,如跳到查看订单页面
String redirect_url = "回调地址如果你需要";
String redirect_urlEncode = URLEncoder.encode(redirect_url,"utf-8");//对上面地址urlencode
mweb_url = mweb_url + "&redirect_url=" + redirect_urlEncode;//拼接返回地址
}
Map<String, String> payMap = new HashMap<String, String>();
payMap.put("mweb_url", mweb_url);
return payMap;
} catch (Exception e) {
logger.info("微信支付异常");
}
return null;
}
最后前端只要向mweb_url发送请求就可以拉取微信客户端了
location.href = result.mweb_url;
如果上面的代码正确没有成功的话,检查一下参数是否正确,注意看微信返回的信息
获取请求ip地址
/**
* 获取用户实际ip
* @param request
* @return
*/
public String getIpAddr(HttpServletRequest request){
String ipAddress = request.getHeader("x-forwarded-for");
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
//根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress= inet.getHostAddress();
}
}
//对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
if(ipAddress.indexOf(",")>0){
ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
}
}
return ipAddress;
}
发送Http的工具类
public class HttpRequest {
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(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)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
}