h5微信支付核心代码

微信支付接口文档地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1


private String httpsRequest(String total_fee, String out_trade_no, String body) throws Exception {//总价(分为单位),订单编号,订单名称

String requestUrl = weixin_url; // 微信接口地址,也就是https://api.mch.weixin.qq.com/pay/unifiedorder


// 这里构造商品订单号,价格,公众账号等数据,封装成xml格式
String outputStr = genProductArgs(total_fee, out_trade_no,body);


logger.info("weixin xml data is [{}]", outputStr);
CloseableHttpClient httpclient = HttpClients.createDefault();
try {


HttpPost httpPost = new HttpPost(requestUrl);


if (null != outputStr) {
StringEntity entity = new StringEntity(outputStr);
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
}
CloseableHttpResponse response = httpclient.execute(httpPost);
InputStream in_nocode = null;
try {
HttpEntity entity = response.getEntity();


String text = "";
StringBuffer buffer = new StringBuffer();
if (entity != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
while ((text = bufferedReader.readLine()) != null) {
buffer.append(new String(text.getBytes("GBK"), "UTF-8"));
}
}
EntityUtils.consume(entity);


String responseXml = buffer.toString();
logger.info("responseXml  data is [{}]", responseXml);
String code_url = "";

in_nocode = new ByteArrayInputStream(responseXml.getBytes());


WxUnifiedorderResponse wxUnifiedorderResponse = JAXBUtil.unmarshal(in_nocode, WxUnifiedorderResponse.class);
code_url = wxUnifiedorderResponse.getCode_url();
return code_url;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (in_nocode != null) {
in_nocode.close();
}
response.close();
}
} finally {
httpclient.close();
httpclient.getConnectionManager().shutdown();
}


return null;

}



WxUnifiedorderResponse.java代码:

package com.douwong.manage.spi.message;


import java.io.ByteArrayInputStream;
import java.io.InputStream;


import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;


import com.douwong.util.JAXBUtil;
/**
 * <xml>
  <return_code><![CDATA[SUCCESS]]></return_code>
  <return_msg><![CDATA[OK]]></return_msg>
  <appid><![CDATA[wx30fa884e887fa171]]></appid>
  <mch_id><![CDATA[1321450301]]></mch_id>
  <nonce_str><![CDATA[KUC0KI4bPwIkOmDu]]></nonce_str>
  <sign><![CDATA[020C37795F3BC6983BD914ACD0AB9EBC]]></sign>
  <result_code><![CDATA[SUCCESS]]></result_code>
  <prepay_id><![CDATA[wx20160624163803b44f8c21240669166793]]></prepay_id>
  <trade_type><![CDATA[NATIVE]]></trade_type>
  <code_url><![CDATA[weixin://wxpay/bizpayurl?pr=62IPObC]]></code_url>
</xml>
 */
@XmlRootElement(name = "xml")
@XmlAccessorType(XmlAccessType.NONE)
public class WxUnifiedorderResponse {


@XmlElement(name = "return_code")
private String return_code;

@XmlElement(name = "return_msg")
private String return_msg;

@XmlElement(name = "nonce_str")
private String nonce_str;

@XmlElement(name = "result_code")
private String result_code;

@XmlElement(name = "code_url")
private String code_url;


public String getReturn_code() {
return return_code;
}


public void setReturn_code(String return_code) {
this.return_code = return_code;
}


public String getReturn_msg() {
return return_msg;
}


public void setReturn_msg(String return_msg) {
this.return_msg = return_msg;
}


public String getNonce_str() {
return nonce_str;
}


public void setNonce_str(String nonce_str) {
this.nonce_str = nonce_str;
}


public String getResult_code() {
return result_code;
}


public void setResult_code(String result_code) {
this.result_code = result_code;
}


public String getCode_url() {
return code_url;
}


public void setCode_url(String code_url) {
this.code_url = code_url;
}


