微信在国内目前无疑是最火的社交软件,智能手机装机必备。

微信api有java,php,Python语言的demo, 为毛没有C#的范例?兄长今天给各位带来一个。不叫哥(割)了,A股今天又暴跌【3912.77 -140.93 (-3.48%)】,为国满仓中...

1.微信帮助类:

 public class WeChatHelper
{
/// <summary>
/// 公众号的全局唯一票据
/// </summary>
public static String ACCESS_TOKEN = null;
/// <summary>
/// 凭证有效时间7200秒
/// </summary>
public static DateTime? ACCESS_TOKEN_EXPIRE_TIME = null;
/// <summary>
/// 公众号用于调用微信JS接口的临时票据
/// </summary>
public static String JS_API_TICKET = null;
/// <summary>
/// 有效期为7200秒
/// </summary>
public static DateTime? JS_API_TICKET_EXPIRE_TIME = null; public const String APP_ID = "你的";
public const String APP_SECRET = "你的";
/// <summary>
/// 生成签名的随机串
/// </summary>
private String nonce = null;
/// <summary>
/// 生成签名的时间戳
/// </summary>
private String timestamp = null;
/// <summary>
/// 签名
/// </summary>
private String signature = null;
/// <summary>
/// 当前网页的URL,不包含#及其后面部分
/// </summary>
private String url = null; public WeChatHelper(string url)
{
this.url = url;
this.CheckAccessTokenAndJsApiTicket();
if (JS_API_TICKET == null || JS_API_TICKET.Trim().Length < )
{
throw new Exception("JS_API_TICKET is empty.");
}
this.Sign();
} private void CheckAccessTokenAndJsApiTicket()
{
DateTime now = DateTime.Now; if (ACCESS_TOKEN == null || ACCESS_TOKEN_EXPIRE_TIME == null || now > ACCESS_TOKEN_EXPIRE_TIME)
{
this.initAccessToken();
} if (JS_API_TICKET == null || JS_API_TICKET_EXPIRE_TIME == null || now > JS_API_TICKET_EXPIRE_TIME)
{
this.initJSAPITicket();
}
}
/// <summary>
/// 初始化凭证
/// </summary>
private void initAccessToken()
{
String result = "";
try {
DateTime expireTime = DateTime.Now; String accessURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET;
Uri realUrl = new Uri(accessURL);
WebRequest request = WebRequest.Create(realUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream resStream = response.GetResponseStream())
{
if (resStream != null)
{
StreamReader reader = new StreamReader(resStream, Encoding.Default);
result = reader.ReadToEnd();
}
if (resStream != null) resStream.Close();
} JavaScriptSerializer jss = new JavaScriptSerializer();
Dictionary<string, object> respDic = (Dictionary<string, object>)jss.DeserializeObject(result);
//var errCode = respDic["errcode"];
//var errMsg = respDic["errmsg"];
if (respDic.ContainsKey("errcode"))
{
throw new Exception("Fail to get weixin access token. ERROR Code:" + respDic["errcode"].ToString() + " errMsg:" + respDic["errmsg"].ToString());
}
//通过键access_token获取值
ACCESS_TOKEN = respDic["access_token"].ToString();
var expireIn = respDic["expires_in"];
if (expireIn != null){
expireTime = expireTime.AddSeconds(double.Parse(expireIn.ToString()));
} ACCESS_TOKEN_EXPIRE_TIME = expireTime; }finally{ }
}
/// <summary>
/// 初始临时票据
/// </summary>
private void initJSAPITicket()
{
String result = "";
try {
DateTime expireTime = DateTime.Now; String accessURL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + ACCESS_TOKEN + "&type=jsapi"; Uri realUrl = new Uri(accessURL);
WebRequest request = WebRequest.Create(realUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream resStream = response.GetResponseStream())
{
if (resStream != null)
{
StreamReader reader = new StreamReader(resStream, Encoding.Default);
result = reader.ReadToEnd();
}
if (resStream != null) resStream.Close();
} JavaScriptSerializer jss = new JavaScriptSerializer();
Dictionary<string, object> respDic = (Dictionary<string, object>)jss.DeserializeObject(result); //var errCode = respDic["errcode"];
//var errMsg = respDic["errmsg"]; if (respDic.ContainsKey("errcode") && respDic["errcode"].ToString() != "")
{
throw new Exception("Fail to get weixin access token. ERROR Code:" + respDic["errcode"].ToString() + " errMsg:" + respDic["errmsg"].ToString());
} JS_API_TICKET = respDic["ticket"].ToString();
var expireIn = respDic["expires_in"]; if (expireIn != null){
expireTime = expireTime.AddSeconds(double.Parse(expireIn.ToString()));
} JS_API_TICKET_EXPIRE_TIME = expireTime; }finally{ }
} private void Sign()
{
this.nonce = Guid.NewGuid().ToString();
this.timestamp = ((long)((DateTime.UtcNow - new DateTime(, , , , , , DateTimeKind.Utc)).TotalMilliseconds/)).ToString(); String signatureUnCrpty = "jsapi_ticket=" + JS_API_TICKET +
"&noncestr=" + this.nonce +
"&timestamp=" + this.timestamp +
"&url=" + this.url; this.signature = FormsAuthentication.HashPasswordForStoringInConfigFile(signatureUnCrpty, "SHA1");
} public String getNonce()
{
return nonce;
} public void setNonce(String nonce)
{
this.nonce = nonce;
} public String getTimestamp()
{
return timestamp;
} public void setTimestamp(String timestamp)
{
this.timestamp = timestamp;
} public String getSignature()
{
return signature;
} public void setSignature(String signature)
{
this.signature = signature;
} public String getUrl()
{
return url;
} public void setUrl(String url)
{
this.url = url;
}
}

