using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace Web.Controllers{ public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } }}
@{ Layout = null;}<!DOCTYPE html><html><head> <meta name="viewport" content="width=device-width" /> <title>Index</title></head><body> <div> </div></body></html>
@{ Layout = null;}<!DOCTYPE html><html><head> <meta name="viewport" content="width=device-width" /> <title>电表充值服务</title> <link href="~/Scripts/jquery-easyui-1.4.5/themes/bootstrap/easyui.css" rel="stylesheet" /> <link href="~/Scripts/jquery-easyui-1.4.5/themes/mobile.css" rel="stylesheet" /> <link href="~/Scripts/jquery-easyui-1.4.5/themes/icon.css" rel="stylesheet" /> <style type="text/css"> body{ margin:0; padding:0; } .logo { width: 100%; height: 70px; background: url(/Images/EleLogo.png) 0 0 no-repeat; background-size: 100% 100%; padding: 0; margin: 0; } .line { width: 100%; float: left; height: auto; text-align: center; margin-top: 10px; } .lineText { width: 100%; float: left; height: auto; text-indent: 5%; text-align: left; font-size: x-large; margin: 0; } .function { height: 60pt; line-height: 60pt; width: 45%; float: left; border-radius: 10px; background-color: #990000; margin-left: 8pt; } .title { font-family: "微软雅黑"; font-size: x-large; color: white; } a { text-decoration: none; color: white; } input { vertical-align: central; } label { vertical-align: central; } .lbBlock { border: 1px solid #808080; background-color: grey; width: 90%; margin-left: 5%; font-size: x-large; border-radius: 10px; text-align: left; text-indent: 10pt; height: 30pt; padding-top: 5pt; } .btn { width: 90%; height: 35pt; font-size: x-large; background-color: #990000; color: white; background: url(/Images/red.png) 0 0 repeat; border: none; border-radius: 10px; margin: 10px 0 0 0; } .input { height: 30pt; width: 90%; font-size: x-large; border-radius: 10px; margin: 0; padding: 0; } </style></head><body> <div class="logo"> </div> <form id="ChargeForm"> <div class="line"> <div class="lineText"> 充值金额: </div> </div> <div class="line"> <input type="number" id="ChargeVal" name="ChargeVal" class="input" placeholder="单位:元" /> </div> </form> <div class="line"> <input type="button" class="btn" value="立即充值" onclick="fCharge()" style="margin-top: 20px;" /> </div> <div class="line"> <input type="button" id="btnHome" class="btn" value="返回主页" onclick="fBackHome()" /> </div> <script src="~/Scripts/jquery-easyui-1.4.5/jquery.min.js"></script> <script src="~/Scripts/jquery-easyui-1.4.5/jquery.easyui.min.js"></script> <script src="~/Scripts/jquery-easyui-1.4.5/jquery.easyui.mobile.js"></script> <script src="~/Scripts/jquery-easyui-1.4.5/easyloader.js"></script> <script type="text/javascript"> $(function () { var vCode = getQueryString("code"); if (vCode != "" && vCode != null) { //alert(vCode); $.ajax({ type: ‘post‘, data: { code: vCode }, url: ‘/Home/getWxInfo‘, success: function (sjson) { //alert(sjson); //var vData = JSON.stringify(sjson); //alert(vData); $.messager.show({ title: ‘提示‘, msg: ‘欢迎您来到微信端充值中心。‘ }); } }) } else { $.ajax({ type: ‘post‘, url: ‘/Home/getCode‘, success: function (sjson) { //alert(sjson); location.href = sjson; } }) } }) //获取url的参数 function getQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; } //初始化微信支付环境 function fCharge() { 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 { fPostCharge(); } } //提交充值数据 function fPostCharge() { var vChargeVal = $("#ChargeVal").val(); vChargeVal = parseFloat(vChargeVal); if (vChargeVal > 0) { $.messager.progress({ title: "", msg: "正在调用微信支付接口,请稍后..." }); $.ajax({ type: "post", data: "totalfee=" + vChargeVal, url: "/Home/MeterRecharge", success: function (json) { $.messager.progress(‘close‘);//记得关闭 //var json = eval("(" + msg + ")");//转换后的JSON对象 onBridgeReady(json); }, error: function () { $.messager.progress(‘close‘);//记得关闭 $.messager.alert("提示", ‘调用微信支付模块失败,请稍后再试。‘, ‘info‘) } }) } else { alert("房间名或者充值金额不可以为空或者为负数,请确认后再试.") } } //调用微信支付模块 function onBridgeReady(json) { WeixinJSBridge.invoke( ‘getBrandWCPayRequest‘, { "appId": json.appId, //公众号名称,由商户传入 "timeStamp": json.timeStamp, //时间戳,自1970年以来的秒数 "nonceStr": json.nonceStr, //随机串 "package": json.packageValue, "signType": "MD5", //微信签名方式: "paySign": json.paySign //微信签名 }, function (res) { if (res.err_msg == "get_brand_wcpay_request:ok") { //alert("支付成功,请稍后查询余额,如有疑问,请联系管理员."); fAlreadyPay(); } // 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回 ok,但并不保证它绝对可靠。 } ); } function fBackHome() { location.href = "/"; } </script></body></html>
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using Web.Models;using WxPayAPI;namespace Web.Controllers{ public class HomeController : Controller { JsApiPay jsApiPay = new JsApiPay(); // GET: Home public ActionResult Index() { if (Session["openid"] == null) { try { //调用【网页授权获取用户信息】接口获取用户的openid和access_token GetOpenidAndAccessToken(); } catch (Exception ex) { //Response.Write(ex.ToString()); //throw; } } return View(); } /** * * 网页授权获取用户基本信息的全部过程 * 详情请参看网页授权获取用户基本信息:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html * 第一步:利用url跳转获取code * 第二步:利用code去获取openid和access_token * */ public void GetOpenidAndAccessToken() { if (Session["code"] != null) { //获取code码,以获取openid和access_token string code = Session["code"].ToString(); Log.Debug(this.GetType().ToString(), "Get code : " + code); jsApiPay.GetOpenidAndAccessTokenFromCode(code); } else { //构造网页授权获取code的URL string host = Request.Url.Host; string path = Request.Path; string redirect_uri = HttpUtility.UrlEncode("http://" + host + path); //string redirect_uri = HttpUtility.UrlEncode("http://gzh.lmx.ren"); WxPayData data = new WxPayData(); data.SetValue("appid", WxPayConfig.APPID); data.SetValue("redirect_uri", redirect_uri); data.SetValue("response_type", "code"); data.SetValue("scope", "snsapi_base"); data.SetValue("state", "STATE" + "#wechat_redirect"); string url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + data.ToUrl(); Log.Debug(this.GetType().ToString(), "Will Redirect to URL : " + url); Session["url"] = url; } } /// <summary> /// 获取code /// </summary> /// <returns></returns> [HttpPost] public ActionResult getCode() { object objResult = ""; if (Session["url"] != null) { objResult = Session["url"].ToString(); } else { objResult = "url为空。"; } return Json(objResult); } /// <summary> /// 通过code换取网页授权access_token和openid的返回数据 /// </summary> /// <returns></returns> [HttpPost] public ActionResult getWxInfo() { object objResult = ""; string strCode = Request.Form["code"]; if (Session["access_token"] == null || Session["openid"] == null) { jsApiPay.GetOpenidAndAccessTokenFromCode(strCode); } string strAccess_Token = Session["access_token"].ToString(); string strOpenid = Session["openid"].ToString(); objResult = new { openid = strOpenid, access_token = strAccess_Token }; return Json(objResult); } /// <summary> /// 充值 /// </summary> /// <returns></returns> [HttpPost] public ActionResult MeterRecharge() { object objResult = ""; string strTotal_fee = Request.Form["totalfee"]; string strFee = (double.Parse(strTotal_fee) * 100).ToString(); //若传递了相关参数,则调统一下单接口,获得后续相关接口的入口参数 jsApiPay.openid = Session["openid"].ToString(); jsApiPay.total_fee = int.Parse(strFee); //JSAPI支付预处理 try { string strBody = "南宫萧尘微信支付";//商品描述 WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(strBody); WxPayData wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数,注意,这里引用了官方的demo的方法,由于原方法是返回string的,所以,要对原方法改为下面的代码,代码在下一段 ModelForOrder aOrder = new ModelForOrder() { appId = wxJsApiParam.GetValue("appId").ToString(), nonceStr = wxJsApiParam.GetValue("nonceStr").ToString(), packageValue = wxJsApiParam.GetValue("package").ToString(), paySign = wxJsApiParam.GetValue("paySign").ToString(), timeStamp = wxJsApiParam.GetValue("timeStamp").ToString(), msg = "成功下单,正在接入微信支付." }; objResult = aOrder; } catch (Exception ex) { ModelForOrder aOrder = new ModelForOrder() { appId = "", nonceStr = "", packageValue = "", paySign = "", timeStamp = "", msg = "下单失败,请重试,多次失败,请联系管理员." }; objResult = aOrder; } return Json(objResult); } }}
这里就是上面修改了的代码,童鞋们请注意
/** * * 从统一下单成功返回的数据中获取微信浏览器调起jsapi支付所需的参数, * 微信浏览器调起JSAPI时的输入参数格式如下: * { * "appId" : "wx2421b1c4370ec43b", //公众号名称,由商户传入 * "timeStamp":" 1395712654", //时间戳,自1970年以来的秒数 * "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串 * "package" : "prepay_id=u802345jgfjsdfgsdg888", * "signType" : "MD5", //微信签名方式: * "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 * } * @return string 微信浏览器调起JSAPI时的输入参数,json格式可以直接做参数用 * 更详细的说明请参考网页端调起支付API:http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7 * */ public WxPayData GetJsApiParameters() { Log.Debug(this.GetType().ToString(), "JsApiPay::GetJsApiParam is processing..."); WxPayData jsApiParam = new WxPayData(); jsApiParam.SetValue("appId", unifiedOrderResult.GetValue("appid")); jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp()); jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr()); jsApiParam.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id")); jsApiParam.SetValue("signType", "MD5"); jsApiParam.SetValue("paySign", jsApiParam.MakeSign()); string parameters = jsApiParam.ToJson(); Log.Debug(this.GetType().ToString(), "Get jsApiParam : " + parameters); return jsApiParam; }
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace Web.Models{ public class ModelForOrder { public string appId { get; set; } public string timeStamp { get; set; } public string nonceStr { get; set; } public string packageValue { get; set; } public string paySign { get; set; } public string msg { get; set; } }}
public ActionResult Index() { if (Session["openid"] == null) { try { //调用【网页授权获取用户信息】接口获取用户的openid和access_token GetOpenidAndAccessToken(); } catch (Exception ex) { //Response.Write(ex.ToString()); //throw; } } return View(); }
$(function () { var vCode = getQueryString("code"); if (vCode != "" && vCode != null) { //alert(vCode); $.ajax({ type: ‘post‘, data: { code: vCode }, url: ‘/Home/getWxInfo‘, success: function (sjson) { //alert(sjson); //var vData = JSON.stringify(sjson); //alert(vData); $.messager.show({ title: ‘提示‘, msg: ‘欢迎您来到微信端充值中心。‘ }); } }) } else { $.ajax({ type: ‘post‘, url: ‘/Home/getCode‘, success: function (sjson) { //alert(sjson); location.href = sjson; } }) } })
/// <summary> /// 获取code /// </summary> /// <returns></returns> [HttpPost] public ActionResult getCode() { object objResult = ""; if (Session["url"] != null) { objResult = Session["url"].ToString(); } else { objResult = "url为空。"; } return Json(objResult); }
//初始化微信支付环境 function fCharge() { 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 { fPostCharge(); } }
/// <summary> /// 充值 /// </summary> /// <returns></returns> [HttpPost] public ActionResult MeterRecharge() { object objResult = ""; string strTotal_fee = Request.Form["totalfee"]; string strFee = (double.Parse(strTotal_fee) * 100).ToString(); //若传递了相关参数,则调统一下单接口,获得后续相关接口的入口参数 jsApiPay.openid = Session["openid"].ToString(); jsApiPay.total_fee = int.Parse(strFee); //JSAPI支付预处理 try { string strBody = "南宫萧尘微信支付";//商品描述 WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(strBody); WxPayData wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数 ModelForOrder aOrder = new ModelForOrder() { appId = wxJsApiParam.GetValue("appId").ToString(), nonceStr = wxJsApiParam.GetValue("nonceStr").ToString(), packageValue = wxJsApiParam.GetValue("package").ToString(), paySign = wxJsApiParam.GetValue("paySign").ToString(), timeStamp = wxJsApiParam.GetValue("timeStamp").ToString(), msg = "成功下单,正在接入微信支付." }; objResult = aOrder; } catch (Exception ex) { ModelForOrder aOrder = new ModelForOrder() { appId = "", nonceStr = "", packageValue = "", paySign = "", timeStamp = "", msg = "下单失败,请重试,多次失败,请联系管理员." }; objResult = aOrder; } return Json(objResult); }
//调用微信支付模块 function onBridgeReady(json) { WeixinJSBridge.invoke( ‘getBrandWCPayRequest‘, { "appId": json.appId, //公众号名称,由商户传入 "timeStamp": json.timeStamp, //时间戳,自1970年以来的秒数 "nonceStr": json.nonceStr, //随机串 "package": json.packageValue, "signType": "MD5", //微信签名方式: "paySign": json.paySign //微信签名 }, function (res) { if (res.err_msg == "get_brand_wcpay_request:ok") { //alert("支付成功,请稍后查询余额,如有疑问,请联系管理员."); fAlreadyPay(); } // 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回 ok,但并不保证它绝对可靠。 } ); }