    public static void main(String[] args) {
    String s="<xml>"+
 "<return_code><![CDATA[SUCCESS]]></return_code>"+
 "<return_msg><![CDATA[OK]]></return_msg>"+
 "<appid><![CDATA[wx30fa884e887fa171]]></appid>"+
 "<mch_id><![CDATA[1321450301]]></mch_id>"+
 "<nonce_str><![CDATA[KUC0KI4bPwIkOmDu]]></nonce_str>"+
 "<sign><![CDATA[020C37795F3BC6983BD914ACD0AB9EBC]]></sign>"+
 "<result_code><![CDATA[SUCCESS]]></result_code>"+
 "<prepay_id><![CDATA[wx20160624163803b44f8c21240669166793]]></prepay_id>"+
 "<trade_type><![CDATA[NATIVE]]></trade_type>"+
 "<code_url><![CDATA[weixin://wxpay/bizpayurl?pr=62IPObC]]></code_url>"+
"</xml>";
    InputStream   in_nocode   =   new   ByteArrayInputStream(s.getBytes());   
   
    WxUnifiedorderResponse WxUnifiedorderResponse = JAXBUtil.unmarshal(in_nocode, WxUnifiedorderResponse.class);
    System.out.println("==>"+WxUnifiedorderResponse.getCode_url());
    }
}



/**

* @param total_fee
*            订单总金额:单位为分,以分为单位
* @param out_trade_no
* @param body
* @return
*/
public  String genProductArgs(String total_fee, String out_trade_no,
String body) {
List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
packageParams.add(new BasicNameValuePair("appid", weixin_appid));
packageParams.add(new BasicNameValuePair("appkey", key));
packageParams.add(new BasicNameValuePair("body", body));
packageParams.add(new BasicNameValuePair("input_charset", "UTF-8"));
packageParams.add(new BasicNameValuePair("mch_id", mch_id));
packageParams.add(new BasicNameValuePair("nonce_str", genNonceStr())); // 随机数,防止恶意攻击
packageParams.add(new BasicNameValuePair("notify_url",
notify_url)); // 微信后台通知我们的我们接口地址
// 订单号
packageParams.add(new BasicNameValuePair("out_trade_no", out_trade_no));
packageParams.add(new BasicNameValuePair("spbill_create_ip", localIp())); // 服务器ip地址
packageParams.add(new BasicNameValuePair("total_fee", total_fee)); // 订单总金额:单位为分,以分为单位
packageParams.add(new BasicNameValuePair("trade_type",
trade_type));
// 调用genXml()方法获得xml格式的请求数据
return genXml(packageParams);
}


private  String genXml(List<NameValuePair> params) {
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
sb2.append("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><xml>");
for (int i = 0; i < params.size(); i++) {
// sb是用来计算签名的
sb.append(params.get(i).getName());
sb.append('=');
sb.append(params.get(i).getValue());
sb.append('&');
// sb2是用来做请求的xml参数
sb2.append("<" + params.get(i).getName() + ">");
sb2.append(params.get(i).getValue());
sb2.append("</" + params.get(i).getName() + ">");
}
sb.append("key=");
sb.append(private_key);
String packageSign = null;
// 生成签名
packageSign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
sb2.append("<sign><![CDATA[");
sb2.append(packageSign);
sb2.append("]]></sign>");
sb2.append("</xml>");
// 这一步最关键 我们把字符转为 字节后,再使用“ISO8859-1”进行编码,得到“ISO8859-1”的字符串
try {
return new String(sb2.toString().getBytes("UTF-8"), "ISO8859-1");
} catch (Exception e) {
e.printStackTrace();
}
return "";


}


/**
* 获取本机Ip

* 通过 获取系统所有的networkInterface网络接口 然后遍历 每个网络下的InterfaceAddress组。 获得符合
* <code>InetAddress instanceof Inet4Address</code> 条件的一个IpV4地址

* @return
*/
@SuppressWarnings("rawtypes")
public String localIp() {
String ip = null;
Enumeration allNetInterfaces;
try {
allNetInterfaces = NetworkInterface.getNetworkInterfaces();
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces
.nextElement();
List<InterfaceAddress> InterfaceAddress = netInterface
.getInterfaceAddresses();
for (InterfaceAddress add : InterfaceAddress) {
InetAddress Ip = add.getAddress();
if (Ip != null && Ip instanceof Inet4Address) {
ip = Ip.getHostAddress();
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
// logger.warn("获取本机Ip失败:异常信息:"+e.getMessage());
}
return ip;
}

//生成随机字符串  
    private  String genNonceStr() {  
        Random random = new Random();  
        return  "no"+random.nextInt(10000)+"a"; 
    }  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值