微信支付

/* 点击立即抢购 */     H5页面调用支付

         <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>

$(".immediately img").click(function() {

var sellerNumberId = $("#sellerId").val();
var openid = $("#openid").val();
var qrcode = $("#qrcode").val();
var oneMoneyId = $("#oneMoneyId").val();
var oneMoneyWxUserId = $("#oneMoneyWxUserId").val();
$.ajax({
type: "GET",
url: "${basePath}/index/WxConfig",
async: true,
dataType: "json",
data: {
"locationUrl": location.href
},
success: function(config) {
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: config.appId, // 必填,公众号的唯一标识
timestamp: config.timestamp, // 必填,生成签名的时间戳
nonceStr: config.nonceStr, // 必填,生成签名的随机串
signature: config.signature, // 必填,签名,见附录1
jsApiList: ['chooseWXPay'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
wx.ready(function() {
$.ajax({
type: "GET",
url: "${basePath}/oneMoneyShop/payPurchase",
async: false,
dataType: "json",
data: {
"oneMoneyWxUserId": oneMoneyWxUserId,
"sellerNumberId": sellerNumberId,
"openid": openid
},
success: function(data) {
if(data.result == "true") {
wx.chooseWXPay({
timestamp: data.timestamp, // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
nonceStr: data.nonceStr, // 支付签名随机串,不长于 32 位
package: data.prepay_id, // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=***)
signType: data.signType, // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
paySign: data.paySign, // 支付签名
success: function(res) {
// 支付成功后的回调函数
// 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回    ok,但并不保证它绝对可靠。
location.href = "${basePath}/oneMoneyShop/inviteFriend?oneMoneyWxUserId=" + oneMoneyWxUserId + "&oneMoneyId=" + oneMoneyId + "&sellerNumberId=" + sellerNumberId + "&qrcode=" + qrcode + "&openId=" + openid;
}
});
} else {
alert("网络错误,请退出后从新再试");
}
}
});
});
}
});
});


//这里开始掉用支付  这里的调用链接必须在商户平台里注册一下

Random r = new Random(1000);

//一元购的订单
String out_trade_no = "money" + (r.nextInt() * 100) + newDateByYMD();
String mchId = spn.getShopNumber(); //商户号
String appId = spn.getAppId();
// 判断是否已经支付
map = WxConfigUitils.getWxConfigUitils().wxPay(openid, appId, spn.getPayKey(), mchId,
“支付的钱”, getRequest().getRemoteAddr(), out_trade_no);
map.put("result", "true");
map.put("mchId", mchId);
map.put("out_trade_no", out_trade_no);

renderJson(map);


/**
* 微信公众号支付

* @return
*/
public Map<String, String> wxPay(String openid, String appid, String key, String mch_id, String money, String ip,
String outTradeNo) {
System.out.println("调用微信支付*****************appid>"+appid);
// 商品描述
String body = "en";
// 订单号
String out_trade_no = outTradeNo;
// 支付金额
BigDecimal re1 = new BigDecimal(money);
BigDecimal re2 = new BigDecimal(Float.toString(100.00f));
Float aa = re1.multiply(re2).floatValue();
String total_fee = String.valueOf(aa);
String[] smill = total_fee.split("\\.");
total_fee = smill[0];
// 终端IP
String spbill_create_ip = ip;
// 异步接收微信支付结果通知的回调地址  支付成功之后 可以在回调地址里处理相应的业务逻辑
String notify_url = "http://"+PropKit.use("system.properties").get("http")+JFinal.me().getContextPath()+"/wxpayxml/analysisXml";
// 交易类型
String trade_type = "JSAPI";
// 随机串
String nonce_str = UUID.randomUUID().toString().substring(0, 32);
// 时间戳
String timestamp = create_timestamp();
// 签名类型
String signType = "MD5";
Map<String, String> map = new HashMap<String, String>();
map.put("appid", appid);
log.error("微信支付-微信APPID="+appid);
map.put("mch_id", mch_id);
log.error("微信支付-商户号="+mch_id);
map.put("nonce_str", nonce_str);
log.error("微信支付-随机串="+nonce_str);
map.put("body", body);
log.error("微信支付-商品描述="+body);
map.put("out_trade_no", out_trade_no);
log.error("微信支付-订单号="+out_trade_no);
map.put("total_fee", total_fee);
log.error("微信支付-需要支付金额(换算后)="+total_fee);
map.put("spbill_create_ip", spbill_create_ip);
log.error("微信支付-终端IP="+spbill_create_ip);
map.put("notify_url", notify_url);
log.error("微信支付-异步接收微信支付结果通知的回调地址="+notify_url);
map.put("trade_type", trade_type);
log.error("微信支付-交易类型="+trade_type);
map.put("openid", openid);
log.error("微信支付-用户OPENID="+openid);
// 支付签名
String paySign = null;
// 预付商品id
String prepayid = "";
try {
paySign = getPayCustomSign(map, key);
map.put("sign", paySign);
log.error("微信支付-统一下单签名="+paySign);
String xml = ArrayToXml(map);
log.error("微信支付-统一下单转XML="+xml);
// 统一下单
String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
String xmlStr = HttpKit.post(url, xml);
log.error("微信支付-统一下单="+xmlStr);
if (xmlStr.indexOf("SUCCESS") != -1) {
Map<String, String> map2 = doXMLParse(xmlStr);
prepayid = (String) map2.get("prepay_id");
}
log.error("微信支付-预付商品id="+prepayid);
} catch (Exception e) {
e.printStackTrace();
}
// 封装h5页面调用参数
Map<String, String> signMap = new HashMap<String, String>();
signMap.put("appId", appid);
signMap.put("timeStamp", timestamp + "");
signMap.put("package", "prepay_id=" + prepayid);
signMap.put("signType", "MD5");
signMap.put("nonceStr", nonce_str);
String paySigntwo = null;
try {
paySigntwo = getPayCustomSign(signMap, key);
log.error("微信支付-支付密钥="+key);
log.error("微信支付-支付签名="+paySigntwo);
} catch (Exception e) {
e.printStackTrace();
}
Map<String, String> paymap = new HashMap<String, String>();
paymap.put("timestamp", timestamp);
paymap.put("nonceStr", nonce_str);
paymap.put("prepay_id", "prepay_id=" + prepayid);
paymap.put("signType", signType);
paymap.put("paySign", paySigntwo);
return paymap;

}



/**
* 获取支付所需签名

* @param ticket
* @param timeStamp
* @param card_id
* @param code
* @return
* @throws Exception
*/
public static String getPayCustomSign(Map<String, String> bizObj, String key) throws Exception {
String bizString = FormatBizQueryParaMap(bizObj, false);
return sign(bizString, key);

}


/**
* 字典排序

* @param paraMap
* @param urlencode
* @return
* @throws Exception
*/
public static String FormatBizQueryParaMap(Map<String, String> paraMap, boolean urlencode) throws Exception {
String buff = "";
try {
List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(paraMap.entrySet());
Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
return (o1.getKey()).toString().compareTo(o2.getKey());
}
});
for (int i = 0; i < infoIds.size(); i++) {
Map.Entry<String, String> item = infoIds.get(i);
if (item.getKey() != "") {
String key = item.getKey();
String val = item.getValue();
if (urlencode) {
val = URLEncoder.encode(val, "utf-8");
}
buff += key + "=" + val + "&";
}
}
if (buff.isEmpty() == false) {
buff = buff.substring(0, buff.length() - 1);
}
} catch (Exception e) {
throw new Exception(e.getMessage());
}
return buff;

}


