Java微信企業(yè)付款

語言:Java(基于 SpringBoot 實現(xiàn)方案)、XML(微信在 HTTP 協(xié)議中的數(shù)據(jù)傳輸方案)
工具包:XML 解析包(JDOM),HTTP 請求工具包(ApacheHttp),MD5 簽名包(JDK 自帶)

一:賬號申請
1、需要到微信商戶平臺進(jìn)行賬號申請,獲取商戶號(mch_id)和密鑰(key)
2、需要在微信開放平臺申請注冊一個 APP(移動支付、公眾號、小程序需要到微信公眾平臺獲取對應(yīng)的服務(wù) ID),獲取?APP ID(app_id)

二:實現(xiàn)代碼

package com.fxkj.photo.app.pay.component;

import com.alibaba.fastjson.JSONObject;
import com.fxkj.common.result.Result;
import com.fxkj.common.util.wachat.*;
import com.fxkj.photo.app.pay.constants.WeChatPayConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
?import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.KeyStore;
import java.util.Map;
import java.util.TreeMap;

?/**
?* @Author admin
?* @Description 微信接口
?*/
@Slf4j
@Component public class WeChatPayComponent {
????@Autowired
? ? private WeChatPayConstants weChatPayConstants;?

? ?? /** * 微信提現(xiàn)(企業(yè)付款)
?????* @param request
?????* @param response
?????* @param params
?????* @return
?????*/
?????public Result weChatWithdrawal(HttpServletRequest request, HttpServletResponse response , Map<String ,Object> params) {
????????????String nonce_str = WXUtil.getNonceStr();
????????????TreeMap<String, Object> parameters = new TreeMap<String, Object>(); ????????????parameters.put("mch_appid",weChatPayConstants.WX_WITHDRAWAL_APP_ID);
????????????parameters.put("mchid", weChatPayConstants.WX_MCH_ID);
????????????parameters.put("nonce_str", nonce_str);?? ?
????????????parameters.put("partner_trade_no", params.get("partner_trade_no"));
????????????parameters.put("openid", params.get("openId"));
????????????parameters.put("check_name", weChatPayConstants.WX_WITHDRAWAL_CHECK_NAME);????????????
????????????parameters.put("amount", "100");
? ? ? ? ? ? parameters.put("desc", weChatPayConstants.WX_WITHDRAWAL_DESC); parameters.put("spbill_create_ip",? request.getRemoteAddr());
????????????parameters.put("sign", WeChatUtils.createSign("UTF-8", parameters,weChatPayConstants.WX_PARTNER_KEY));
????????????String resContent = "";
????????????String tosend = WeChatUtils.getRequestXml(parameters);
????????????try {
????????????????resContent = httpsRefundRequest(weChatPayConstants.WX_WITHDRAWAL_GATE_URL, "POST", tosend,weChatPayConstants.WX_MCH_ID);
????????????????Map<String, String> map = XMLUtil.doXMLParse(resContent);
????????????????if (map.get("return_code").equalsIgnoreCase("SUCCESS") && map.get("result_code").equalsIgnoreCase("SUCCESS")) {
? ? ? ? ? ? ? ? ????return Result.error(0 ,map.get("return_msg"));
? ? ? ? ? ? ????} else {
? ? ? ? ? ? ? ? ????return Result.error(1 ,map.get("return_msg"));
????????????????}
????????????} catch (Exception e) {
? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? }
? ? ? ? ? ? return Result.error(1 ,"FAIL");
? ? ? ? }

????/**
????* 企業(yè)付款請求方法
????* @param requestUrl
????* @param requestMethod
????* @param outputStr
????* @param mch_id
????* @return
????* @throws Exception
????*/
????@SuppressWarnings("deprecation")
????private String httpsRefundRequest(String requestUrl, String requestMethod, String outputStr, String mch_id) throws Exception {?
????????KeyStore keyStore = KeyStore.getInstance("PKCS12");
????????StringBuilder res = new StringBuilder("");
????????ClassPathResource classPathResource = new ClassPathResource("apiclient_cert.p12");
????????InputStream instream = classPathResource.getInputStream();
????????try {
????????????keyStore.load(instream, mch_id.toCharArray());
????????} finally {
????????????instream.close();
????????}
????????SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mch_id.toCharArray()).build();
????????SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] { "TLSv1" }, null, ????????SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
????????CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
????????try {
????????????HttpPost httpost = new HttpPost(requestUrl);
????????????httpost.addHeader("Connection", "keep-alive");
????????????httpost.addHeader("Accept", "*/*");
????????????httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
????????????httpost.addHeader("Host", "api.mch.weixin.qq.com");
????????????httpost.addHeader("X-Requested-With", "XMLHttpRequest");
????????????httpost.addHeader("Cache-Control", "max-age=0");
????????????httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
????????????StringEntity entity2 = new StringEntity(outputStr, Consts.UTF_8);
????????????httpost.setEntity(entity2); ?
????????????CloseableHttpResponse response = httpclient.execute(httpost);
????????????try {
????????????????HttpEntity entity = response.getEntity();
????????????????if (entity != null) {
????????????????????BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(entity.getContent()));
????????????????????String text = "";
????????????????????res.append(text);
????????????????????while ((text = bufferedReader.readLine()) != null) {
????????????????????????res.append(text);
????????????????????} ?
????????????????}
????????????????EntityUtils.consume(entity);
????????????} finally { response.close();
????????}
?????} finally {
?????????httpclient.close();
?????}
?????return res.toString();
?}

package com.fxkj.photo.app.pay.constants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @Author admin
* @Description 微信 常量配置
*/
@Component
public class WeChatPayConstants {

?????/** * 微信支付商戶號 */
?????@Value("${wx.pay.app.mchId}")
?????public String WX_MCH_ID;

?????/** * 商戶號對應(yīng)的密鑰 */
?????@Value("${wx.pay.app.privateKey}")
?????public String WX_PARTNER_KEY;

????/** * 校驗用戶姓名選項 * 1、NO_CHECK:不校驗真實姓名 * 2、FORCE_CHECK:強校驗真實姓名 */ ????@Value("${wx.withdrawal.app.check_name}")
?????public String WX_WITHDRAWAL_CHECK_NAME;

?????/** * 公眾號APPID */
? ? ?@Value("${wx.withdrawal.app.appId}")
?????public String WX_WITHDRAWAL_APP_ID;

? ? ?/** * 請求Url */
? ? ?@Value("${wx.withdrawal.app.gateUrl}")
?????public String WX_WITHDRAWAL_GATE_URL;

????/** * 企業(yè)付款備注 */
????@Value("${wx.withdrawal.app.desc}")
? ? public String WX_WITHDRAWAL_DESC;
}


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。