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分享插件,集成了我们公司常用的几个分享平台. 但是总感觉之前的结构上很不理想,样式,行为揉成一起,心里想的做的完美,实际上总是很多的偏差,所以这次我对其进行了改版. ...
随机推荐
- 全局安装npm包报错没有权限
背景:npm i npm-check -g 时报错没有权限 Error: EACCES: permission denied, access '/usr/local/lib/node_modules' ...
- Redis学习之zskiplist跳跃表源码分析
跳跃表的定义 跳跃表是一种有序数据结构,它通过在每个结点中维持多个指向其他结点的指针,从而达到快速访问其他结点的目的 跳跃表的结构 关于跳跃表的学习请参考:https://www.jianshu.co ...
- HttpRuntime.Cache 与 HttpContext.Current.Cache
1.HttpRuntime.Cache是应用程序级别的, 2.而HttpContext.Current.Cache是针对当前WEB上下文定义的. 3.这二个都是调用的同一个对象,不同的是:HttpRu ...
- pom文件语法无误却报红叉(Unknown error)的可能原因
本文链接:https://blog.csdn.net/Little_Stars/article/details/94553090可能原因及解决办法: >> 缓存问题,只要 “Maven - ...
- Git 版本及版本范围表示法
很多 Git 命令都使用 revision(修订版本)作为参数.根据不同的命令,有时候 revision 参 数代表一个特定的提交,有时候代表某一个提交可以追踪到的所有的父提交(比如 git log) ...
- GitHub 上受欢迎的 Android UI Library整理
https://github.com/Tapadoo/Alerter ★2528 - 克服Toast和Snackbar的限制 https://github.com/wenmingvs/NotifyUt ...
- 4-rocketmq 发送时异常:system busy 和 broker busy 解决方案
原文:https://www.cnblogs.com/enenen/p/10138511.html 推荐阅读:https://juejin.im/post/5d996285f265da5bad4052 ...
- 高德地图的JSAPI学习笔记【一】
高德地图的项目要做 学习笔记记录下来 一.注册账号并申请Key 二.准备页面写好 1.在页面添加 JS API 的入口脚本标签,并将其中「您申请的key值」替换为您刚刚申请的 key: <sc ...
- vue 利用路由跨页传参
第一页,点击进入第二页进行传值: <template> <div id="app"> <div><router-link to=" ...
- 理解AMD ,CMD,CommonJS规范
https://blog.csdn.net/xcymorningsun/article/details/52709608 理解AMD ,CMD,CommonJS规范 2016年09月30日 10:33 ...