您的位置:首页 > 移动开发 > 微信开发

微信扫码支付(模式一)

2016-12-28 14:36 381 查看
生成支付路径:

HttpServletResponse response;

public static int defaultWidthAndHeight=200;

// 选择价格查看详情列表
@RequestMapping("GetQrCode")
public @ResponseBody String GetQrCode(HttpServletRequest request) throws IOException{
System.out.println("---------------GetQrCode------------------");
// TODO Auto-generated method stub
String nonce_str = PayCommonUtil.getNonce_str();
long time_stamp = System.currentTimeMillis() / 1000;
String product_id = "cheyibai_dashang_105";
String key = PayConfigUtil.API_KEY; // key

SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
packageParams.put("appid", PayConfigUtil.APP_ID);
packageParams.put("mch_id", PayConfigUtil.MCH_ID);
packageParams.put("time_stamp", String.valueOf(time_stamp));
packageParams.put("nonce_str", nonce_str);
packageParams.put("product_id", product_id);
String sign = PayCommonUtil.createSign("UTF-8", packageParams,key);//MD5哈希
packageParams.put("sign", sign);

//生成参数
String str = ToUrlParams(packageParams);
String payurl = "weixin://wxpay/bizpayurl?" + str;
//        logger.info("payurl:"+payurl);
System.out.println("payurl:"+payurl);

//        //生成二维码
//        Map<EncodeHintType, Object>  hints=new HashMap<EncodeHintType, Object>();
//        // 指定纠错等级
//        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
//        // 指定编码格式
//        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//        hints.put(EncodeHintType.MARGIN, 1);
//        try {
//            BitMatrix bitMatrix = new MultiFormatWriter().encode(payurl,BarcodeFormat.QR_CODE, defaultWidthAndHeight, defaultWidthAndHeight, hints);
//            OutputStream out = response.getOutputStream();
//            MatrixToImageWriter.writeToStream(bitMatrix, "png", out);//输出二维码
//            out.flush();
//            out.close();
//
//        } catch (WriterException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }

return payurl;

public String ToUrlParams(SortedMap<Object, Object> packageParams){
//实际可以不排序
StringBuffer sb = new StringBuffer();
@SuppressWarnings("rawtypes")
Set es = packageParams.entrySet();
@SuppressWarnings("rawtypes")
Iterator it = es.iterator();
while (it.hasNext()) {
@SuppressWarnings("rawtypes")
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if (null != v && !"".equals(v)) {
sb.append(k + "=" + v + "&");
}
}

sb.deleteCharAt(sb.length()-1);//删掉最后一个&
return sb.toString();
}

回调函数:

@RequestMapping("NativeCallBack")
public @ResponseBody String NativeCallBack(HttpServletRequest request) throws IOException{
System.out.println("---------------NativeCallBack------------------");
// 读取xml
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();

SortedMap<Object, Object> packageParams = PayCommonUtil.xmlConvertToMap(sb.toString());
System.out.println(packageParams);

// 账号信息
String key = PayConfigUtil.API_KEY; // key

String resXml="";//反馈给微信服务器
// 验签
if (PayCommonUtil.isTenpaySign("UTF-8", packageParams, key)) {
//appid openid mch_id is_subscribe nonce_str product_id sign

//统一下单
String openid = (String)packageParams.get("openid");
String product_id = (String)packageParams.get("product_id");
//解析product_id,计算价格等

String out_trade_no = String.valueOf(System.currentTimeMillis()); // 订单号
String order_price = "1"; // 价格   注意:价格的单位是分
String body = product_id;   // 商品名称  这里设置为product_id
String attach = "XXX店"; //附加数据

String nonce_str0 = PayCommonUtil.getNonce_str();

// 获取发起电脑 ip
String spbill_create_ip = PayConfigUtil.CREATE_IP;
String trade_type = "NATIVE";

SortedMap<Object,Object> unifiedParams = new TreeMap<Object,Object>();
unifiedParams.put("appid", PayConfigUtil.APP_ID); // 必须
unifiedParams.put("mch_id", PayConfigUtil.MCH_ID); // 必须
unifiedParams.put("out_trade_no", out_trade_no); // 必须
unifiedParams.put("product_id", product_id);
unifiedParams.put("body", body); // 必须
unifiedParams.put("attach", attach);
unifiedParams.put("total_fee", order_price);  // 必须
unifiedParams.put("nonce_str", nonce_str0);  // 必须
unifiedParams.put("spbill_create_ip", spbill_create_ip); // 必须
unifiedParams.put("trade_type", trade_type); // 必须
unifiedParams.put("openid", openid);
unifiedParams.put("notify_url", PayConfigUtil.NOTIFY_URL);//异步通知url

String sign0 = PayCommonUtil.createSign("UTF-8", unifiedParams,key);
unifiedParams.put("sign", sign0); //签名

String requestXML = PayCommonUtil.getRequestXml(unifiedParams);
System.out.println(requestXML);
//统一下单接口
String rXml = HttpUtil.postData(PayConfigUtil.UFDODER_URL, requestXML);

//统一下单响应
SortedMap<Object, Object> reParams = PayCommonUtil.xmlConvertToMap(rXml);
System.out.println(reParams);

//验签
if (PayCommonUtil.isTenpaySign("UTF-8", reParams, key)) {
// 统一下单返回的参数
String prepay_id = (String)reParams.get("prepay_id");//交易会话标识  2小时内有效

String nonce_str1 = PayCommonUtil.getNonce_str();

SortedMap<Object,Object> resParams = new TreeMap<Object,Object>();
resParams.put("return_code", "SUCCESS"); // 必须
resParams.put("return_msg", "OK");
resParams.put("appid", PayConfigUtil.APP_ID); // 必须
resParams.put("mch_id", PayConfigUtil.MCH_ID);
resParams.put("nonce_str", nonce_str1); // 必须
resParams.put("prepay_id", prepay_id); // 必须
resParams.put("result_code", "SUCCESS"); // 必须
resParams.put("err_code_des", "OK");

String sign1 = PayCommonUtil.createSign("UTF-8", resParams,key);
resParams.put("sign", sign1); //签名

resXml = PayCommonUtil.getRequestXml(resParams);
System.out.println(resXml);

}else{
System.out.println("签名验证错误");
resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
+ "<return_msg><![CDATA[签名验证错误]]></return_msg>" + "</xml> ";
}

}else{
System.out.println("签名验证错误");
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();
return resXml;
}

相关的参数配置:

public class PayConfigUtil {

//以下相关参数需要根据自己实际情况进行配置
public static String APP_ID = "wxa81b573eefc9de5a";// appid

public static String APP_SECRET = "7bc91419829a49aa21ff75f02900b673";// appsecret
public static String MCH_ID = "1427282902";// 你的商业号
public static String API_KEY = "7bc91419829a49aa21ff75f02900b673";// API key

public static String CREATE_IP = "8.8.8.8";// key
public static String UFDODER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";//统一下单接口
//异步通知回调地址(并不是支付的回调地址,而是支付成功之后的回调地址,这个地址只在代码中设置)
public static String NOTIFY_URL = "http://admin.xiaobaigouche.com/cybNoviceMall/pay/Re_notify/";
}

支付成功后微信服务器异步通知我们最终结果的接口:

// 异步通知url接口
@RequestMapping("Re_notify")
public @ResponseBody String Re_notify(HttpServletRequest request) throws IOException{
// 读取参数
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();

SortedMap<Object, Object> packageParams = PayCommonUtil.xmlConvertToMap(sb.toString());
System.out.println(packageParams);

// 账号信息
String key = PayConfigUtil.API_KEY; // key

String resXml = ""; // 反馈给微信服务器
// 判断签名是否正确
if (PayCommonUtil.isTenpaySign("UTF-8", packageParams, key)) {
// ------------------------------
// 处理业务开始
// ------------------------------
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> ";
}

} else {
System.out.println("签名验证错误");
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();

return resXml;
}

将支付路径生成为二维码,使用微信扫一扫,就能进行支付了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: