最近搞扫码支付,下面把参考各种资料做出来的微信原生支付模式二的方法贴出来,以供参考。
函数入口
public String createQrCode() {
String qrCodeUrl = weChatPayService.payNative2();
if (StringUtil.isEmpty(qrCodeUrl)) {
flag = false;
} else {
String path = ServletActionContext.getRequest().getSession()
.getServletContext().getRealPath("/")
+ "/" + "qrCode";
flag = QrcodeUtil.createQrcode(qrCodeUrl, path, "付款二维码");
}
return SUCCESS;
}
weChatPayService
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
public class WeChatPayServiceImpl implements IWeChatPayService {
@Override
public String createPayment(String xml) {
String resXml = HttpUtil.postData(CommonValue.gateUrl, xml, null);
return resXml;
}
@Override
public String payNative2() {
// TODO 生成订单
// 生成订单结束
// 调用统一下单
String qrCodeUrl = "";
HttpServletRequest request = ServletActionContext.getRequest();
StringBuilder addr = new StringBuilder("http://");
addr.append(request.getServerName());// 服务器IP地址
if (request.getServerPort() != 80) {
addr.append(":" + request.getServerPort());// 端口号
}
addr.append(request.getContextPath() + "/");// 项目名
String notifyUrl = addr.toString() + "qrCreate!wxNotify.action";
SortedMap postDate = new TreeMap();
// 生成订单所需参数
postDate.put("appid", CommonValue.APPID);// 微信分配的公众账号 ID
postDate.put("mch_id", CommonValue.MCH_ID);// 微信支付分配的商户号
postDate.put("nonce_str", "linchuncheng");// 随机字符串,随便填,String(32)
postDate.put("body", "支付测试");// 商品描述,String(32)
postDate.put("notify_url",notifyUrl);// 接收微信支付异步通知回调地址
postDate.put("trade_type", "NATIVE");// 交易类型
postDate.put("total_fee", "1");// 总费用,整数,单位:分
postDate.put("product_id", "123456");// 商品id,商户自行定义
postDate.put("out_trade_no", "123114");// 商户系统内部的订单号,商户自行定义
postDate.put("spbill_create_ip", "127.0.0.1");// 提交订单的IP(本地ip),这里不该填127.0.0.1.应填实际的本地外网ip。但本人实验时由于是公司内网,填的ip有效无效没有考证
// 生成签名
String sign = "";
sign = Signature.getSign(postDate, CommonValue.KEY);
postDate.put("sign", sign);
// 将postDate转化成xml
String xml = XMLUtil.parseToXML(postDate);
System.out.println(xml);
String resXml = "";
resXml = createPayment(xml);
System.out.println(resXml);
// 处理结果
try {
Document doc = DocumentHelper.parseText(resXml);
if ("FAIL".equals(doc.getRootElement().element("return_code")
.getText())) {
System.out.println(doc.getRootElement().element("return_msg")
.getText());
} else if ("SUCCESS".equals(doc.getRootElement()
.element("return_code").getText())) {
if ("SUCCESS".equals(doc.selectSingleNode("/xml/result_code")
.getText())) {
qrCodeUrl = doc.selectSingleNode("/xml/code_url").getText();
}else if ("FAIL".equals(doc.selectSingleNode("/xml/result_code").getText())) {
System.out.println("err_code:" + doc.selectSingleNode("/xml/err_code").getText());
System.out.println("err_code_des:" + doc.selectSingleNode("/xml/err_code_des").getText());
}
}
return qrCodeUrl;
} catch (DocumentException e) {
e.printStackTrace();
}
return null;
}
public void weixin_notify() throws Exception{
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
//读取参数
InputStream inputStream ;
StringBuffer sb = new StringBuffer();
inputStream = request.getInputStream();
String s ;
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
while ((s = in.readLine()) != null){
sb.append(s);
}
in.close();
inputStream.close();
//解析xml成map
SortedMap m = new TreeMap();
m = XMLUtil.doXMLParse(sb.toString());
//过滤空 设置 TreeMap
SortedMap packageParams = new TreeMap();
Iterator it = m.keySet().iterator();
while (it.hasNext()) {
String parameter = (String) it.next();
Object parameterValue = m.get(parameter);
String v = "";
if(null != parameterValue) {
v = parameterValue.toString().trim();
}
packageParams.put(parameter, v);
}
// 账号信息
String key = CommonValue.KEY; // key
//判断签名是否正确
if(Signature.isWxSign("UTF-8", packageParams)) {
//------------------------------
//处理业务开始
//------------------------------
String resXml = "";
if("SUCCESS".equals((String)packageParams.get("result_code"))){
// 这里是支付成功
//////////执行自己的业务逻辑////////////////
String mch_id = (String)packageParams.get("mch_id");
String openid = (String)packageParams.get("openid");
String is_subscribe = (String)packageParams.get("is_subscribe");
String out_trade_no = (String)packageParams.get("out_trade_no");
String total_fee = (String)packageParams.get("total_fee");
System.out.println("mch_id:"+mch_id);
System.out.println("openid:"+openid);
System.out.println("is_subscribe:"+is_subscribe);
System.out.println("out_trade_no:"+out_trade_no);
System.out.println("total_fee:"+total_fee);
//////////执行自己的业务逻辑////////////////
System.out.println("支付成功");
//通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
resXml = "" + " "
+ " " + " ";
} else {
System.out.println("支付失败,错误信息:" + packageParams.get("err_code"));
resXml = "" + " "
+ " " + " ";
}
//------------------------------
//处理业务完毕
//------------------------------
BufferedOutputStream out = new BufferedOutputStream(
response.getOutputStream());
out.write(resXml.getBytes());
out.flush();
out.close();
} else{
System.out.println("通知签名验证失败");
}
}
}
被service引用的工具方法
public static String postData(String urlStr, String data, String contentType) {
BufferedReader reader = null;
try {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(CONNECT_TIMEOUT);
if (contentType != null)
conn.setRequestProperty("content-type", contentType);
OutputStreamWriter writer = new OutputStreamWriter(
conn.getOutputStream(), CommonValue.DEFAULT_ENCODING);
if (data == null)
data = "";
writer.write(data);
writer.flush();
writer.close();
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream(), CommonValue.DEFAULT_ENCODING));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\r\n");
}
return sb.toString();
} catch (IOException e) {
System.out.println("Error connecting to " + urlStr + ": "
+ e.getMessage());
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
}
}
return null;
}
public static String getSign(Map map,String key){
ArrayList list = new ArrayList();
for(Map.Entry entry:map.entrySet()){
if(entry.getValue()!=""){
list.add(entry.getKey() + "=" + entry.getValue() + "&");
}
}
int size = list.size();
String [] arrayToSort = list.toArray(new String[size]);
Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < size; i ++) {
sb.append(arrayToSort[i]);
}
String result = sb.toString();
result += "key=" + key;
//Util.log("Sign Before MD5:" + result);
result = MD5.MD5Encode(result).toUpperCase();
//Util.log("Sign Result:" + result);
return result;
}
public static String parseToXML(SortedMap date){
StringBuffer sbxml = new StringBuffer("");
Iterator it = date.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if (null != v && !"".equals(v) && !"appkey".equals(k)) {
if ("attach".equalsIgnoreCase(k)
|| "body".equalsIgnoreCase(k)
|| "sign".equalsIgnoreCase(k)) {
sbxml.append("<" builder="new" children="" doc="builder.build(in);" document="" e="(Element)" element="" else="" encoding="\"UTF-8\"");" in="new" inputstream="" ioexception="" it="children.iterator();" iterator="" jdomexception="" k="e.getName();" list="e.getChildren();" m="new" name="" null="=" param="" public="" return="" root="doc.getRootElement();" saxbuilder="" sb="new" sortedmap="" static="" string="" stringbuffer="" strxml="" throws="" v="XMLUtil.getChildrenText(children);" value="e.getTextNormalize();" xml="">");
}
}
return sb.toString();
}
生成二维码
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
public class QrcodeUtil {
/**
* 功能描述:生成二维码
*/
public static boolean createQrcode(String content,String path,String fileName) {
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400,hints);
File dir = new File(path);
if(!dir.exists()){
dir.mkdirs();
}
File file1 = new File(path,fileName+".jpg");
MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
以上内容为本人自己参考各种资料实现出来的,仅供参考,不喜勿喷。如有发现错误,欢迎指正。