C# MVC 微信支付教程系列之公众号支付





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,但并不保证它绝对可靠。
}
);
}


C# MVC 微信支付教程系列之公众号支付的更多相关文章
- 【原创分享·微信支付】 C# MVC 微信支付教程系列之公众号支付
微信支付教程系列之公众号支付 今天,我们接着讲微信支付的系列教程,前面,我们讲了这个微信红包和扫码支付.现在,我们讲讲这个公众号支付.公众号支付的应用环境常见的用户通过公众号,然后再通 ...
- 【分享·微信支付】 C# MVC 微信支付教程系列之公众号支付
微信支付教程系列之公众号支付 今天,我们接着讲微信支付的系列教程,前面,我们讲了这个微信红包和扫码支付.现在,我们讲讲这个公众号支付.公众号支付的应用环境常见的用户通过公众号,然后 ...
- 【原创分享·微信支付】 C# MVC 微信支付教程系列之扫码支付
微信支付教程系列之扫码支付 今天,我们来一起探讨一下这个微信扫码支付.何为扫码支付呢?这里面,扫的码就是二维码了,就是我们经常扫一扫的那种二维码图片,例如,我们自己添 ...
- C# 微信支付教程系列之扫码支付
微信支付教程系列之扫码支付 今天,我们来一起探讨一下这个微信扫码支付.何为扫码支付呢?这里面,扫的码就是二维码了,就是我们经常扫一扫的那种二维码图片,例如,我们自己添加好友的时候 ...
- .NET微信支付(H5仅限公众号支付)
闲来无事,恰好有一个要用微信公众平台支付的功能,研究来研究去,就是要细心和多看腾讯提供的文档.当然有几个坑是很有必要说明一下的 公众号支付,这里统一叫H5支付,以下都是. 在做H5支付的时候,第一步就 ...
- 微信支付接口开发之---微信支付之JSSDK(公众号支付)步骤
1.准备 1.1.公众号为服务号,开通微信支付功能 1.2.为了方便调试微信后台的回调URL(必须为外网),我用了nat123软件来做一个映射 1.3.官方微信开发的示例WxP ...
- 【原创分享·微信支付】C# MVC 微信支付教程系列之现金红包
微信支付教程系列之现金红包 最近最弄这个微信支付的功能,然后扫码.公众号支付,这些都做了,闲着无聊,就看了看微信支付的其他功能,发现还有一个叫“现金红包”的玩意,想 ...
- JAVA开发微信支付-公众号支付/微信浏览器支付(JSAPI)
写这篇文章的目的有2个,一是自己的项目刚开发完微信支付功能,趁热回个炉温习一下,二也是帮助像我这样对微信支付不熟悉,反复看了多天文档还是一知半解,原理都没摸清,更不要说实现了.本以为网上的微信开发教程 ...
- 微信公众号支付流程(Node实现)
前言 花费了一天时间,调通了微信公众号支付.作下记录,方便以后再次填坑.先声明,微信公众号支付,不同于微信H5支付,这点在本文结束时再详细说明. 微信配置 设置测试目录 在微信公众平台设置,栏目见下图 ...
随机推荐
- SLAM领域牛人、牛实验室、牛研究成果梳理
点击公众号"计算机视觉life"关注,置顶星标更快接收消息! 本文阅读时间约5分钟 对于小白来说,初入一个领域时最应该了解的当然是这个领域的研究现状啦.只有知道这个领域大家现在正在 ...
- 在 CentOS7 上安装 Zookeeper服务
1.创建 /usr/local/services/zookeeper 文件夹: mkdir -p /usr/local/services/zookeeper 2.进入到 /usr/local/serv ...
- Godot必须明确掌握的概念与知识
本文对godot必须掌握的概念进行罗列,以便于浏览学习: (随时补充) 1.场景 2.节点 X:场景与节点 3.脚本(建议直接学习GDscript,当然掌握C#也可以) 4.类
- 既然选择了远方,便只顾风雨兼程--myvue
浅谈以下vue的模式,其实vue的模式跟react是一样的,都是MVVM模式,就是直接数据和视图之间的切换 如果单纯这样认识的话,和angular相比较起来,vue就简单的很多,但是事实情况并不是这样 ...
- Java 多重catch语句的具体使用介绍
某些情况,由单个代码段可能引起多个异常.处理这种情况,你可以定义两个或更多的catch子句,每个子句捕获一种类型的异常.当异常被引发时,每一个catch子句被依次检查,第一个匹配异常类型的子句执行.当 ...
- 如何在eclipse添加SVN菜单
首先需要在eclipse中安装svn插件,这个网上教程很多 那么我来说下如何在将svn添加到菜单中去吧. 很简单,
- Linux下启动Oracle服务和监听程序
$ su – oracle $ sqlplus / nolog sql> conn / as sysdba sql> startup #启动Oracle,需 ...
- Linux相关代码
Linux ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ---- ...
- 剑指offer(9)变态跳台阶
题目描述 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级.求该青蛙跳上一个n级的台阶总共有多少种跳法. 题目分析 根据上一个题目可以知道,青蛙只跳1或2可以得出是一个斐波那契问题,即 ...
- 关于redis集群的问题no reachable node in cluster
重新启动redis集群时启动失败 n context with path [] threw exception [Request processing failed; nested exception ...