开发指引_Native支付|微信支付商户文档中心
1.开发使用
安装依赖
com.github.wxpay
wxpay-sdk
0.0.3
org.apache.httpcomponents
httpclient
4.5.3
2.配置配置文件
#微信的appid,商家id和密钥
weixin.appid=wx8087d8...
weixin.mch_id=1532...
weixin.api_key=Cc15838062...
3.创建httpclient工具类
这是一个工具类,编写了发送请求的一些功能。
public class HttpClient {
private String url;
private Map param;
private int statusCode;
private String content;
private String xmlParam;
private boolean isHttps;
public boolean isHttps() {
return isHttps;
}
public void setHttps(boolean isHttps) {
this.isHttps = isHttps;
}
public String getXmlParam() {
return xmlParam;
}
public void setXmlParam(String xmlParam) {
this.xmlParam = xmlParam;
}
public HttpClient(String url, Map param) {
this.url = url;
this.param = param;
}
public HttpClient(String url) {
this.url = url;
}
public void setParameter(Map map) {
param = map;
}
public void addParameter(String key, String value) {
if (param == null) {
param = new HashMap();
}
param.put(key, value);
}
public void post() throws ClientProtocolException, IOException {
HttpPost http = new HttpPost(url);
setEntity(http);
execute(http);
}
public void put() throws ClientProtocolException, IOException {
HttpPut http = new HttpPut(url);
setEntity(http);
execute(http);
}
public void get() throws ClientProtocolException, IOException {
if (param != null) {
StringBuilder url = new StringBuilder(this.url);
boolean isFirst = true;
for (String key : param.keySet()) {
if (isFirst) {
url.append("?");
} else {
url.append("&");
}
url.append(key).append("=").append(param.get(key));
}
this.url = url.toString();
}
HttpGet http = new HttpGet(url);
execute(http);
}
/**
* set http post,put param
*/
private void setEntity(HttpEntityEnclosingRequestBase http) {
if (param != null) {
List nvps = new LinkedList();
for (String key : param.keySet()) {
nvps.add(new BasicNameValuePair(key, param.get(key))); // 参数
}
http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 设置参数
}
if (xmlParam != null) {
http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));
}
}
private void execute(HttpUriRequest http) throws ClientProtocolException,
IOException {
CloseableHttpClient httpClient = null;
try {
if (isHttps) {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain,
String authType)
throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext);
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
.build();
} else {
httpClient = HttpClients.createDefault();
}
CloseableHttpResponse response = httpClient.execute(http);
try {
if (response != null) {
if (response.getStatusLine() != null) {
statusCode = response.getStatusLine().getStatusCode();
}
HttpEntity entity = response.getEntity();
// 响应内容
content = EntityUtils.toString(entity, Consts.UTF_8);
}
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpClient.close();
}
}
public int getStatusCode() {
return statusCode;
}
public String getContent() throws ParseException, IOException {
return content;
}
}
4.编写接口
@PostMapping("/createNavite/{orderId}")
public Result createNative(@PathVariable String orderId) {
return orderChargeService.createNative(orderId);
}
5.具体实现
这段代码本质上就是设置微信支付需要的请求东西,发送给微信接口,然后微信接口返回给我们一个xml文件,从xml文件中获取所需要的信息。
@Override
public Result createNative(String orderId) {
//1.根据订单查出订单信息
QueryWrapper queryWrapper = new QueryWrapper<>();
queryWrapper.eq("order_id",orderId);
queryWrapper.eq("order_status",0);
OrderCharge orderCharge = orderChargeMapper.selectOne(queryWrapper);
if(orderCharge != null){
try {
//创建HttpClient对象,远程调用微信功能
HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
//支持Https协议
httpClient.setHttps(true);
//设置XML参数格式
Map params = new HashMap<>();
params.put("appid",appid);
params.put("mch_id",mchid);
params.put("nonce_str", WXPayUtil.generateNonceStr());
params.put("body",orderCharge.getOrderId());
params.put("out_trade_no",orderId);
//实际的支付价格
params.put("total_fee",new params.put("total_fee",orderCharge.getOrderAmount().multiply(new BigDecimal(100)).intValue()+"");
//设置用户的终端ip地址
params.put("spbill_create_ip","127.0.0.1");
//设置支付通知请求
params.put("notify_url","http://localhost:8080/orderCharge/payNotify");
//设置交易类型
params.put("trade_type","NATIVE");
//设置请求参数
httpClient.setXmlParam(WXPayUtil.generateSignedXml(params,apiKey));
//发送请求
httpClient.post();
//获取请求响应结果
String content = httpClient.getContent();
Map map = WXPayUtil.xmlToMap(content);
if(map.get("return_code").equals("SUCCESS")){
Map result = new HashMap<>();
//支付二维码
result.put("codeUrl",map.get("code_url"));
result.put("price",orderCharge.getOrderAmount());
result.put("orderId",orderId);
return new Result(200,"生成二维码成功",result);
}
}catch (Exception e){
e.printStackTrace();
}
}
return new Result(500,"支付失败",null);
}
6.查询支付状态
发送请求确认微信订单的支付状态。
public Result queryPayStatus(String orderId){
try {
HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
Map params = new HashMap<>();
params.put("appid",appid);
params.put("mch_id",mchid);
params.put("out_trade_no",orderId);
params.put("nonce_str", WXPayUtil.generateNonceStr());
httpClient.setHttps(true);
httpClient.setXmlParam(WXPayUtil.generateSignedXml(params,apiKey));
httpClient.post();
String content = httpClient.getContent();
Map map = WXPayUtil.xmlToMap(content);
if(map.get("trade_state").equals("SUCCESS")){
//TODO 1.修改订单状态
//TODO 2.往支付记录添加支付记录
return new Result(200,"支付成功",null);
}
}catch (Exception e){
e.printStackTrace();
}
return new Result(500,"支付失败",null);
}