微信原生支付(native)模式二
最近搞掃碼支付,下面把參考各種資料做出來的微信原生支付模式二的方法貼出來,以供參考。
- 函數入口
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<String, Object> postDate = new TreeMap<String, Object>();
// 生成訂單所需參數
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<String, Object> m = new TreeMap<String, Object>();
m = XMLUtil.doXMLParse(sb.toString());
//過濾空 設置 TreeMap
SortedMap<String,Object> packageParams = new TreeMap<String,Object>();
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 = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
} else {
System.out.println("支付失敗,錯誤信息:" + packageParams.get("err_code"));
resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
+ "<return_msg><![CDATA[報文爲空]]></return_msg>" + "</xml> ";
}
//------------------------------
//處理業務完畢
//------------------------------
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<String,Object> map,String key){
ArrayList<String> list = new ArrayList<String>();
for(Map.Entry<String,Object> 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<String, Object> date){
StringBuffer sbxml = new StringBuffer("<xml>");
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("<" + k + ">" + "<![CDATA[" + v + "]]></"
+ k + ">");
} else {
sbxml.append("<" + k + ">" + v + "</" + k + ">");
}
}
}
sbxml.append("</xml>");
return sbxml.toString();
}
/**
* 解析xml,返回第一級元素鍵值對。如果第一級元素有子節點,則此節點的值是子節點的xml數據。
* @param strxml
* @return
* @throws JDOMException
* @throws IOException
*/
public static SortedMap doXMLParse(String strxml) throws JDOMException, IOException {
strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
if(null == strxml || "".equals(strxml)) {
return null;
}
SortedMap m = new TreeMap();
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();
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 = XMLUtil.getChildrenText(children);
}
m.put(k, v);
}
//關閉流
in.close();
return m;
}
/**
* 獲取子結點的xml
* @param children
* @return String
*/
public static String getChildrenText(List children) {
StringBuffer sb = new StringBuffer();
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("<" + name + ">");
if(!list.isEmpty()) {
sb.append(XMLUtil.getChildrenText(list));
}
sb.append(value);
sb.append("</" + name + ">");
}
}
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<EncodeHintType,String> hints = new HashMap<EncodeHintType,String>();
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;
}
}
以上內容爲本人自己參考各種資料實現出來的,僅供參考,不喜勿噴。如有發現錯誤,歡迎指正。