1.h5页面通过这个接口获取预支付id
@RequestMapping(value = "/payOrder")
@ResponseBody
public String payOrder(HttpServletRequest request, double totalFee, String body,String openId, String attach) throws Exception {
String resultString = null;
BigDecimal fee = new BigDecimal(totalFee); // 微信支付参数以分为单位。
fee = fee.multiply(new BigDecimal(100));
String payFee = fee.longValue() + "";
//1 生成预支付id
String ipAddress = request.getRemoteAddr();
String orderNumber = System.currentTimeMillis() + new Random().nextInt(100) + "";
String openid=String.valueOf(openId);
logger.info("微信支付准备"+openid+attach+"");
try {
Map<String, String> map = PayCommonUtil.getPrepayId(payFee, ipAddress, orderNumber, body, openid,attach);
String prepay_id = map.get("prepay_id");
//2 给H5页面传递参数 调起微信支付
resultString = PayCommonUtil.createPackageValue(prepay_id);
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resultString;
}
2.H5页面代码如下:通过预支付id调起公众号支付
$.post("/douyalive/chatroom/payOrder",{totalFee:totle,body:"送出礼物——"+body,openId:getUserInfo().openId,attach:attach},function(data){
var _data=JSON.parse(data)
function onBridgeReady(){
WeixinJSBridge.invoke(
'getBrandWCPayRequest', {
"appId":_data.appId, //公众号名称,由商户传入
"timeStamp":_data.timeStamp, //时间戳,自1970年以来的秒数
"nonceStr":_data.nonceStr, //随机串
"package":_data.package,
"signType":_data.signType, //微信签名方式:
"paySign":_data.paySign //微信签名
},
function(res){
if(res.err_msg == "get_brand_wcpay_request:ok" ) {
sessionStorage.setItem("type1",2)
ChatRoom.sendGiftI();
console.log(11)
}else if(res.err_msg == "get_brand_wcpay_request:cancel"){
alert("支付取消")
}else{
alert("支付失败")
}
}
);
}
if (typeof WeixinJSBridge == "undefined"){
if( document.addEventListener ){
document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
}else if (document.attachEvent){
document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
}
}else{
onBridgeReady();
}
})
附PayCommonUtil工具类的代码
public class PayCommonUtil {
@SuppressWarnings("unused")
private static Logger log = LoggerFactory.getLogger(PayCommonUtil.class);
//微信支付统一接口(POST)
public final static String UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
public final static String APPID = "";//服务号的应用号
public final static String MCH_ID = "";//商户号
public final static String APP_SECRECT = "";
public final static String API_KEY = "";//API密钥
public final static String SIGN_TYPE = "MD5";//签名加密方式
//通知回调地址
public final static String NOTIFY_URL = "http://wx.douyamovie.com/douyawechat/notice.do";
//微信支付成功支付后跳转的地址
public final static String SUCCESS_URL = "http://wx.douyamovie.com";
//订单查询接口(POST)
public final static String CHECK_ORDER_URL = "https://api.mch.weixin.qq.com/pay/orderquery";
public static String CreateNoncestr(int length) {
String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
String res = "";
for (int i = 0; i < length; i++) {
Random rd = new Random();
res += chars.indexOf(rd.nextInt(chars.length() - 1));
}
return res;
}
public static String CreateNoncestr() {
String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
String res = "";
for (int i = 0; i < 16; i++) {
Random rd = new Random();
res += chars.charAt(rd.nextInt(chars.length() - 1));
}
return res;
}
/**
* @Description:sign签名
* @param characterEncoding 编码格式
* @param parameters 请求参数
* @return
*/
@SuppressWarnings("unchecked")
public static String createSign(String characterEncoding,SortedMap<Object,Object> parameters){
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
Object v = entry.getValue();
if(null != v && !"".equals(v)
&& !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + API_KEY);
String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;
}
/**
* @Description:将请求参数转换为xml格式的string
* @param parameters 请求参数
* @return
*/
@SuppressWarnings("unchecked")
public static String getRequestXml(SortedMap<Object,Object> parameters){
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Set es = parameters.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
String v = (String)entry.getValue();
if ("attach".equalsIgnoreCase(k)||"body".equalsIgnoreCase(k)||"sign".equalsIgnoreCase(k)) {
sb.append("<"+k+">"+"<![CDATA["+v+"]]></"+k+">");
}else {
sb.append("<"+k+">"+v+"</"+k+">");
}
}
sb.append("</xml>");
return sb.toString();
}
/**
*
* getPrepayId(调用微信统一下单接口,生成微信预支付id)
* @param totalFee 支付金额
* @param ipAddress ip地址
* @param orderNumber 订单号
* @param body 商品或支付单简要描述
* @param openid trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识
* @return
* @throws Exception
* @throws
*/
@SuppressWarnings("unchecked")
public static Map<String, String> getPrepayId(String totalFee,String ipAddress,String orderNumber,String body,String openid,String attach) throws Exception{
SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
parameters.put("appid", APPID);
parameters.put("mch_id", MCH_ID);
parameters.put("nonce_str", CreateNoncestr());
parameters.put("body", body);
parameters.put("out_trade_no", orderNumber);
parameters.put("total_fee", totalFee);
parameters.put("attach",attach);
parameters.put("spbill_create_ip",ipAddress);
parameters.put("notify_url",NOTIFY_URL);
parameters.put("trade_type", "JSAPI");
parameters.put("openid", openid);
String sign = PayCommonUtil.createSign("UTF-8", parameters);
parameters.put("sign", sign);
String requestXML = PayCommonUtil.getRequestXml(parameters);
String result =CommonUtil.httpsRequest(UNIFIED_ORDER_URL, "POST", requestXML);
log.info("getPrepayId"+result);
Map<String, String> map = XMLUtil.doXMLParse(result);//解析微信返回的信息,以Map形式存储便于取值
return map;
}
/**
*
* createPackageValue(调起支付)
* @param //appid
* @param //appKey
* @param prepay_id
* @return
* @throws
* @author 小帅帅
* @date 2016-7-5下午01:41:54
*/
public static String createPackageValue(String prepay_id) {
SortedMap<Object,Object> params = new TreeMap<Object,Object>();
params.put("appId", APPID);
params.put("timeStamp", Long.toString(new Date().getTime()));
params.put("nonceStr", PayCommonUtil.CreateNoncestr());
params.put("package", "prepay_id="+prepay_id);
params.put("signType", SIGN_TYPE);
String paySign = PayCommonUtil.createSign("UTF-8", params);
params.put("packageValue", "prepay_id="+prepay_id); //这里用packageValue是预防package是关键字在js获取值出错
params.put("paySign", paySign); //paySign的生成规则和Sign的生成规则一致
params.put("sendUrl", SUCCESS_URL); //付款成功后跳转的页面
String json = JSONObject.toJSONString(params);
log.info("createPackageValue"+json);
return json;
}
}