public static String sign(String content, String key) throws Exception {
String signStr = "";
signStr = content + "&key=" + key;
return MD5(signStr).toUpperCase();
}


public final static String MD5(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
try {
byte[] btInput = s.getBytes("utf-8");
MessageDigest mdInst = MessageDigest.getInstance("MD5");
mdInst.update(btInput);
byte[] md = mdInst.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}


public static String ArrayToXml(Map<String, String> arr) {
String xml = "<xml>";
Iterator<Entry<String, String>> iter = arr.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
String key = entry.getKey();
String val = entry.getValue();
if (IsNumeric(val)) {
xml += "<" + key + ">" + val + "</" + key + ">";
} else
xml += "<" + key + "><![CDATA[" + val + "]]></" + key + ">";
}
xml += "</xml>";
return xml;
}


public static boolean IsNumeric(String str) {
if (str.matches("\\d *")) {
return true;
} else {
return false;
}
}


public static Map<String, String> doXMLParse(String xml) throws XmlPullParserException, IOException {
InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
Map<String, String> map = null;
XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser();
pullParser.setInput(inputStream, "UTF-8");// 为xml设置要解析的xml数据
int eventType = pullParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
map = new HashMap<String, String>();
break;
case XmlPullParser.START_TAG:
String key = pullParser.getName();
if (key.equals("xml"))
break;
String value = pullParser.nextText();
map.put(key, value);
break;
case XmlPullParser.END_TAG:
break;
}
eventType = pullParser.next();
}
return map;

}



