Asp.Net微信js分享

1、准备工作
官方文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#111
必须是认证过的公众号才可以,先登录微信公众平台进入“公众号设置”的“功能设置”里填写“js接口安全域名”、“网页授权域名”
然后在开发设置中获取AppID和AppSecret,并设置ip白名单
2、前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>https://www.cnblogs.com/webapi/</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<meta name="description" content="https://www.cnblogs.com/webapi/" />
<meta name="keywords" content="https://www.cnblogs.com/webapi/" />
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<script src="https://cdn.bootcss.com/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script type="text/javascript">
var pagetUrl = window.location.href;
$(function () {
//--微信JS配置
if (wx != null && wx != undefined) {
if (pagetUrl.indexOf("#") > 0) {
pagetUrl = str.substring(0, pagetUrl.indexOf("#"));
}
$.ajax({
url: "weixinshare.aspx",
type: "post",
data: { purl: pagetUrl },
dataType: "json",
success: function (data) {
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: data.appid, // 必填,公众号的唯一标识
timestamp: data.timestamp, // 必填,生成签名的时间戳
nonceStr: data.nonceStr, // 必填,生成签名的随机串
signature: data.signature, // 必填,签名,见附录1
jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
}
});
wx.ready(function () {
//自定义“分享给朋友”及“分享到QQ”按钮的分享内容(1.4.0)
wx.ready(function () { //需在用户可能点击分享按钮前就先调用
wx.updateAppMessageShareData({
title: '微信分享测试-分享标题', // 分享标题
desc: '微信分享测试-分享描述,微信分享测试-分享描述', // 分享描述
link: pagetUrl, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: 'https://www.baidu.com/img/bd_logo1.png', // 分享图标
success: function () {
// 设置成功
}
})
});
//自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容(1.4.0)
wx.ready(function () { //需在用户可能点击分享按钮前就先调用
wx.updateTimelineShareData({
title: '微信分享测试-分享标题,微信分享测试-分享描述', // 分享标题
link: pagetUrl, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: 'https://www.baidu.com/img/bd_logo1.png', // 分享图标
success: function () {
// 设置成功
}
})
});
});
}
});
</script>
</head>
<body>
<h1>微信分享测试</h1>
<div>
微信JS-SDK是微信公众平台 面向网页开发者提供的基于微信内的网页开发工具包。通过使用微信JS-SDK,网页开发者可借助微信高效地使用拍照、选图、语音、位置等手机系统的能力,同时可以直接使用微信分享、扫一扫、卡券、支付等微信特有的能力,为微信用户提供更优质的网页体验。此文档面向网页开发者介绍微信JS-SDK如何使用及相关注意事项
</div>
</body>
</html>
3、后台
using LitJson;
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text; public partial class weixin_weixin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#111 string url = Request.Form["purl"]; string appid = "wxd111111111111";
string appSecret = "";
string jsapiTicket = getJsApiTicket(appid, appSecret);
// 获取时间戳
string timestamp = Convert.ToString(GetTimeStamp());
// 获取随机字符串
string nonceStr = createNonceStr();
// 获取签名signature
string rawstring = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + nonceStr + "×tamp=" + timestamp + "&url=" + url + "";
string signature = SHA1_Hash(rawstring);
// 返回的json
string json = "{\"appid\":\"" + appid + "\",\"timestamp\":\"" + timestamp + "\",\"nonceStr\":\"" + nonceStr + "\",\"signature\":\"" + signature + "\"}";
Response.Write(json);
Response.End();
}
//创建随机字符串
public string createNonceStr()
{
int length = ;
string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string str = "";
Random rad = new Random();
for (int i = ; i < length; i++)
{
str += chars.Substring(rad.Next(, chars.Length - ), );
}
return str;
}
public string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(, , , , , , );
return Convert.ToInt64(ts.TotalSeconds).ToString();
} public string SHA1_Hash(string str_sha1_in)
{
SHA1 sha1 = new SHA1CryptoServiceProvider();
byte[] bytes_sha1_in = System.Text.UTF8Encoding.Default.GetBytes(str_sha1_in);
byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in);
string str_sha1_out = BitConverter.ToString(bytes_sha1_out);
str_sha1_out = str_sha1_out.Replace("-", "").ToLower();
return str_sha1_out;
}
// 获取Token
public string GetToken(string appid, string secret)
{
//获取token,有效期7200秒,需要cache
string strJson = string.Empty;
if (GetCache("token") != null)
{
strJson = GetCache("token").ToString();
}
else {
strJson = RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret));
SetCache("token", strJson, );
} JsonData jd = JsonMapper.ToObject(strJson);
return jd["access_token"].ToString();
}
//获取ticket
public string getJsApiTicket(string appid, string appSecret)
{
//获取ticket,有效期7200秒,需要cache
string token = GetToken(appid, appSecret); string strJson = string.Empty;
if (GetCache("ticket") != null)
{
strJson = GetCache("ticket").ToString();
}
else
{
strJson = RequestUrl("https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=" + token);
SetCache("ticket", strJson, );
} JsonData jd = JsonMapper.ToObject(strJson);
return jd["ticket"].ToString();
}//公共方法,request网络获取
public string RequestUrl(string url)
{
// 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "get";
request.ContentType = "text/html";
request.Headers.Add("charset", "utf-8"); HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
string content = sr.ReadToEnd();
return content;
}
/// <summary>
/// 创建缓存项过期
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="obj">object对象</param>
/// <param name="expires">过期时间(分钟)</param>
public void SetCache(string key, object obj, int expires)
{
Cache.Insert(key, obj, null, DateTime.UtcNow.AddMinutes(expires), TimeSpan.Zero);
}
public object GetCache(string key)
{
if (string.IsNullOrEmpty(key))
{
return null;
}
return Cache.Get(key);
}
}
Asp.Net微信js分享的更多相关文章
- 微信JS分享功能--微信JS系列文章(二)
概述 在上一篇文章微信JS初始化-- 微信JS系列文章(一)中已经介绍了微信JS初始化的相关工作,接下来本文继续就微信JS的分享功能进行描述,供大家参考. 代码 $(document).ready(f ...
- 微信js分享朋友圈(二)
近期又用到微信分享的功能了.虽然不是第一次用了,依然我又有幸踩到了一个坑,所以分享一下吧. 根据微信sdk写的代码一步步很顺利,但是后面就是获取微信返回的分享结果的回调的时候IOS老是有问题,然后就网 ...
- 微信js分享朋友圈(一)
1.绑定域名 先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”. 备注:登录后可在“开发者中心”查看对应的接口权限. 2.引入js文件 <script type=&q ...
- 微信JS SDK配置授权,实现分享接口
微信开放的JS-SDK面向网页开发者提供了基于微信内的网页开发工具包,最直接的好处就是我们可以使用微信分享.扫一扫.卡券.支付等微信特有的能力.7月份的时候,因为这个分享的证书获取问题深深的栽了一坑, ...
- 微信网页JS分享,微信二次分享无缩略图问题
很多时候我们要在微信中分享h5网页,这个时候就得用微信的分享接口来自定义分享的地址.标题.描述.缩略图了. 分享到微信的时候遇到一个问题,就是第一次分享到微信里,是正确的,但是在微信打开分享的链接,再 ...
- asp.net中js和jquery调用ashx的不同方法分享,需要的朋友可以参考一下
asp.net中js和jquery调用ashx的不同方法分享,需要的朋友可以参考一下 =============js================ 复制代码代码如下: var xhr = n ...
- 微信js sdk分享开发摘记java版
绑定域名和引入js的就不说了 废话不说直接上代码 public void share(HttpServletRequest request) throws Exception { StringBuff ...
- 微信JS接口
微信JS接口 分享到朋友圈 分享给朋友 分享到QQ 拍照或从手机相册中选图 识别音频并返回识别结果 使用微信内置地图查看位置来源:http://www.cnblogs.com/txw1958/p/ ...
- 自己封装的一个JS分享组件
因为工作的需求之前也封装过一个JS分享插件,集成了我们公司常用的几个分享平台. 但是总感觉之前的结构上很不理想,样式,行为揉成一起,心里想的做的完美,实际上总是很多的偏差,所以这次我对其进行了改版. ...
随机推荐
- c# .net core + .net framework mongodb nuget 包
FastNet.Framework.Mongo https://github.com/my-core/FastNet.Framework GH.MongoDb.GenericRepository ht ...
- Flink及Storm、Spark主流流框架比较
转自:http://www.sohu.com/a/142553677_804130 引言 随着大数据时代的来临,大数据产品层出不穷.我们最近也对一款业内非常火的大数据产品 - Apache Flink ...
- lock、tryLock和lockInterruptibly的差別
lock():若lock被thread A取得,thread B会进入block状态,直到取得lock:tryLock():若当下不能取得lock,thread就会放弃,可以设置一个超时时间参数,等待 ...
- dp - 最大子矩阵和 - HDU 1081 To The Max
To The Max Problem's Link: http://acm.hdu.edu.cn/showproblem.php?pid=1081 Mean: 求N*N数字矩阵的最大子矩阵和. ana ...
- 使用eclipse git插件合并merge部分代码方法
当有一个父项目,它的下面有多个子项目:或者一个项目下边,只想合并部分路径,甚至部分文件的内容,使用下边的方法可以达到目的,特此记录: 1.主项目右键 -> team -> remove f ...
- 数据库的dml、ddl和dcl的概念
学过数据库肯定会知道DML.DDL和DCL这三种语言,这种基础概念性的东西是必须要记住的. DML(Data Manipulation Lanaguage,数据操纵语言) DML就是我们经常用到的SE ...
- 使用kibana给不同的用户创建不同的space
Elastic安全机制 在很多的情况下,出于安全的原因,我们需要对不同的Kibana用户分配不同的用户权限,这样使得他们之间不能互相访问彼此的资源,同 时他们也应该对不同的索引拥有不同的权限,比如读, ...
- Python实现抽样分布的验证(正态分布、卡方分布、T分布)
参考链接:https://github.com/v-gazh/LearningStatsGroup/blob/master/week7/week7.ipynb 源地址:https://github.c ...
- 如何才能通俗易懂的解释js里面的‘闭包’?
1. "闭包就是跨作用域访问变量." [示例一] var name = 'wangxi' function user () { // var name = 'wangxi' fun ...
- 如何开发出成功的iOS应用(流程图)
转自:http://mobile.51cto.com/hot-307342.htm 近来,肥沃的应用开发土壤不断孕育出一个个振奋人心的故事,成千上万的人都觊觎从这个机遇无限的领域中分一杯羹.虽然现在的 ...