HoJe
男孩子你要加油阿
前言准备材料H5支付请求的参数返回结果统一下单回调接口用到的工具类886
. 前言
大家好,分享是快乐的,也见证了个人成长历程,文章大多都是工作经验总结以及平时学习积累,基于自身认知不足之处在所难免,也请大家指正,共同进步。此次微信支付也是我刚入这个行业做的第一个功能,在这里做总结以及分享给需要的人.
微信支付之二维码支付(总结已经更新)
微信支付之JSAPI支付(总结还没有更新呢)
微信支付之退款(总结还没有更新呢)
微信支付之查询订单(总结还没有更新呢)
. 准备材料
首先你得看微信支付的H5开发文档
H5开发文档
至于如何申请账号,那是公司层面的操作,这里我不清楚,也不做相关的介绍了,我只清楚拿到账号之后的操作。
微信服务公众平台
微信商户平台
然后就是必要的配置了
公众平台的appid:基本配置-公众号开发信息-开发者ID(AppID)
签名密钥:基本配置-公众号开发信息-开发者密码(AppSecret),自己生成,保证唯一即可,生成之后妥善保存,二次不可见
商户号:账户中心-账户设置-商户信息-商户号
微信支付证书:账户中心-->账户设置-->API安全-->证书下载
这个是涉及到退款业务,必须使用证书(以后有用的)
再然后就是微信的SDK
. H5支付请求的参数
开发文档你们应该都看熟了吧,让我们一起看看需要哪些参数吧.
一共有十一个参数,知道需要哪些参数了,获取到传给微信就可以召唤神龙了.
下面是参数打包好的举例.
. 返回结果
知道参数了让我们看看返回的结果
介绍的很详细,我就不多说了.
. 统一下单
首页你得有统一下单是url:https://api.mch.weixin.qq.com/pay/unifiedorder
让我们一起召唤神龙吧.
代码如下
1@RequestMapping(value = "/h5Pay")
2 @ResponseBody
3 public Object h5Pay(HttpServletRequest request,HttpServletResponse response,String orderNumber) {
4 PayOrderDO payOrderDO = this.payOrderService.getOrder(orderNumber);//订单信息
5 logger.info("订单号:{}发起H5支付",product.getOutTradeNo());
6 String mweb_url = "";
7 String ip= "127.0.0.1";//IPUtils.getIpAddr(request); 上线获取Ip
8 Map<String, String> request_data = new HashMap<>();
9 try {
10 Map<String, String> data = new HashMap<String, String>();
11 data.put("appid", WxConstants.APP_ID);//公众账号ID
12 data.put("mch_id",WxConstants.PARTNER);//商户号
13 data.put("body", "测试");//商品详情
14 data.put("out_trade_no",orderNumber);//订单号
15 data.put("nonce_str", UuidUtil.get32UUID());//32位字符
16 //转换微信中存在最小计算单位是分的问题
17 BigDecimal payMoney = payOrderDO.getPayMoney();
18 BigDecimal bigDecimal = new BigDecimal(100);
19 BigDecimal amount = payMoney.multiply(bigDecimal).setScale(0, BigDecimal.ROUND_DOWN);
20 data.put("total_fee", String.valueOf(amount));//总金额
21 data.put("spbill_create_ip", ip);//用户终端IP
22 data.put("trade_type", "MWEB"); // H5支付的交易类型为MWEB
23 data.put("notify_url", WxConstants.NOTIFY_URL);//通知地址
24 data.put("scene_info", "{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"https://xxx.com\",\"wap_name\": \"打赏给HoJe\"}}");
25 String sign = createSign(data, WxConstants.PARTNER_KEY, WxConstants.CHARSET);
26 //调用生成签名的方法,用以Map集合中的相关参数生成签名
27 data.put("sign", sign);//签名
28 String xml = WXPayUtil.generateSignedXml(data, WxConstants.PARTNER_KEY);//转Xml格式 微信SDK自带
29
30 System.out.println("request - XML:" + xml);
31
32 String resultXML = HttpsClientUtil.doPost(WxConstants.BAUSE_URL, xml);//发送post请求 如请求成功返回的数据是xml格式的
33
34 System.out.println("result - XML:" + resultXML);
35 Map<String, String> map = xmlToMap(resultXML);//xml转map 微信SDK自带
36 String returnCode = map.get("return_code");
37 if("SUCCESS".equals(returnCode)){
38 String resultCode = map.get("result_code");
39 if("SUCCESS".equals(resultCode)){
40 logger.info("订单号:{}发起H5支付成功",product.getOutTradeNo());
41 mweb_url = (String) map.get("mweb_url");
42 }else{
43 String errCodeDes = map.get("err_code_des");
44 logger.info("订单号:{}发起H5支付(系统)失败:{}",product.getOutTradeNo(),errCodeDes);
45 }
46 }else{
47 String returnMsg = map.get("return_msg");
48 logger.info("(订单号:{}发起H5支付(通信)失败:{}",product.getOutTradeNo(),returnMsg);
49 }
50 } catch (Exception e) {
51 logger.error("订单号:{}发起H5支付失败(系统异常))",product.getOutTradeNo(),e);
52 }
53 return mweb_url;
54 }
本人自己写的也可能不是很完美欢迎你们指出 送上更完美的demo 谢谢!!!
. 回调接口
我踩的坑阿!
注意:
1丶回调url必须得填写正确要不然微信访问不到会一直调用,就是支付成功后微信异步通知我们的服务器地址加项目加路径.
2丶一定要验证签名,要不然微信不知道是那个商户的会觉得不合法.
3丶给微信的数据一定是xml格式的,要不然微信解析不到就会一直调用(这就是微信比支付宝坑的地方)
话不多说上代码
1/**
2 * 微信支付回调函数
3 * 支付成功后微信服务器会调用此方法,修改数据库订单状态
4 */
5 @RequestMapping(value = "/notify")
6 public void wxPayCallBack(HttpServletRequest request, HttpServletResponse response) {
7 try {
8 InputStream inStream = request.getInputStream();
9 ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
10 byte[] buffer = new byte[1024];
11 int len = 0;
12 while ((len = inStream.read(buffer)) != -1) {
13 outSteam.write(buffer, 0, len);
14 }
15 outSteam.close();
16 inStream.close();
17 String result = new String(outSteam.toByteArray(), WxConstants.CHARSET);
18 Map<String, String> map = xmlToMap(result);//xml转map 微信SDK自带
19 // 判断签名是否正确 微信SDK自带的方法
20 if (WXPayUtil.isSignatureValid(map, WxConstants.PARTNER_KEY)) {
21 logger.info("微信支付成功回调");
22 // ------------------------------
23 // 处理业务开始
24 // ------------------------------
25 String resXml = "";
26 if ("SUCCESS".equals((String) map.get("result_code"))) {
27 // 这里是支付成功
28 String orderNo = (String) map.get("out_trade_no");
29 logger.info("微信订单号{}付款成功",orderNo);
30 //这里 根据实际业务场景 做相应的操作
31 // 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
32 resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
33 } else {
34 logger.info("支付失败,错误信息:{}",packageParams.get("err_code"));
35 resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
36 }
37 // ------------------------------
38 // 处理业务完毕
39 // ------------------------------
40 BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
41 out.write(resXml.getBytes());
42 out.flush();
43 out.close();
44 } else {
45 System.out.println("通知签名验证失败");
46 logger.info("通知签名验证失败");
47 }
48
49
50 } catch (Exception e) {
51 e.printStackTrace();
52 }
53
54 }
其实你弄懂了,微信支付也没有那么难的.
我看过一个博客的签名分享给大家:再牛逼的技术也抵挡不住你傻逼式的坚持.
. 用到的工具类
1丶32位字符串
1public class UuidUtil {
2
3 public static String get32UUID() {
4 String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
5 return uuid;
6 }
7}
2丶获取用户的终端ip
1/**
2 * IP地址
3 *
4 * @author HoJe
5 */
6public class IPUtils {
7 private static Logger logger = LoggerFactory.getLogger(IPUtils.class);
8
9 /**
10 * 获取IP地址
11 *
12 * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
13 * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
14 */
15 public static String getIpAddr(HttpServletRequest request) {
16 String ip = null;
17 try {
18 ip = request.getHeader("x-forwarded-for");
19 if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
20 ip = request.getHeader("Proxy-Client-IP");
21 }
22 if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
23 ip = request.getHeader("WL-Proxy-Client-IP");
24 }
25 if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
26 ip = request.getHeader("HTTP_CLIENT_IP");
27 }
28 if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
29 ip = request.getHeader("HTTP_X_FORWARDED_FOR");
30 }
31 if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
32 ip = request.getRemoteAddr();
33 }
34 } catch (Exception e) {
35 logger.error("IPUtils ERROR ", e);
36 }
37
38 //使用代理,则获取第一个IP地址
39 if(StringUtils.isEmpty(ip) && ip.length() > 15) {
40 if(ip.indexOf(",") > 0) {
41 ip = ip.substring(0, ip.indexOf(","));
42 }
43 }
44
45 return ip;
46 }
47
48}
3丶生成签名
1/**
2 * 生成签名
3 * 这个方法是从微信sdk里copy过来的,自己也可以写,要注意生成签名后UTF-8的转换,要不然容易报签名Body UTF-8错误
4 *
5 * @param data 待签名数据
6 * @param key API密钥
7 * @param charset UTF-8
8 */
9 public static String createSign(final Map<String, String> data, String key, String charset) throws Exception {
10 return createSign(data, key, WXPayConstants.SignType.MD5, charset);
11 }
12
13 /**
14 * 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。
15 *
16 * @param data 待签名数据
17 * @param key API密钥
18 * @param signType 签名方式
19 * @param charset UTF-8
20 * @return 签名
21 */
22 private static String createSign(final Map<String, String> data, String key, WXPayConstants.SignType signType, String charset) throws Exception {
23 //根据规则创建可排序的map集合
24 Set<String> keySet = data.keySet();
25 String[] keyArray = keySet.toArray(new String[keySet.size()]);
26 Arrays.sort(keyArray);
27 StringBuilder sb = new StringBuilder();
28 for (String k : keyArray) {
29 if (k.equals(WXPayConstants.FIELD_SIGN)) {
30 continue;
31 }
32 if (data.get(k).trim().length() > 0){
33 sb.append(k).append("=").append(data.get(k).trim()).append("&");
34 } // 参数值为空,则不参与签名
35 }
36 sb.append("key=").append(key);
37 //转换UTF-8
38 String str = new String(sb.toString().getBytes(charset));
39 if (WXPayConstants.SignType.MD5.equals(signType)) {
40 return MD5(sb.toString()).toUpperCase();
41 } else if (WXPayConstants.SignType.HMACSHA256.equals(signType)) {
42 return HMACSHA256(sb.toString(), key);
43 } else {
44 throw new Exception(String.format("Invalid sign_type: %s", signType));
45 }
46 }
47}
4丶http请求的工具 实际没有用到很多方法有的是退款需要用到的
1public class HttpsClientUtil {
2 private static PoolingHttpClientConnectionManager connMgr;
3 private static RequestConfig requestConfig;
4 private static final int MAX_TIMEOUT = 7000;
5
6 static {
7 // 设置连接池
8 connMgr = new PoolingHttpClientConnectionManager();
9 // 设置连接池大小
10 connMgr.setMaxTotal(100);
11 connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
12
13 RequestConfig.Builder configBuilder = RequestConfig.custom();
14 // 设置连接超时
15 configBuilder.setConnectTimeout(MAX_TIMEOUT);
16 // 设置读取超时
17 configBuilder.setSocketTimeout(MAX_TIMEOUT);
18 // 设置从连接池获取连接实例的超时
19 configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
20 // 在提交请求之前 测试连接是否可用
21 configBuilder.setStaleConnectionCheckEnabled(true);
22 requestConfig = configBuilder.build();
23 }
24
25 /**
26 * 发送 GET 请求(HTTP),不带输入数据
27 *
28 * @param url
29 * @return
30 */
31 public static String doGet(String url) {
32 return doGet(url, new HashMap<String, Object>());
33 }
34
35 /**
36 * 发送 GET 请求(HTTP),K-V形式
37 *
38 * @param url
39 * @param params
40 * @return
41 */
42 public static String doGet(String url, Map<String, Object> params) {
43 String apiUrl = url;
44 StringBuffer param = new StringBuffer();
45 int i = 0;
46 for (String key : params.keySet()) {
47 if (i == 0)
48 param.append("?");
49 else
50 param.append("&");
51 param.append(key).append("=").append(params.get(key));
52 i++;
53 }
54 apiUrl += param;
55 String result = null;
56 HttpClient httpclient = new DefaultHttpClient();
57 try {
58 HttpGet httpPost = new HttpGet(apiUrl);
59 HttpResponse response = httpclient.execute(httpPost);
60 int statusCode = response.getStatusLine().getStatusCode();
61
62 System.out.println("执行状态码 : " + statusCode);
63
64 HttpEntity entity = response.getEntity();
65 if (entity != null) {
66 InputStream instream = entity.getContent();
67 result = IOUtils.toString(instream);
68 }
69 } catch (IOException e) {
70 e.printStackTrace();
71 }
72 return result;
73 }
74
75 /**
76 * 发送 POST 请求(HTTP),不带输入数据
77 *
78 * @param apiUrl
79 * @return
80 */
81 public static String doPost(String apiUrl) {
82 return doPost(apiUrl, new HashMap<String, Object>());
83 }
84
85 /**
86 * 发送 POST 请求(HTTP),K-V形式
87 *
88 * @param apiUrl API接口URL
89 * @param params 参数map
90 * @return
91 */
92 public static String doPost(String apiUrl, Map<String, Object> params) {
93 CloseableHttpClient httpClient = HttpClients.createDefault();
94 String httpStr = null;
95 HttpPost httpPost = new HttpPost(apiUrl);
96 CloseableHttpResponse response = null;
97
98 try {
99 httpPost.setConfig(requestConfig);
100 List<NameValuePair> pairList = new ArrayList<>(params.size());
101 for (Map.Entry<String, Object> entry : params.entrySet()) {
102 NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
103 .getValue().toString());
104 pairList.add(pair);
105 }
106 httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
107 response = httpClient.execute(httpPost);
108 System.out.println(response.toString());
109 HttpEntity entity = response.getEntity();
110 httpStr = EntityUtils.toString(entity, "UTF-8");
111 } catch (IOException e) {
112 e.printStackTrace();
113 } finally {
114 if (response != null) {
115 try {
116 EntityUtils.consume(response.getEntity());
117 } catch (IOException e) {
118 e.printStackTrace();
119 }
120 }
121 }
122 return httpStr;
123 }
124
125 /**
126 * 发送 POST 请求(HTTP),JSON形式
127 *
128 * @param apiUrl
129 * @param json json对象
130 * @return
131 */
132 public static String doPost(String apiUrl, Object json) {
133 CloseableHttpClient httpClient = HttpClients.createDefault();
134 String httpStr = null;
135 HttpPost httpPost = new HttpPost(apiUrl);
136 CloseableHttpResponse response = null;
137
138 try {
139 httpPost.setConfig(requestConfig);
140 StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");//解决中文乱码问题
141 stringEntity.setContentEncoding("UTF-8");
142 stringEntity.setContentType("application/json");
143 httpPost.setEntity(stringEntity);
144 response = httpClient.execute(httpPost);
145 HttpEntity entity = response.getEntity();
146 System.out.println(response.getStatusLine().getStatusCode());
147 httpStr = EntityUtils.toString(entity, "UTF-8");
148 } catch (IOException e) {
149 e.printStackTrace();
150 } finally {
151 if (response != null) {
152 try {
153 EntityUtils.consume(response.getEntity());
154 } catch (IOException e) {
155 e.printStackTrace();
156 }
157 }
158 }
159 return httpStr;
160 }
161
162 /**
163 * 发送 SSL POST 请求(HTTPS),K-V形式
164 *
165 * @param apiUrl API接口URL
166 * @param params 参数map
167 * @return
168 */
169 public static String doPostSSL(String apiUrl, Map<String, Object> params) {
170 CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
171 HttpPost httpPost = new HttpPost(apiUrl);
172 CloseableHttpResponse response = null;
173 String httpStr = null;
174
175 try {
176 httpPost.setConfig(requestConfig);
177 List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
178 for (Map.Entry<String, Object> entry : params.entrySet()) {
179 NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
180 .getValue().toString());
181 pairList.add(pair);
182 }
183 httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
184 response = httpClient.execute(httpPost);
185 int statusCode = response.getStatusLine().getStatusCode();
186 if (statusCode != HttpStatus.SC_OK) {
187 return null;
188 }
189 HttpEntity entity = response.getEntity();
190 if (entity == null) {
191 return null;
192 }
193 httpStr = EntityUtils.toString(entity, "utf-8");
194 } catch (Exception e) {
195 e.printStackTrace();
196 } finally {
197 if (response != null) {
198 try {
199 EntityUtils.consume(response.getEntity());
200 } catch (IOException e) {
201 e.printStackTrace();
202 }
203 }
204 }
205 return httpStr;
206 }
207
208 /**
209 * 发送 SSL POST 请求(HTTPS),JSON形式
210 *
211 * @param apiUrl API接口URL
212 * @param json JSON对象
213 * @return
214 */
215 public static String doPostSSL(String apiUrl, Object json) {
216 CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
217 HttpPost httpPost = new HttpPost(apiUrl);
218 CloseableHttpResponse response = null;
219 String httpStr = null;
220
221 try {
222 httpPost.setConfig(requestConfig);
223 StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");//解决中文乱码问题
224 stringEntity.setContentEncoding("UTF-8");
225 stringEntity.setContentType("application/json");
226 httpPost.setEntity(stringEntity);
227 response = httpClient.execute(httpPost);
228 int statusCode = response.getStatusLine().getStatusCode();
229 if (statusCode != HttpStatus.SC_OK) {
230 return null;
231 }
232 HttpEntity entity = response.getEntity();
233 if (entity == null) {
234 return null;
235 }
236 httpStr = EntityUtils.toString(entity, "utf-8");
237 } catch (Exception e) {
238 e.printStackTrace();
239 } finally {
240 if (response != null) {
241 try {
242 EntityUtils.consume(response.getEntity());
243 } catch (IOException e) {
244 e.printStackTrace();
245 }
246 }
247 }
248 return httpStr;
249 }
250
251 /**
252 * 创建SSL安全连接
253 *
254 * @return
255 */
256 private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
257 SSLConnectionSocketFactory sslsf = null;
258 try {
259 SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
260
261 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
262 return true;
263 }
264 }).build();
265 sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
266
267 @Override
268 public boolean verify(String arg0, SSLSession arg1) {
269 return true;
270 }
271
272 @Override
273 public void verify(String host, SSLSocket ssl) throws IOException {
274 }
275
276 @Override
277 public void verify(String host, X509Certificate cert) throws SSLException {
278 }
279
280 @Override
281 public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
282 }
283 });
284 } catch (GeneralSecurityException e) {
285 e.printStackTrace();
286 }
287 return sslsf;
288 }
289}
好了效果就不展示了,有什么问题可以提出噢.
一起学习一起加油.
886
又到说再见的时候了,好了今天就到这里了.拜拜