【原创分享·微信支付】C# MVC 微信支付之微信模板消息推送










using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace 微信支付之模板消息推送.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>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace 微信支付之模板消息推送.Models
{
public class DataFontStyle
{
public string value { get; set; }
public string color { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace 微信支付之模板消息推送.Models
{
/// <summary>
/// 帐户资金变动提醒Model
/// </summary>
public class CashModel
{
public DataFontStyle first { get; set; }
public DataFontStyle date { get; set; }
public DataFontStyle adCharge { get; set; }
public DataFontStyle type { get; set; }
public DataFontStyle cashBalance { get; set; }
public DataFontStyle remark { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace 微信支付之模板消息推送.Models
{
public class PushMessage
{
public string touser { get; set; }
public string template_id { get; set; }
public string url { get; set; }
public string topcolor { get; set; }
/// <summary>
/// 注意,这里是CashModel,你如果要通用,有多个推送模板要用,那你就用object
/// </summary>
public CashModel data { get; set; } }
}漏了一个类,现在补回来,我们命名为:WxResult.cs,代码如下:public class WxResult
{
public int? errcode { get; set; }
public string errmsg { get; set; }
public int? msgid { get; set; }
}

@{
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">
.line {
width: 100%;
float: left;
height: auto;
text-align: center;
margin-top: 15pt;
font-size: x-large;
}
.lineText {
width: 100%;
float: left;
height: auto;
text-indent: 5%;
text-align: left;
font-size: x-large;
margin: 0;
}
a {
text-decoration: none;
color: white;
}
.input {
height: 30pt;
width: 90%;
font-size: x-large;
border-radius: 10px;
margin: 0;
padding: 0;
}
.btn {
width: 90%;
height: 35pt;
font-size: x-large;
background-color: green;
color: white;
border: none;
border-radius: 10px;
}
</style>
</head>
<body>
<div style="width: 100%; text-align: center;">
<form id="form1">
<div class="line">
<div class="lineText">*接收者openid:</div>
</div>
<div class="line">
<input type="text" id="openid" name="openid" class="input" />
</div>
<div class="line">
<div class="lineText">*first.DATA:</div>
</div>
<div class="line">
<input type="text" id="first" name="first" class="input" />
</div>
</form>
</div>
<div class="line">
<input type="button" id="btnSave" class="btn" value="推送" onclick="fPush()" />
</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) {
$.ajax({
type: 'post',
data: {
code: vCode
},
url: '/Home/getWxInfo',
success: function (sjson) {
$.messager.show({
title: '提示',
msg: '欢迎您的到来(看到这个提示,代表已经成功获取openid和access_token了)。'
});
$("#openid").val(sjson.openid);
}
})
}
else {
$.ajax({
type: 'post',
url: '/Home/getCode',
success: function (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 fPush() {
var vTtile = $("#first").val();
$.ajax({
type: 'post',
data: {
first: vTtile
},
url: '/Home/Push',
success: function (sjson) {
if (sjson.result) {
$.messager.alert("提示", sjson.msg, 'info');
}
else {
$.messager.alert("提示", sjson.msg, 'warning');
}
}
})
}
</script>
</body>
</html>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using WxPayAPI;
using 微信支付之模板消息推送.Models; namespace 微信支付之模板消息推送.Controllers
{
public class HomeController : Controller
{
JsApiPay jsApiPay = new JsApiPay(); JavaScriptSerializer JsonHelper = new JavaScriptSerializer();
/// <summary>
/// 最后更新Access_token的时间
/// </summary>
public static DateTime dtAccess_token;
/// <summary>
/// Access_token的值
/// </summary>
public static string strAccess_token;
// 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);
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"];
string strAccess_Token = "";
string strOpenid = "";
if (Session["access_token"] == null || Session["openid"] == null)
{
jsApiPay.GetOpenidAndAccessTokenFromCode(strCode);
strAccess_Token = Session["access_token"].ToString();
strOpenid = Session["openid"].ToString();
}
else
{
strAccess_Token = Session["access_token"].ToString();
strOpenid = Session["openid"].ToString();
}
objResult = new { openid = strOpenid, access_token = strAccess_Token };
return Json(objResult);
} /// <summary>
/// 推送
/// </summary>
/// <returns></returns>
[HttpPost]
public ActionResult Push()
{
object objResult = "";
string strFirst = Request.Form["first"];
string strMsg = "";
bool bResult = false;
//这个是推送消息的类
PushMessage aPushMessage = new PushMessage()
{
template_id = "lypG1jYyOEfY********OK7-LhEwpPeVNHHxemSI",//模板ID
//data=,//暂时不赋值
topcolor = "#FF0000",//头部颜色
touser = Session["openid"].ToString(),//用户的Openid
url = "http://www.baidu.com"//用途是当用户点击推送消息的时候,会进入这个页面,具体用途,自己拓展
}; //构造要推送的内容
CashModel aCachData = new CashModel()
{
adCharge = new DataFontStyle()
{
color = "#589E63",
value = "对应变动金额"
},
cashBalance = new DataFontStyle()
{
color = "#589E63",
value = "对应帐户余额"
},
date = new DataFontStyle()
{
color = "#589E63",
value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
},
first = new DataFontStyle()
{
color = "#589E63",
value = strFirst
},
remark = new DataFontStyle()
{
color = "#589E63",
value = "对应:点击“查看详情“立即查阅您的帐户财务记录。"
},
type = new DataFontStyle()
{
color = "#589E63",
value = "对应“现金”"
}
};
//这时候,把要推送的内容,赋值给push,这样,我们要推送的内容就完成了。
aPushMessage.data = aCachData; string strUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + GetLatestAccess_token(); string strJsonData = JsonHelper.Serialize(aPushMessage);
string strResult = HttpPost(strUrl, strJsonData);
WxResult aResult = JsonHelper.Deserialize<WxResult>(strResult);
if (aResult != null)
{
if (aResult.errcode == )
{
bResult = true;
}
else
{
bResult = false;
strMsg = aResult.errmsg;
}
}
else
{
bResult = false;
strMsg = "通讯失败,请重试。";
} objResult = new { result = bResult, msg = strMsg };
return Json(objResult);
} /// <summary>
/// HttpPost
/// </summary>
/// <param name="Url"></param>
/// <param name="postDataStr"></param>
/// <returns></returns>
public static string HttpPost(string Url, string postDataStr)
{
byte[] postData = Encoding.UTF8.GetBytes(postDataStr);//编码,尤其是汉字,事先要看下抓取网页的编码方式
WebClient webClient = new WebClient();
webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可
byte[] responseData = webClient.UploadData(Url, "POST", postData);//得到返回字符流
string srcString = Encoding.UTF8.GetString(responseData);//解码
return srcString; } /// <summary>
/// 返回最新的Access_token
/// </summary>
/// <returns></returns>
public string GetLatestAccess_token()
{
if (dtAccess_token == null || dtAccess_token <= DateTime.Now.AddHours(-) || string.IsNullOrWhiteSpace(strAccess_token))
{
string strUrl = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", WxPayConfig.APPID, WxPayConfig.APPSECRET);
string strAccess_tokenData = HttpGet(strUrl, "");
ModelForAccess_token aToken = JsonHelper.Deserialize<ModelForAccess_token>(strAccess_tokenData);
dtAccess_token = DateTime.Now;
strAccess_token = aToken.access_token;
return strAccess_token;
}
else
{
return strAccess_token;
}
} /// <summary>
/// WebGet
/// </summary>
/// <param name="Url"></param>
/// <param name="postDataStr"></param>
/// <returns></returns>
public static string HttpGet(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close(); return retString;
} public class ModelForAccess_token
{
public string access_token { get; set; }
public int? expires_in { get; set; }
}
}
}


【原创分享·微信支付】C# MVC 微信支付之微信模板消息推送的更多相关文章
- C# MVC 微信支付之微信模板消息推送
微信支付之微信模板消息推送 今天我要跟大家分享的是"模板消息"的推送,这玩意呢,你说用途嘛,那还是真真的牛逼呐.原因在哪?就是因为它是依赖微信 ...
- 前后端分离djangorestframework—— 接入微信模板消息推送
微信 什么是微信也不多说,跟前面的支付宝一样的 微信支付 微信支付也有个沙箱环境,沙箱环境官方文档 由文档中那句很显眼的话所得,即使是测试环境也需要真实的商户号,所以这个就没法想支付宝那样用沙箱账号来 ...
- java开发微信模板消息推送
发布时间:2018-12-12 技术:springboot+maven 概述 该demo主要涉及微信模板消息推送功能, 详细 代码下载:http://www.demodashi.com/dem ...
- ASP.NET 微信公众平台模板消息推送功能完整开发
最近公众平台的用户提出了新需求,他们希望当收到新的邮件或者日程的时候,公众平台能主动推送一条提醒给用户.看了看平台提供的接口,似乎只有[模板消息]能尽量满足这一需求,但不得不说微信提供的实例太少,而且 ...
- 微信小程序之模板消息推送
最近在用sanic框架写微信小程序,其中写了一个微信消息推送,还挺有意思的,写了个小demo 具体见官方文档:https://developers.weixin.qq.com/miniprogram/ ...
- qhfl-9 微信模板消息推送
开发中用的是测试号 微信公众号认证流程 用户登陆 <!DOCTYPE html> <html lang="en"> <head> <met ...
- Java对接微信公众号模板消息推送
内容有点多,请耐心! 最近公司的有这个业务需求,又很凑巧让我来完成: 首先想要对接,先要一个公众号,再就是开发文档了:https://developers.weixin.qq.com/doc/offi ...
- 微信小程序:模板消息推送提示{“errcode”:41030,”errmsg”:”invalid page hint: [gP1eXXXXXX]”}
在开发小程序 模板消息定时推送功能时,在开发版测试程序功能运行正常,但提交到线上后提示报错{“errcode”:41030,”errmsg”:”invalid page hint: [gP1eXXXX ...
- C#微信公众号开发系列教程五(接收事件推送与消息排重)
微信公众号开发系列教程一(调试环境部署) 微信公众号开发系列教程一(调试环境部署续:vs远程调试) C#微信公众号开发系列教程二(新手接入指南) C#微信公众号开发系列教程三(消息体签名及加解密) C ...
随机推荐
- node中的cmd规范
你应该熟悉nodejs模块中的exports对象,你可以用它创建你的模块.例如:(假设这是rocker.js文件) exports.name = function() { console.log('M ...
- ExtJS 4.2 组件的查找方式
组件创建了,就有方法找到这些组件.在DOM.Jquery都有各自的方法查找元素/组件,ExtJS也有自己独特的方式查找组件.元素.本次从全局查找.容器内查找.form表单查找.通用组件等4个方面介绍组 ...
- 在 C# 里使用 F# 的 option 变量
在使用 C# 与 F# 混合编程的时候(通常是使用 C# 实现 GUI,F#负责数据处理),经常会遇到要判断一个 option 是 None 还是 Some.虽然 Option module 里有 i ...
- 基于netty http协议栈的轻量级流程控制组件的实现
今儿个是冬至,所谓“冬大过年”,公司也应景五点钟就放大伙儿回家吃饺子喝羊肉汤了,而我本着极高的职业素养依然坚持留在公司(实则因为没饺子吃没羊肉汤喝,只能呆公司吃食堂……).趁着这一个多小时的时间,想跟 ...
- 熊乐:H3 BPM为加速企业流程管理提供源动力
近日,在北京·金隅喜来登酒店,H3 BPM以"让天下没有难用的流程"为主题,正式发布H3 BPM10.0版本.全新的业务流程管理系统在易用性方面大大提升,并且全面支持Java与.N ...
- windows 7(32/64位)GHO安装指南(系统安装篇)~重点哦!!~~~~
经过了前三篇的铺垫,我们终于来到了最重要的部分~~如果没看过前几篇的小伙伴们,可以出门右转~~用十几分钟回顾一下~~然后在看这篇会感觉不一样的~~~~ 下面让我们来正式开始吧 我们进入大白菜的桌面是酱 ...
- phpexcel读取输出操作
//读取 <?php header("Content-Type:text/html;charset=utf-8"); include 'Classes/PHPExcel.ph ...
- 把int*传值给char*,打印出错误的数字
首先进入debug模式查看i的地址也就是ptr的值 以16进制位小端模式存储(一个整型四个字节,8位16进制数)(根据系统位数情况) 紧接着因为ptr是char*型指针变量,读取数据时按照一个字节一个 ...
- ucos实时操作系统学习笔记——操作系统在STM32的移植
使用ucos实时操作系统是在上学的时候,导师科研项目中.那时候就是网上找到操作系统移植教程以及应用教程依葫芦画瓢,功能实现也就罢了,没有很深入的去研究过这个东西.后来工作了,闲来无聊就研究了一下这个只 ...
- 匹夫细说C#:不是“栈类型”的值类型,从生命周期聊存储位置
0x00 前言: 匹夫在日常和别人交流的时候,常常会发现一旦讨论涉及到“类型”,话题的热度就会立马升温,因为很多似是而非.或者片面的概念常常被人们当做是全面和正确的答案.加之最近在园子看到有人翻译的& ...