对于微信API我早已是无力吐槽,真的是看一次吐一次,这么乱大家造嘛,

关于微信开发和微信API遇到的坑比所有的套路都深,简直是生无可恋,哎

下面给大家提供一个有关于微信企业付款的代码吧,不多说,直接上代码:

private Logger logger = Logger.getLogger(getClass());
// 开发者ID
private String AppID = "";
// 商户号
private String mchId = "";
// 支付key
private static String key = "";

// 统一下提现地址
private String UNIFIED_FEEDBACK_URL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";

// 校验用户姓名选项
private String check_name = "NO_CHECK";

// 校验用户姓名选项
private String send_name = "";

// 企业付款描述信息
private String desc = "";

@Autowired
private UserService userService;

@RequestMapping("/pay")
@ResponseBody
public boolean pay(HttpServletRequest request,Integer userid) throws Exception {
Userinfo user = UserUtils.getUserById(request, userid);
boolean falg = true;
SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
StringBuffer param = new StringBuffer();
param.append("mch_appid=" + AppID);
param.append("&mchid=" + mchId);
param.append("&nonce_str="+ MD5Util.MD5Encode(String.valueOf(new Random().nextInt(10000)), "utf-8").toUpperCase());
String currTime = TenpayUtil.getCurrTime();
String strTime = currTime.substring(8, currTime.length());
String strRandom = TenpayUtil.buildRandom(4) + "";
param.append("&partner_trade_no=" + strTime + strRandom);
param.append("&openid=" + user.getOpenid());
param.append("&check_name=" + check_name);
param.append("&re_user_name=" + user.getName());// 收款人姓名
int amount = (int) ( 10 * Math.random() + 100);
//int amount =(int) (Math.random()*100+100);
request.getSession().setAttribute(Constants.REDPACKET, amount);
param.append("&amount=" + amount);
param.append("&desc=" + desc);
InetAddress inetAddress = InetAddress.getLocalHost();
String ip =inetAddress.getHostAddress();
param.append("&spbill_create_ip=" + ip);
String[] params = param.toString().split("&");
Arrays.sort(params);
param = new StringBuffer();
for (String p : params) {
String[] value = p.split("=");
parameters.put(value[0], value[1]);
param.append(value[0] + "=" + value[1] + "&");
}
String sign = WeixinPaySign.createSign("UTF-8", parameters, key);
parameters.put("sign", sign);
String requestXML = XMLUtil.getRequestXml(parameters);
logger.info("requestXML:" + requestXML);
CloseableHttpClient httpclient = ClientCustomSSL.ssl();
logger.info("httpclient:" + httpclient);
HttpPost httpPost = new HttpPost(UNIFIED_FEEDBACK_URL);
httpPost.setEntity(new StringEntity(requestXML, "utf-8"));
System.out.println("executing request" + httpPost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStreamReader reader = new InputStreamReader(entity.getContent(),"UTF-8");
char[] buff = new char[1024];
int length = 0;
StringBuffer strxml = new StringBuffer();
while ((length = reader.read(buff)) != -1) {
strxml.append(new String(buff, 0, length));
System.out.println(new String(buff, 0, length));
}
// httpclient.close();
httpclient.getConnectionManager().shutdown();
// 解析传过来的xml
Document document = DocumentHelper.parseText(strxml.toString());
// 得到xml根元素
Element root = document.getRootElement();
// 得到根元素的所有子节点
List<Element> elementList = root.elements();
for (Element e : elementList) {
// result_code业务
if ("return_code".equals(e.getName())&& !"SUCCESS".equals(e.getText())) {
falg = false;
}
if ("result_code".equals(e.getName())&& !"SUCCESS".equals(e.getText())) {
falg = false;
}
}
response.close();
return falg;
}

 

 

//安全证书地址
public static String certPath = "cert/apiclient_cert.p12";
// 商户号
private static String mchId = "";
/**
* 验证证书公共方法
* @description
* @param certPath 证书的路径
* @param mchid 商户id
* @return
* @throws Exception
* @author Jobs
*/
public static CloseableHttpClient ssl() throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
System.out.println("keyStore:" + keyStore);
FileInputStream instream = new FileInputStream(new File(certPath));
System.out.println("instream:" + instream);
try {
keyStore.load(instream, mchId.toCharArray());
} finally {
instream.close();
}

// 相信自己的CA和所有自签名的证书
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchId.toCharArray()).build();
// 只允许使用TLSv1协议
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpclient;
}

 

/**
*@说明:将请求参数转换为xml格式的string
*/
public static String getRequestXml(SortedMap<Object, Object> parameters) {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Set<Entry<Object, Object>> es = parameters.entrySet();
Iterator<Entry<Object, Object>> it = es.iterator();
while (it.hasNext()) {
Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) it.next();
String k = (String) entry.getKey();
String v = entry.getValue().toString();
if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k)|| "sign".equalsIgnoreCase(k)) {
sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
} else {
sb.append("<" + k + ">" + v + "</" + k + ">");
}
}
sb.append("</xml>");
return sb.toString();
}

 

导出研究这个企业付款时也是各种坑,还好熬过了这些坑

*注:主要代码段是第一段,后续的那些是在网上都可以找到的工具类

写下这些希望可以帮到那些被坑过套路过的

posted on 2017-03-22 10:10  待繁华落幕  阅读(456)  评论(0编辑  收藏  举报