2.前端脚本:wechat.js

需要引入    <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js" type="text/javascript" ></script>

var titleStr = '测一测,你是哪个小升初名校的菜';
var descStr = '测一测,你是哪个小升初名校的菜';
var linkStr = window.location.href;
var logoStr = 'http://game.zy.com/Content/images/share_icon.png';
var optionTimeline = {
title: titleStr,
desc: descStr,
link: linkStr,
imgUrl: logoStr,
trigger: function (res) {
//alert('用户点击分享到朋友圈');
},
success: function (res) {
//alert('已分享');可以统计分享到朋友圈次数
$.ajax({
url: '/Game/SetShare',
type: 'POST',
async: false,
cache: false,
data: { typeID: 1 },
success: function (objJson) { }
});
}
};
var optionAppMessag ={
title: titleStr,
desc: descStr,
link: linkStr,
imgUrl: logoStr,
trigger: function (res) {
//alert('用户点击发送给朋友');
},
success: function (res) {
//alert('已分享');可以统计发送朋友次数
$.ajax({
url: '/Game/SetShare',
type: 'POST',
async: false,
cache: false,
data: { typeID: 2 },
success: function (objJson) { }
});
},
cancel: function (res) {
//alert('已取消');
},
fail: function (res) {
//alert(JSON.stringify(res));
}
};
function getWeChat() {
$.ajax({
url: '/Game/GetWeChatInfo',
type: 'GET',
async: false,
cache: false,
data: { 'url': linkStr },
success: function (objJson) {
// if (objJson.success) {
var objJson = eval('(' + objJson + ')'); //由JSON字符串转换为JSON对象
var appId = objJson.APP_ID;
var timestamp = objJson.TIMESTAMP;
var nonce = objJson.NONCE;
var signature = objJson.SIGNATURE;
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: appId, // 必填,公众号的唯一标识
timestamp: timestamp, // 必填,生成签名的时间戳
nonceStr: nonce, // 必填,生成签名的随机串
signature: signature, // 必填,签名,见附录1
jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
// }
// else { // }
} }); }
//初始分享数据
function weChatShare(optionAppMessag, optionTimeline) {
wx.ready(function () {
wx.onMenuShareAppMessage(optionAppMessag);
wx.onMenuShareTimeline(optionTimeline);
})
};
wx.error(function(res){
//alert("Error weixin");
// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。 });
getWeChat();
weChatShare(optionAppMessag, optionTimeline);

以上代码封装了相关参数,原因是 weChatShare() 方法初始了分享的标题,如果要使用动态的标题,必须在获取动态数据后在初始化一次。

 /* 游戏结束调用 返回答题的json */
window.gameOver = function (strJson) { $.ajax({
url: "/Game/SumbmitAnswer",
type: "POST",
data: { answer: strJson },
timeout: 5000,
async: false,
dataType: "json",
success: function (result) {
/* 更新视图 */
if (jc.hasUI("results")) {
jc.ui.results.all(function (i, obj) {
obj.setInfo({ scrollName: result.School, right: result.RightNum, ranking: result.Beat });
//初始化微信分享新数据
optionTimeline.title = optionAppMessag.title = "我答对了" + result.RightNum + "道题,打败了" + result.Beat + "%的学生,成为" + result.School + "学校的潜力学生. 放学后别走,等你来挑战";
weChatShare(optionAppMessag, optionTimeline);
});
}
}
}); }

.net 微信分享功能的更多相关文章

  1. AndroidStudio用微信官方方法接入微信分享功能

    转载请注明出处:http://www.cnblogs.com/wangoublog/p/5367950.html 现在微信的功能众所周知,用户量.影响力也是惊人,很多应用接入微信的功能已成为一种不可缺 ...

  2. 微信分享功能引入页面-控制分享时候调用的标题、图片、url和微信按钮隐藏显示控制

    1.设置分享调用的标题.图片.url预览. 2.控制右上角三个点按钮的隐藏显示(和底部工具栏的显示隐藏--未测试). 3.判断网页是否在微信中被调用. <!doctype html> &l ...

  3. android APP 中微信分享功能实现 的总结

    //花了很长时间最终完成了微信分享功能,中间走了很多弯路,在此做一下小结,希望对在应用中使用到微信分享的朋友有所帮助. 主要问题就是下面两个: 1.为什么运行了项目之后,微信分享只是闪了一下就没有了? ...

  4. 微信开发】【Asp.net MVC】-- 微信分享功能

    [微信开发][Asp.net MVC]-- 微信分享功能 2017-01-15 09:09 by stoneniqiu, 12886 阅读, 15 评论, 收藏, 编辑 内嵌在微信中的网页,右上角都会 ...

  5. AndroidStudio怎么实现微信分享功能

    在应用中添加微信分享功能,需要在微信开放平台上传你的应用,审核通过后方可使用此功能. https://open.weixin.qq.com/网址 申请的过程比较简单,这里就不追溯了,贴一个友情链接 h ...

  6. Android微信分享功能实例+demo

    Android微信分享功能实例 1 微信开放平台注册 2 获得appId,添加到程序中,并运行程序 3 使用应用签名apk生成签名,添加到微信开放平台应用签名,完成注册 4 测试分享功能. 有问题请留 ...

  7. php框架tp3.2.3和js写的微信分享功能心得,分享的标题内容图片自定义

    https://blog.csdn.net/weixin_42231483/article/details/81585322 最近用PHP的tp3.2.3框架和js写的微信分享功能心得,分享的标题内容 ...

  8. VueJs单页应用实现微信网页授权及微信分享功能

    在实际开发中,无论是做PC端.WebApp端还是微信公众号等类型的项目的时候,或多或少都会涉及到微信相关的开发,最近公司项目要求实现微信网页授权,并获取微信用户基本信息的功能及微信分享的功能,现在总算 ...

  9. 【微信开发】【Asp.net MVC】-- 微信分享功能

    内嵌在微信中的网页,右上角都会有一个默认的分享功能.如下图所示,第一个为自定义的效果,第二个为默认的效果.实现了自定义的分享链接是不是更让人有点击的欲望?下面讲解下开发的过程. 一.准备,设置js接口 ...

  10. 在Unity3D项目中接入ShareSDK实现安卓平台微信分享功能(可使用ShareSDK默认UI或自定义UI)

    最近公司的大厅要重做,我协助主程一起制作新大厅和新框架,前面制作的编辑器也派上了用场.等全部功能做完后我会再写一个复盘,这两天主程在忙于写热更新的功能,所以把接入分享SDK功能的任务交给了我,Shar ...

随机推荐

  1. cocos2d-js去掉左下角的三行数字(帧数)

    project.json 里面"showFPS": true, 改成 false 就行了... 调整帧率也在这里调整 或者是 同cocos2dx,cocos2d-js左下角的FPS ...

  2. apache配置多域名多站点记录

    <VirtualHost *:80>  DocumentRoot "/mnt/web/www.*.cn"  ServerName www.*.cn  ErrorLog ...

  3. libsvm参数学习和核函数使用(转载)

    一.参数说明 English libsvm_options: -s svm_type : set type of SVM (default 0) 0 -- C-SVC        1 -- nu-S ...

  4. U-Mail邮件系统六项特色服务铸就金口碑

    评价一款邮件系统优劣的标准或许有很多,左右你是否选择某个平台的需求或许有不同,但是U-Mail小编必须提醒你:服务水准不可等闲视之!之所以如此, 这是因为:现代社会垃圾邮件猖獗,病毒层出不穷令人防不胜 ...

  5. loadrunner 编写socket脚本实例(附服务端实现)

    一.socket背景知识 这个咱就不废话了,网上一搜一大堆 二.本实例实现的功能 服务端接收客户端发送的字符串,并返回"5678succ"共8个字符 三.服务端实现(java代码) ...

  6. Eclipse 的常用快捷方式

    快捷方式<!--[if !supportLists]-->0. Ctrl + 1 (快速修复)<!--[if !supportLists]-->1. Ctrl + D (删除当 ...

  7. scala 学习之:list span 用法

    Pack consecutive duplicates of list elements into sublists. If a list contains repeated elements the ...

  8. UNIX:高级环境编程 - 第十五章 IPC:进程间通信

    IPC(InterProcess Communication)进程间通信.为啥没有进程间通信,这是因为进程间都是同步的关系,不需要通信. 1.管道 1.1管道特点: (1)半双工的(即数据只能在一个方 ...

  9. PostrgreSQL 表名大小些问题(public."tablename")

    问题: 今天做表查询的时候,发现用以前的代码查询出现问题,提示说表名不存在. 现象: 通过PostrgreSQL客户端查询,发现出问题的表的查询语句如下: SELECT * FROM public.& ...

  10. C代码编译成可执行程序的过程

    C代码通过编译器编译成可执行代码,经历了四个阶段,依次为:预处理.编译.汇编.链接. 接下来详细讲解各个阶段 一.预处理 1.任务:进行宏定义展开.头文件展开.条件编译,不检查语法. 2.命令:gcc ...