项目需求:学校学生网上缴费项目,刚来公司实习网上百度了各种资料,感谢很多大神避免了很多大坑。
本次扫码支付为:电脑生成二维码,手机微信扫码进行付款。建议开发前下载官方demo熟悉及后续有用到里面代码:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1
1.微信公众平台→支付配置→支付授权目录(授权目录就是指你要进行支付的目录)添加你的项目发布文件网址,手上暂无公司微信公众平台账号,百度上下有什么详细说明就不再说明了。
2.新建mvc项目→新建文件夹resources将官方demo中的business和lib文件夹复制过来
3.打开lib文件夹里的config,在这里配置基础信息和支付回调地址
4.新建wxpay页面,此页面展示付款二维码,采用了jquery.qrcode.min.js生成二维码,贴部分重要代码
<script language="javascript"> $(function () { getwxqrcode(); }); function getwxqrcode() { //$('#qrcode').css('display', ''); //去除隐藏 //$('#paytitle').html('微信支付'); $('#tradeno').html(''); $('#paymoney').html(''); $.ajax({ type: "post", url: "/studentindex/getwxqrcode", data: { time: new date(), productid: "考试费用", idcard: '@viewbag.idcard', }, success: function (json) { if (json.result) { $("#qrcode").qrcode(json.str); //生成二维码 $("#tradeno").html(json.no); //订单编号 $('#paymoney').html(json.money); } else { $("#qrcode").html("二维码生成失败"); } }, error: function (json) { $("#qrcode").html("二维码生成错误"); } }) } <div class="i_ma"> <div class="i_name"> 微信支付 <p>wechat payment</p> </div> <div class="space_hx"> </div> <div>订单编号:<p id="tradeno"></p></div> <div>考试费用:<p id="paymoney"></p></div> <div id="qrcode"> </div> </div> <div class="space_hx"> </div>
5.控制器内添加生成二维码方法,这里面的idcard是学生身份证,添加到附加数据内便于后面查询订单时判断是谁缴了费
//生成微信支付二维码 [httppost] public actionresult getwxqrcode(string idcard) { object objresult = ""; string tradeno; string paymoney; string strproductid = request.form["productid"]; //商品id string strqrcodestr = getwxpayurl(strproductid, idcard, out tradeno, out paymoney); //session["outtradeno"] = outtradeno; if (!string.isnullorwhitespace(strproductid)) { objresult = new { result = true, str = strqrcodestr, no = tradeno, money = paymoney }; } else { objresult = new { result = false }; } return json(objresult); } //生成直接微信支付url,支付url有效期为10分钟,模式二 public string getwxpayurl(string productid, string idcard, out string out_trade_no, out string money) { wxpaydata data = new wxpaydata(); data.setvalue("body", "分类考试学费");//商品描述 data.setvalue("attach", idcard);//附加数据 out_trade_no = wxpayapi.generateouttradeno(); //session["out_trade_no"] = out_trade_no; data.setvalue("out_trade_no", out_trade_no);//随机字符串 string total = convert.toint32((context.receiptinfomodel.orderby(x => x.id).firstordefault().paymoney * 100)).tostring(); money = context.receiptinfomodel.orderby(x => x.id).firstordefault().paymoney + "元"; data.setvalue("total_fee", total);//总金额 data.setvalue("time_start", datetime.now.tostring("yyyymmddhhmmss"));//交易起始时间 data.setvalue("time_expire", datetime.now.addminutes(10).tostring("yyyymmddhhmmss"));//交易结束时间 data.setvalue("goods_tag", "商品的备忘,可以自定义");//商品标记 data.setvalue("trade_type", "native");//交易类型 data.setvalue("product_id", productid);//商品id wxpaydata result = wxpayapi.unifiedorder(data);//调用统一下单接口 string url = result.getvalue("code_url").tostring();//获得统一下单接口返回的二维码链接 prewxpayorder(idcard, out_trade_no); return url; } //生成二维码同时,生成预支付订单 public void prewxpayorder(string idcard, string out_trade_no) { wxpayordermodel model = new wxpayordermodel(); model.studentcard = idcard; model.orderno = out_trade_no; model.ordertime = datetime.now; model.status = 0; model.ordertype = "微信"; context.wxpayordermodel.add(model); context.savechanges(); //log.info("生成预支付订单","订单号:"+out_trade_no); }
6.新建wxpayok页面(此页面是config里配置的支付回调url),视图不需要改动,在控制器里添加接收微信返回的数据
//接收微信返回信息 public actionresult wxpayok() { //接收从微信后台post过来的数据 system.io.stream s = request.inputstream; int count = 0; byte[] buffer = new byte[1024]; stringbuilder builder = new stringbuilder(); while ((count = s.read(buffer, 0, 1024)) > 0) { builder.append(encoding.utf8.getstring(buffer, 0, count)); } s.flush(); s.close(); s.dispose(); //转换数据格式并验证签名 wxpaydata data = new wxpaydata(); try { data.fromxml(builder.tostring()); } catch (wxpayexception ex) { //若签名错误,则立即返回结果给微信支付后台 wxpaydata res = new wxpaydata(); res.setvalue("return_code", "fail"); res.setvalue("return_msg", ex.message); log.error("签名错误", "sign check error : " + res.toxml()); response.write(res.toxml()); response.end(); } processnotify(data); return view(); } //微信支付后台返回的数据 public void processnotify(wxpaydata data) { wxpaydata notifydata = data; //检查支付结果中transaction_id是否存在 if (!notifydata.isset("transaction_id")) { wxpaydata res = new wxpaydata(); res.setvalue("return_code", "fail"); res.setvalue("return_msg", "支付结果中微信订单号不存在"); log.error("error", "订单号不存在"); response.write(res.toxml()); response.end(); } else { string transaction_id = notifydata.getvalue("transaction_id").tostring(); if (!queryorder(transaction_id)) { wxpaydata res = new wxpaydata(); res.setvalue("return_code", "fail"); res.setvalue("return_msg", "订单查询失败"); log.error("error", "订单查询失败"); response.write(res.toxml()); response.end(); } else { wxpaydata res = new wxpaydata(); res.setvalue("return_code", "success"); res.setvalue("return_msg", "ok"); //log.info("success", "支付成功"); addwaypayrecord(data.getvalue("out_trade_no").tostring(), data.getvalue("transaction_id").tostring(), data.getvalue("attach").tostring()); response.write(res.toxml()); response.end(); } } } //查询订单 public bool queryorder(string transaction_id) { wxpaydata req = new wxpaydata(); req.setvalue("transaction_id", transaction_id); wxpaydata res = wxpayapi.orderquery(req); if (res.getvalue("return_code").tostring() == "success" && res.getvalue("result_code").tostring() == "success") { return true; } else { return false; } } //微信支付完成添加记录 tradeno:订单号 public void addwaypayrecord(string tradeno, string tranid, string idcard) { lock (wxlock)//线程同步 { wxpayordermodel wxpayordermodel = context.wxpayordermodel.firstordefault(x => x.orderno == tradeno && x.ordertype == "微信" && x.studentcard == idcard && x.status == 0); if (wxpayordermodel != null) { wxpayordermodel.status = 1; context.entry(wxpayordermodel).state = system.data.entitystate.modified; context.savechanges(); studentmodel studentmodel = context.studentmodel.where(a => a.identitycard == wxpayordermodel.studentcard).firstordefault(); paymodel paymodel = context.paymodel.firstordefault(x => x.studentid == studentmodel.candidatenum); random rd = new random(); if (paymodel == null) { paymodel paymodel = new paymodel(); paymodel.paycount = context.receiptinfomodel.orderby(x => x.id).firstordefault().paymoney; paymodel.ordernumber = tradeno; paymodel.paytime = datetime.now; paymodel.payoddnum = tranid; context.paymodel.add(paymodel); context.savechanges(); } } } }
7.这时候页面也接收到微信返回的数据同时也添加到数据库中,页面上得给用户一个友好提示,告诉他支付成功了。在wxpay页面里加个ajax实时轮询数据库
$(function () { setinterval(getwxpayresult, 2000); function getwxpayresult() { var no = $("#tradeno").text(); $.ajax({ url: "/studentindex/wxpayresult", type: "post", data: { idcard: '@viewbag.idcard', tradeno:no, }, success: function (json) { if (json.result) { document.location.href = "/studentindex/wxpayisok?idcard=@viewbag.idcard"+"&&tradeno="+no; } else { } }, error: function (json) { alert("错误"); } }) } })
同时控制器里需要加上对应的方法,判断支付成功后跳转到一个新的页面wxpayisok
//ajax轮询支付结果 public actionresult wxpayresult(string idcard, string tradeno) { object data = ""; studentmodel studentmodel = context.studentmodel.firstordefault(x => x.identitycard == idcard); paymodel model = context.paymodel.firstordefault(x => x.studentid == studentmodel.candidatenum); if (model != null) { data = new { result = true }; } return json(data); } //支付完成 public actionresult wxpayisok(string idcard, string tradeno) { studentmodel studentmodel = context.studentmodel.firstordefault(x => x.identitycard == idcard); paymodel model = context.paymodel.firstordefault(x => x.studentid == studentmodel.candidatenum); if (model != null) { return content("<script>alert('缴费成功!');window.location.href='/studentindex/studentindex';</script>"); } else { return content("<script>alert('缴费失败!请保留好支付凭证前往缴费处申请退款');window.location.href='/studentindex/studentindex';</script>"); } }
结尾:第一次写博客有些乱,微信支付安全性还需要提高,项目部署也没经过大批量测试,就直接上线。
到现在也经历过两次几千人的缴费,一分钟缴费好几次,也碰到过网络延迟问题缴费成功后没及时更新数据库和一个浏览器打开两次微信支付界面导致两次缴费只算一次的各种问题。