SpringBoot中對(duì)接微信支付接口
1.微信支付開(kāi)發(fā)文檔
https://pay.weixin.qq.com/wiki/doc/api/index.html
1.準(zhǔn)備工作:
在微信上申請(qǐng)服務(wù)號(hào)類型的公眾號(hào),從公眾號(hào)獲取以下數(shù)據(jù)
-
appid:微信公眾賬號(hào)或開(kāi)放平臺(tái)APP的唯一標(biāo)識(shí)
-
mch_id:商戶號(hào) (配置文件中的partner)
-
partnerkey:商戶密鑰
2.根據(jù)項(xiàng)目需求選擇適合的支付方式,本例使用Native支付方式
點(diǎn)擊查看文檔->API列表
開(kāi)發(fā)步驟
引入依賴
<dependency>
<groupId>com.github.wxpay</groupId>
<artifactId>wxpay-sdk</artifactId>
<version>0.0.3</version>
</dependency>
修改application.proerties配置文件
#關(guān)聯(lián)的公眾號(hào)appid #商戶號(hào) #商戶key
weixin.appid=wx34bb2aa123de3dcd
weixin.partner=1611167878
weixin.partnerkey=4ca478a4580794e2f7cf67881cb21dd4b1
參數(shù)注入:
@Component
public class PropertiesUtils implements InitializingBean {
@Value("${weixin.appid}")
private String appid;
@Value("${weixin.partner}")
private String partner;
@Value("${weixin.partnerkey}")
private String partnerkey;
public static String APPID;
public static String PARTNER;
public static String PARTNERKEY;
@Override
public void afterPropertiesSet() throws Exception {
APPID = appid;
PARTNER = partner;
PARTNERKEY = partnerkey;
}
}
HttpClient工具類:
用于發(fā)送http請(qǐng)求,可直接復(fù)制
/**
* http請(qǐng)求客戶端
*/
public class HttpClient {
private String url;
private Map<String, String> param;
private int statusCode;
private String content;
private String xmlParam;
private boolean isHttps;
private boolean isCert = false;
//證書(shū)密碼 微信商戶號(hào)(mch_id)
private String certPassword;
public boolean isHttps() {
return isHttps;
}
public void setHttps(boolean isHttps) {
this.isHttps = isHttps;
}
public boolean isCert() {
return isCert;
}
public void setCert(boolean cert) {
isCert = cert;
}
public String getXmlParam() {
return xmlParam;
}
public void setXmlParam(String xmlParam) {
this.xmlParam = xmlParam;
}
public HttpClient(String url, Map<String, String> param) {
this.url = url;
this.param = param;
}
public HttpClient(String url) {
this.url = url;
}
public String getCertPassword() {
return certPassword;
}
public void setCertPassword(String certPassword) {
this.certPassword = certPassword;
}
public void setParameter(Map<String, String> map) {
param = map;
}
public void addParameter(String key, String value) {
if (param == null)
param = new HashMap<String, String>();
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<NameValuePair> nvps = new LinkedList<NameValuePair>();
for (String key : param.keySet())
nvps.add(new BasicNameValuePair(key, param.get(key))); // 參數(shù)
http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 設(shè)置參數(shù)
}
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) {
if(isCert) {
FileInputStream inputStream = new FileInputStream(new File(ConstantPropertiesUtils.CERT));
KeyStore keystore = KeyStore.getInstance("PKCS12");
char[] partnerId2charArray = certPassword.toCharArray();
keystore.load(inputStream, partnerId2charArray);
SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keystore, partnerId2charArray).build();
SSLConnectionSocketFactory sslsf =
new SSLConnectionSocketFactory(sslContext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
} else {
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();
// 響應(yīng)內(nèi)容
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;
}
}
到此準(zhǔn)備工作結(jié)束,剩下的就是參考微信支付開(kāi)發(fā)文檔,提供微信支付接口所需參數(shù)和獲取請(qǐng)求結(jié)果,從結(jié)果中取出我們所需的數(shù)據(jù)
準(zhǔn)備微信支付所需參數(shù)
//對(duì)接微信支付
//組裝數(shù)據(jù)
Map<String, String> paramMap = new HashedMap<>();
paramMap.put("appid", PropertiesUtils.APPID); //公眾號(hào)appid
paramMap.put("mch_id",PropertiesUtils.PARTNER); //商戶號(hào)
paramMap.put("out_trade_no",orderInfo.getOutTradeNo()); //商戶訂單號(hào)
paramMap.put("nonce_str", WXPayUtil.generateNonceStr()); //隨機(jī)字符串
String object = orderInfo.getReserveDate()+"就診"+ orderInfo.getDepname();
paramMap.put("body",object); //商品描述
//paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
paramMap.put("total_fee","1"); //支付金額
paramMap.put("spbill_create_ip","127.0.0.1"); //用戶的客戶端IP
paramMap.put("notify_url", "https://2495161sb6.goho.co/api/order/weixinPay/weixinNotify");//微信支付結(jié)果通知的回調(diào)地址
paramMap.put("trade_type", "NATIVE"); //交易類型
注: total_fee 屬性為支付金額,單位是分
微信支付接口地址: https://api.mch.weixin.qq.com/pay/unifiedorder文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-548045.html
調(diào)用接口,發(fā)送Http請(qǐng)求
//對(duì)接微信支付
HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
httpClient.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
//微信接口為https請(qǐng)求,告訴httpClient改請(qǐng)求為https
httpClient.setHttps(true);
httpClient.post();
接收返回值,獲取所需數(shù)據(jù)
//獲取響應(yīng)數(shù)據(jù)
String content = httpClient.getContent();
Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
//以下字段在return_code和result_code都為SUCCESS的時(shí)候有返回
if(resultMap.get("return_code").equals("SUCCESS")&&resultMap.get("result_code").equals("SUCCESS")) {
map = new HashMap<>();
map.put("orderId", orderId); //訂單id
map.put("totalFee", orderInfo.getAmount());
map.put("resultCode", resultMap.get("result_code"));
map.put("codeUrl", resultMap.get("code_url")); //二維碼鏈接
}
查詢訂單退款等操作參考下單即可
map = new HashMap<>();
map.put(“orderId”, orderId); //訂單id
map.put(“totalFee”, orderInfo.getAmount());
map.put(“resultCode”, resultMap.get(“result_code”));
map.put(“codeUrl”, resultMap.get(“code_url”)); //二維碼鏈接
}文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-548045.html
查詢訂單退款等操作參考下單即可
到了這里,關(guān)于對(duì)接微信支付接口的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!