위 챗 애플 릿 서비스 업 체 자바 버 전 결제
10072 단어 Java위 챗 페 이 먼 트
package com.belzee.zxw.utils;
import com.alibaba.fastjson.JSONObject;
import com.belzee.zxw.model.WeixinTemplate;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;
/** */
public class WeiXinUtils {
protected static Logger logger = LoggerFactory.getLogger(WeiXinUtils.class);
/** appId*/
public static final String APPID = "";
/*** url*/
private static final String mchPayUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
/*** id*/
private static final String serverMchId="";
/*** Appid*/
private static final String serverAppId="";
/*** ApiKey*/
public static final String serverPayKey="";
/** */
private static final String tradeType="JSAPI";
public static Map toMchPay(String subMchId,String body,String detail,
String outTradeNo,Integer totalFee,String timeStart,
String subOpenid,String spbillCreateIp) {
SortedMap map = new TreeMap<>();
map.put("appid",serverAppId);
map.put("mch_id",serverMchId);
map.put("sub_appid",APPID);
map.put("sub_mch_id",subMchId);
map.put("nonce_str",PayUtil.create_nonce_str());
map.put("body",body);
//map.put("detail",detail);
map.put("out_trade_no",outTradeNo);
map.put("total_fee",totalFee+"");
map.put("trade_type",tradeType);
map.put("sub_openid",subOpenid);
map.put("spbill_create_ip",spbillCreateIp);
map.put("notify_url","https://www.xlcnp.cn/zzwweixinorder/notify");
map.put("sign",PayUtil.createSign(map));
Map headers = new HashMap<>();
headers.put("content-type", "application/json;charset=utf-8");
String s = HttpClientUtils.sendPost(mchPayUrl, headers, PayUtil.getRequestXml(map), "utf-8");
Map returnMap = new HashMap<>();
try {
returnMap = PayUtil.doXMLParse(s);
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.error("request:"+PayUtil.getRequestXml(map));
logger.error("return:"+JSONObject.toJSONString(returnMap));
return returnMap;
}
}
Pay.Util
package com.belzee.zxw.utils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
/**
*
* @author Charlie
* 2016 8 4 9:18:09
*/
public class PayUtil {
private static final String serverPayKey=WeiXinUtils.serverPayKey;
/**
*
*
* @return 2016 8 4 9:26:07
* @author Xuehao
*/
public static String create_nonce_str() {
String s = UUID.randomUUID().toString();
// “-”
return s.replaceAll("\\-", "").toUpperCase();
}
/**
*
*
* @return 2016 8 4 9:26:20
* @author Xuehao
*/
public static String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
/**
*
*
* @param params
* @param encode
* @return
* @throws UnsupportedEncodingException
*/
public static String createSign(Map params, boolean encode) throws UnsupportedEncodingException {
Set keysSet = params.keySet();
Object[] keys = keysSet.toArray();
Arrays.sort(keys);
StringBuffer temp = new StringBuffer();
boolean first = true;
for (Object key : keys) {
if (first) {
first = false;
} else {
temp.append("&");
}
temp.append(key).append("=");
Object value = params.get(key);
String valueString = "";
if (null != value) {
valueString = value.toString();
}
if (encode) {
temp.append(URLEncoder.encode(valueString, "UTF-8"));
} else {
temp.append(valueString);
}
}
return temp.toString();
}
//
public static String createSign(SortedMap parameters){
StringBuilder sb = new StringBuilder();
Set es = parameters.entrySet();
for (Object e : es) {
Map.Entry entry = (Map.Entry) e;
String k = (String) entry.getKey();
Object v = entry.getValue();
if (null != v && !"".equals(v)
&& !"sign".equals(k) && !"key".equals(k)) {
sb.append(k).append("=").append(v).append("&");
}
}
sb.append("key=").append(serverPayKey);
System.out.println(sb.toString());
return MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
}
// xml
public static String getRequestXml(SortedMap parameters){
StringBuilder sb = new StringBuilder();
sb.append("");
Set es = parameters.entrySet();
for (Object e : es) {
Map.Entry entry = (Map.Entry) e;
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if ("attach".equalsIgnoreCase(key) || "body".equalsIgnoreCase(key) || "sign".equalsIgnoreCase(key)) {
sb.append("").append("").append(key).append(">");
} else {
sb.append("").append(value).append("").append(key).append(">");
}
}
sb.append(" ");
return sb.toString();
}
//xml
public static Map doXMLParse(String strxml) throws JDOMException, IOException {
strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
if(null == strxml || "".equals(strxml)) {
return null;
}
Map m = new HashMap();
InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(in);
Element root = doc.getRootElement();
List list = root.getChildren();
for (Object aList : list) {
Element e = (Element) aList;
String k = e.getName();
String v = "";
List children = e.getChildren();
if (children.isEmpty()) {
v = e.getTextNormalize();
} else {
v = getChildrenText(children);
}
m.put(k, v);
}
//
in.close();
return m;
}
private static String getChildrenText(List children) {
StringBuilder sb = new StringBuilder();
if(!children.isEmpty()) {
for (Object aChildren : children) {
Element e = (Element) aChildren;
String name = e.getName();
String value = e.getTextNormalize();
List list = e.getChildren();
sb.append("");
if (!list.isEmpty()) {
sb.append(getChildrenText(list));
}
sb.append(value);
sb.append("").append(name).append(">");
}
}
return sb.toString();
}
/**
*
* @param map
* @return
*/
public static boolean isTenpaySign(Map map) {
String charset = "utf-8";
String signFromAPIResponse = map.get("sign");
if (signFromAPIResponse == null || signFromAPIResponse.equals("")) {
System.out.println("API , !!!");
return false;
}
System.out.println(" :" + signFromAPIResponse);
// TreeMap
SortedMap packageParams = new TreeMap<>();
for (String parameter : map.keySet()) {
String parameterValue = map.get(parameter);
String v = "";
if (null != parameterValue) {
v = parameterValue.trim();
}
packageParams.put(parameter, v);
}
StringBuilder sb = new StringBuilder();
Set es = packageParams.entrySet();
for (Object e : es) {
Map.Entry entry = (Map.Entry) e;
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if (!"sign".equals(k) && null != v && !"".equals(v)) {
sb.append(k).append("=").append(v).append("&");
}
}
sb.append("key=").append(serverPayKey);
// API , API
//
String tobesign = sb.toString();
String resultSign = MD5Util.MD5Encode(tobesign, "utf-8").toUpperCase();
String tenpaySign = packageParams.get("sign").toUpperCase();
return tenpaySign.equals(resultSign);
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.