当前位置:   article > 正文

java微信支付测试秘钥_微信支付——沙箱调试环境getsignkey方法秘钥获取及常见问题说明...

weixin_sign_key

packagecom.jetcms.weixinpay;importorg.apache.commons.lang.StringUtils;importorg.jdom.Document;importorg.jdom.Element;importorg.jdom.JDOMException;importorg.jdom.input.SAXBuilder;import java.io.*;importjava.net.MalformedURLException;importjava.net.URL;importjava.net.URLConnection;importjava.security.MessageDigest;import java.util.*;public classgetSignKeyUtils {/*** 获取微信支付沙箱API验签密钥 (调用该方法生成)

*@paramnonce_str 随机字符串 生成方法:RandomStringUtils.random(10, N62_CHARS);

*@parammchId 正式的商户号

*@paramapiKey 正式的密钥

*@return

*/

public staticString getSignKey(String nonce_str,String mchId,String apiKey) {

Map param = new HashMap();

param.put("mch_id", mchId);//需要真实商户号

param.put("nonce_str", nonce_str);//随机字符

String sign = createSign(param, apiKey);//通过SDK生成签名其中API_KEY为商户对应的真实密钥

param.put("sign", sign);

String xml= assembParamToXml(param);//将map转换为xml格式

String url = "https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey";//沙箱密钥获取api

Map param1 = new HashMap();

String resXml=post(url, xml);try{if(StringUtils.isNotBlank(resXml)) {

param1=parseXMLToMap(resXml);

}

}catch(Exception e) {

e.printStackTrace();

}

String key= param1.get("sandbox_signkey");returnkey;

}/*** 微信支付签名sign

*@paramparam

*@paramkey

*@return

*/@SuppressWarnings("unchecked")public static String createSign(Mapparam,String key){//签名步骤一:按字典排序参数

List list=newArrayList(param.keySet());

Object[] ary=list.toArray();

Arrays.sort(ary);

list=Arrays.asList(ary);

String str="";for(int i=0;i

str+=list.get(i)+"="+param.get(list.get(i)+"")+"&";

}//签名步骤二:加上key

str+="key="+key;//步骤三:加密并大写

str= MD5Encode(str,"utf-8").toUpperCase();returnstr;

}/*** 将需要传递给微信的参数转成xml格式

*@paramparameters

*@return

*/

public static String assembParamToXml(Mapparameters){

StringBuffer sb= newStringBuffer();

sb.append("");

Set es =parameters.keySet();

List list=new ArrayList(es);

Object[] ary=list.toArray();

Arrays.sort(ary);

list=Arrays.asList(ary);

Iterator it =list.iterator();while(it.hasNext()) {

String key=(String) it.next();

String val=(String) parameters.get(key);if ("attach".equalsIgnoreCase(key)||"body".equalsIgnoreCase(key)||"sign".equalsIgnoreCase(key)) {

sb.append(""+""+key+">");

}else{

sb.append(""+val+""+key+">");

}

}

sb.append("");returnsb.toString();

}public staticString post(String urlStr,String xmlInfo) {

String line1= "";try{

URL url= newURL(urlStr);

URLConnection con=url.openConnection();

con.setDoOutput(true);

con.setRequestProperty("Cache-Control", "no-cache");

con.setRequestProperty("Content-Type", "text/xml");

OutputStreamWriter out= newOutputStreamWriter(con

.getOutputStream());

out.write(new String(xmlInfo.getBytes("utf-8")));

out.flush();

out.close();

BufferedReader br= new BufferedReader(newInputStreamReader(con

.getInputStream()));

String line= "";for (line = br.readLine(); line != null; line =br.readLine()) {

line1+=line;

}return new String(line1.getBytes(),"utf-8");

}catch(MalformedURLException e) {

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}return null;

}/*** 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。

*@paramstrxml

*@return*@throwsJDOMException

*@throwsIOException*/

public static Map parseXMLToMap(String strxml) throwsJDOMException, IOException {

strxml= strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");if(null == strxml || "".equals(strxml)) {return null;

}

Map m= newHashMap();

InputStream in= new ByteArrayInputStream(strxml.getBytes("UTF-8"));

SAXBuilder builder= newSAXBuilder();

Document doc=builder.build(in);

Element root=doc.getRootElement();

List list=root.getChildren();

Iterator it=list.iterator();while(it.hasNext()) {

Element e=(Element) it.next();

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();returnm;

}/*** 62个字母和数字,含大小写*/

public static final char[] N62_CHARS = {'0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W','X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w','x', 'y', 'z'};public staticString MD5Encode(String origin,String charsetName){

String resultString=null;try{

resultString=newString(origin);

MessageDigest md=MessageDigest.getInstance("MD5");if(StringUtils.isBlank(charsetName)){

resultString=byteArrayToHexString(md.digest(resultString.getBytes()));

}else{

resultString=byteArrayToHexString(md.digest(resultString.getBytes(charsetName)));

}

}catch(Exception e){

}returnresultString;

}public static String byteArrayToHexString(byteb[]){

StringBuffer resultSb=newStringBuffer();for(int i=0;i

resultSb.append(byteToHexString(b[i]));

}returnresultSb.toString();

}/*** 获取子结点的xml

*@paramchildren

*@returnString*/

public staticString getChildrenText(List children) {

StringBuffer sb= newStringBuffer();if(!children.isEmpty()) {

Iterator it=children.iterator();while(it.hasNext()) {

Element e=(Element) it.next();

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("" + name + ">");

}

}returnsb.toString();

}public static String byteToHexString(byteb){int n=b;if(n<0){

n+=256;

}int d1=n/16;int d2=n%16;return hexDigits[d1]+hexDigits[d2];

}public static final String hexDigits[]={ "0", "1", "2", "3", "4", "5","6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/186224
推荐阅读
相关标签
  

闽ICP备14008679号