//这里是回调

  package com.activity.common.utils.wxInterface;


import java.io.BufferedOutputStream;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;


import com.activity.common.controller.moblie.base.BaseController;
import com.activity.common.controller.moblie.shareBargain.ShareBargainController;
import com.activity.common.model.WxPayResult;
import com.activity.common.model.activity.ProductWinningInfo;
import com.activity.common.model.groupPurchase.GroupPurchase;
import com.activity.common.model.groupPurchase.GroupPurchaseGroupWxUser;
import com.activity.common.model.groupPurchase.GroupPurchaseWxUser;
import com.activity.common.model.oneMoneyShop.OneMoneyGroupWxUser;
import com.activity.common.model.oneMoneyShop.OneMoneyShop;
import com.activity.common.model.oneMoneyShop.OneMoneyWxUser;
import com.activity.common.model.publicNumber.SellerPublicNumber;
import com.activity.common.model.shareBargain.ShareBargainWxuser;
import com.activity.common.service.shareBargain.ShareBargainWxuserService;
import com.jfinal.aop.Clear;
import com.jfinal.core.JFinal;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.web.Interceptor.LoginInterceptor;
import com.web.controller.ControllerPath;


@ControllerPath(controllerKey = "/wxpayxml")
public class PayNotify extends BaseController {
private final Logger log = LoggerFactory.getLogger(ShareBargainController.class);

@Clear(LoginInterceptor.class)
public void analysisXml() throws Exception {
log.error("***************微信支付回调数据开始********************");
// 示例报文
// String xml =
// "<xml><appid><![CDATA[wxb4dc385f953b356e]]></appid><bank_type><![CDATA[CCB_CREDIT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1228442802]]></mch_id><nonce_str><![CDATA[1002477130]]></nonce_str><openid><![CDATA[o-HREuJzRr3moMvv990VdfnQ8x4k]]></openid><out_trade_no><![CDATA[1000000000051249]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[1269E03E43F2B8C388A414EDAE185CEE]]></sign><time_end><![CDATA[20150324100405]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[1009530574201503240036299496]]></transaction_id></xml>";
String inputLine;
String notityXml = "";
String resXml = "";


try {
while ((inputLine = getRequest().getReader().readLine()) != null) {
notityXml += inputLine;
}
getRequest().getReader().close();
} catch (Exception e) {
}


Map<String, String> m = parseXmlToList2(notityXml);
WxPayResult wpr = new WxPayResult();
wpr.setAppid(m.get("appid").toString());
log.error("---->" + m.get("appid").toString());


wpr.setBankType(m.get("bank_type").toString());
log.error("-1 ---->" + m.get("bank_type").toString());


wpr.setCashFee(m.get("cash_fee").toString());
log.error("-0 ---->" + m.get("bank_type").toString());


wpr.setFeeType(m.get("fee_type").toString());
wpr.setIsSubscribe(m.get("is_subscribe").toString());
log.error("0 ---->" + m.get("is_subscribe").toString());


wpr.setMchId(m.get("mch_id").toString());
log.error("1 ---->" + m.get("mch_id").toString());


wpr.setNonceStr(m.get("nonce_str").toString());
wpr.setOpenid(m.get("openid").toString());
String openId = m.get("openid").toString();
log.error("2 ---->" + openId);


// out_trade_no:系统本身订单ID
String out_trade_no = m.get("out_trade_no").toString();
log.error("微信支付回调" + out_trade_no);


wpr.setOutTradeNo(out_trade_no);
wpr.setResultCode(m.get("result_code").toString());
log.error("微信支付回调result_code" + m.get("result_code").toString());


wpr.setReturnCode(m.get("return_code").toString());
log.error("微信支付回调result_code" + m.get("return_code").toString());


wpr.setSign(m.get("sign").toString());
log.error("微信支付回调sign" + m.get("sign").toString());


wpr.setTimeEnd(m.get("time_end").toString());
log.error("微信支付回调time_end" + m.get("time_end").toString());


wpr.setTotalFee(m.get("total_fee").toString());
log.error("微信支付回调total_fee" + m.get("total_fee").toString());


wpr.setTradeType(m.get("trade_type").toString());
log.error("微信支付回调trade_type" + m.get("trade_type").toString());


// //transaction_id:微信支付系统订单ID,有微信支付系统生成
wpr.setTransactionId(m.get("transaction_id").toString());
if ("SUCCESS".equals(wpr.getResultCode())) {
// 支付成功
//在这里处理业务逻辑
/**
* 1.根据商户号和订单号查询出支付的参与活动用户 2.保存支付金额    这是分享砍价
*/
if(m.get("out_trade_no").contains("share")){
List<ShareBargainWxuser> sbwList = ShareBargainWxuserService.getService()
.getSbwByMchIdAndoutTradeNo(m.get("mch_id").toString(), m.get("out_trade_no").toString());
log.error("支付后回调-查询参加活动用户"+sbwList.size());
if (sbwList.size() > 0) {
ShareBargainWxuser sbw = new ShareBargainWxuser();
for (ShareBargainWxuser sbwErgodic : sbwList) {
sbw = sbwErgodic;
}
String money = m.get("total_fee").toString();
int moneyInt = Integer.parseInt(money);
float moneyNum = (float) (moneyInt * 0.01);
log.error("支付后回调-参加活动用户ID"+sbw.getId());
log.error("支付后回调-支付金额"+moneyNum);
String id = sbw.getId();
new ShareBargainWxuser().set("ID", id).set("PAY_MONEY", moneyNum).set("STATE", "6").update();
String sql="select* from TB_PRODUCT_WINNING_INFO where ACTIVITY_WXUSER_ID = ? ";
ProductWinningInfo pwi = ProductWinningInfo.dao.findFirst(sql,id);
pwi.set("ID", pwi.getId()).set("PAY_MONEY", moneyNum).set("PRICE", sbw.getPrice()).set("LOW_PRICE", sbw.getLowPrice()).update();
/* //修改砍价活动获奖人数
ShareBargain ab = ShareBargain.dao.findById(sbw.getJoinActivityId());
int winningPropleNumber = ab.getWinningPropleNumber().intValue();
new ShareBargain().set("ID", ab.getId()).set("WINNING_PROPLE_NUMBER",winningPropleNumber+1).update();*/

}
}

//这里是处理支付完成 拼团
else if(m.get("out_trade_no").toString().contains("purchase")){
log.error("***************这里是处理支付完成 一元购********************");
log.error("**************************out_trade_no>"+m.get("out_trade_no").toString());
log.error("**************************mch_id>"+m.get("mch_id").toString());
String payoutNo = m.get("out_trade_no").toString();
//根据订单号查询  拼团的组团的团长 所属的信息
String sql="select * from TB_GROUP_PURCHASE_GROUP_WXUSER where PAYOUTNO = ? ";
GroupPurchaseGroupWxUser groupPurchaseGroupWxUser = GroupPurchaseGroupWxUser.dao.findFirst(sql,payoutNo);
log.error("**************************groupPurchaseGroupWxUser>"+groupPurchaseGroupWxUser);
if(groupPurchaseGroupWxUser!=null){
//这是该团的团长参与的微信活动
String groupPurchaseWxUserId = groupPurchaseGroupWxUser.getGroupPurchaseWxUserId();
GroupPurchaseWxUser groupPurchaseWxUser = GroupPurchaseWxUser.dao.findById(groupPurchaseWxUserId);
//该活动的拼团大活动
String groupPurchaseId = groupPurchaseWxUser.getGroupPurchaseId();
GroupPurchase groupPurchase = GroupPurchase.dao.findById(groupPurchaseId);
//公众号
String sellerNumberId = groupPurchaseWxUser.getBelongPublicNumberId();
SellerPublicNumber sellerPublicNumber = SellerPublicNumber.dao.findById(sellerNumberId);
boolean update = groupPurchaseWxUser.set("ID", groupPurchaseWxUserId)
                            .set("PAYMONEY", groupPurchase.getGroupPrice())
                            .set("PAYSTATE", "1")
                            .update();
if(sellerPublicNumber!=null){
//TODO 发送参与成功通知
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//发送参与通知
String json = " {\"touser\":\""+openId+"\","+"\"template_id\":\""+sellerPublicNumber.getSuccessId()+"\","
+ "\"url\":\"http://open.weixin.qq.com/connect/oauth2/authorize?appid=" + sellerPublicNumber.getAppId()
+ "&redirect_uri=http%3a%2f%2f" + PropKit.use("system.properties").get("http") + JFinal.me().getContextPath()
+ "%2fgroupPurchase%2fgoFriendRedirect%3fgroupPurchaseWxUserId%3d" + groupPurchaseWxUser.getId() + "%26groupPurchaseId%3d" + groupPurchase.getId()+ "%26sellerNumberId%3d" + sellerNumberId+ "%26qrcode%3d" + groupPurchaseWxUser.getScanCode()
+ "&response_type=code&scope=snsapi_userinfo&state=wx#wechat_redirect\"," + "\"topcolor\":\"#FF0000\","
+ "\"data\":{" + "\"first\": {" + "\"value\":\"您已成功参与拼团活动\"," + "\"color\":\"#000000" + "\"},"
+ "\"keyword1\":{" + "\"value\":\"" + groupPurchase.getActivityName() + "\"," + "\"color\":\"#1d326b" + "\"},"
+ "\"keyword2\":{" + "\"value\":\"" + sdf.format(new Date()) + "\"," + "\"color\":\"#1d326b" + "\"},"
+ "\"remark\":{" + "\"value\":\"感谢您的参与,点击可以查看活动详情\"," + "\"color\":\"#CD4F39\"}}}";
String ps = HttpUtils.post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken(),json);
System.out.println(ps);
//*******发送结束
update = groupPurchaseGroupWxUser.set("ID", groupPurchaseGroupWxUser.getId()).set("PAYSTATE", "1").update();
log.error("修改该用户支付状态***》"+update);
}
}
}
resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";

} else {
resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";

}
BufferedOutputStream out = new BufferedOutputStream(getResponse().getOutputStream());
out.write(resXml.getBytes());
out.flush();
out.close();
renderNull();
}


/**
* description: 解析微信通知xml

* @param xml
* @return
* @author
* @see
*/
private Map<String, String> parseXmlToList2(String xml) {
Map<String, String> retMap = new HashMap<String, String>();
try {
StringReader read = new StringReader(xml);
// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource source = new InputSource(read);
// 创建一个新的SAXBuilder
SAXBuilder sb = new SAXBuilder();
// 通过输入源构造一个Document
Document doc = (Document) sb.build(source);
Element root = doc.getRootElement();// 指向根节点
@SuppressWarnings("unchecked")
List<Element> es = root.getChildren();
if (es != null && es.size() != 0) {
for (Element element : es) {
retMap.put(element.getName(), element.getValue());
}
}
} catch (Exception e) {
}
return retMap;
}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值