微信应用js-sdk自定义分享图文

大兔子大兔子 提交于 2020-04-06 08:46:03

之前写过步骤 但是代码很少 这里奉献上我自己写的代码

我是用js做的 先奉上js部分的代码

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>众悦学车无忧险 免费申领</title>
    <meta name="description" content="李才桃">
    <meta name="keywords" content="李才桃">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <link rel="icon" type="image/png" href="assets/i/favicon.png">
    <link rel="stylesheet" href="assets/css/amazeui.min.css">
    <link href="css/app.css" rel="stylesheet" type="text/css" />
    <script src="assets/js/jquery-1.8.3.min.js" type="text/javascript"></script>
    <script src="assets/js/amazeui.min.js" type="text/javascript"></script>
    <script src="assets/js/jquery.min.js" type="text/javascript"></script> 
    <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () { GetDate(); })
        function getcanshu(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }
        function GetDate() {
            $.ajax({
                type: 'POST',
                url: 'handler.ashx?url=' + encodeURIComponent(location.href.split('#')[0]),
                dataType: "text",
                data: {
                    "dynamicUrl": encodeURIComponent(location.href.split('#')[0])
                },
                complete: function (XMLHttpRequest, textStatus) {
                },
                success: function (data) {
                    var a = data.split(',');
                    var timestamp = a[1];
                    var nonceStr = a[2];
                    var jsapi_ticket = a[3];
                    var sigu = a[4];
                    var url = a[5];
                    wx.config({
                        debug: false,
                        appId: '你的微信公众号',
                        timestamp: timestamp,
                        nonceStr: nonceStr,
                        signature: sigu,
                        jsApiList: [
                        'checkJsApi',
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage',
                        'onMenuShareQQ',
                        'onMenuShareWeibo'
                        ]
                    });
                    wx.checkJsApi({
                        jsApiList: ['checkJsApi',
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo'], // 需要检测的JS接口列表,所有JS接口列表见附录2,
                        success: function (res) {
                            $("#TextBox1").val(res);
                            // 以键值对的形式返回,可用的api值true,不可用为false
                            // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                            // alert('wx.error: ' + JSON.stringify(res));
                        }
                    });
                    wx.ready(function () {
                        var title = "众悦学车无忧险 免费申领";
                        var wxname = $("#hidd_wxname").val();
                        var content = wxname + "喊你免费来领\"众悦考试险\",驾考不过赔学费,众悦携手中国平安为您全程护航!";
                        var img = "http://m.zyue.com/wxtest/assets/gaoxiaoimages/gxwxads.png";
                        //var link = encodeURIComponent(location.href.split('#')[0]);
                        var link = "http://m.zyue.com/wxtest/gaoxiaoindex.aspx";

                        //分享到朋友圈
                        wx.onMenuShareTimeline({
                            title: title, // 分享标题
                            link: link, // 分享链接
                            imgUrl: img, // 分享图标
                            success: function () {
                                // 用户确认分享后执行的回调函数
                            },
                            cancel: function () {
                                // 用户取消分享后执行的回调函数
                            }
                        });
                        // 获取“分享给朋友”按钮点击状态及自定义分享内容接口
                        wx.onMenuShareAppMessage({
                            title: title, // 分享标题
                            desc: content, // 分享描述
                            link: link, // 分享链接
                            imgUrl: img, // 分享图标
                            type: '', // 分享类型,music、video或link,不填默认为link
                            dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
                            success: function () {
                                // 用户确认分享后执行的回调函数
                            },
                            cancel: function () {
                                // 用户取消分享后执行的回调函数
                            }
                        });
                        //获取“分享到QQ”按钮点击状态及自定义分享内容接口
                        wx.onMenuShareQQ({
                            title: title, // 分享标题
                            desc: content, // 分享描述
                            link: link, // 分享链接
                            imgUrl: img, // 分享图标
                            success: function () {
                                // 用户确认分享后执行的回调函数
                            },
                            cancel: function () {
                                // 用户取消分享后执行的回调函数
                            }
                        });
                        //获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口
                        wx.onMenuShareWeibo({
                            title: title, // 分享标题
                            desc: content, // 分享描述
                            link: link, // 分享链接
                            imgUrl: img, // 分享图标
                            success: function () {
                                // 用户确认分享后执行的回调函数
                            },
                            cancel: function () {
                                // 用户取消分享后执行的回调函数
                            }
                        });
                        //获取“分享到QQ空间”按钮点击状态及自定义分享内容接口
                        wx.onMenuShareQZone({
                            title: title, // 分享标题
                            desc: content, // 分享描述
                            link: link, // 分享链接
                            imgUrl: img, // 分享图标
                            success: function () {
                                // 用户确认分享后执行的回调函数
                            },
                            cancel: function () {
                                // 用户取消分享后执行的回调函数
                            }
                        });
                    });
                    wx.error(function (res) {
                        // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
                    });

                }
            });
        }
    </script>
    <script type="text/javascript">
        $(function ($) {

            //提交申请页面
            $("#example").hover(function () {
                $(this).stop().animate({
                    opacity: '1'
                }, 600);
            }, function () {
                $(this).stop().animate({
                    opacity: '1'
                }, 1000);
            }).on('click', function () {
                $("body").append("<div id='mask'></div>");
                $("#mask").addClass("mask").fadeIn("slow");
                $("#LoginBox").fadeIn("slow");
            });
            //
            //关闭
            $(".close_btn").hover(function () { $(this).css({ color: 'black' }) }, function () { $(this).css({ color: '#999' }) }).on('click', function () {
                $("#LoginBox").fadeOut("fast");
                $("#mask").css({ display: 'none' });
            });

            //申请成功页面
            //弹出登录
            $("#example_successful").hover(function () {
                $(this).stop().animate({
                    opacity: '1'
                }, 600);
            }, function () {
                $(this).stop().animate({
                    opacity: '1'
                }, 1000);
            }).on('click', function () {
                $("body").append("<div id='mask_successful'></div>");
                $("#mask_successful").addClass("mask_successful").fadeIn("slow");
                $("#LoginBox_successful").fadeIn("slow");
                var canshu = getcanshu("z_openid");
                $.ajax({
                    type: 'POST',
                    url: 'ashx/addoneclick.ashx',
                    dataType: "text",
                    data: {
                        "openid": canshu
                    }
                });
            });
        });
        function UserAddVerfy() {
            var addName = document.getElementById("input_name").value;
            var addTel = document.getElementById("input_photo").value;
            var addCity = document.getElementById("input_city").value;
            var addschool = document.getElementById("input_school").value;
            var addTelReg = /^1\d{10}$/;
            if (addName == "" || addName == null) {
                alert("请输入用户名");
                return false;
            }
            else if (addTel == "" || addTel == null || !addTelReg.test(addTel)) {
                alert("请输入手机号码");
                return false;
            }
            else if (addCity == "" || addCity == null) {
                alert("请输入城市");
                return false;
            }
            else if (addschool == "" || addschool == null) {
                alert("请输入学校");
                return false;
            }
            return true;
        }
        function getcanshu(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }
        
    </script>
</head>

 

异步操作的代码

<%@ WebHandler Language="C#" Class="handler" %>

using System;
using System.Web;
using System.IO;
using System.Data;
using System.Text;
using System.Web.UI;
using System.Threading;
using System.Xml;

public class handler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        string timeStamp = TenpayUtil.getTimestamp();
        string nonceStr = TenpayUtil.getNoncestr();
        string appid = "你的微信公众号";
        ////获取公众号的access_token
        string gongzhong = GetPage("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的微信公众号&secret=dc29b4e4f0c0827b19315e8c3068ca94");
        gongzhonghao hao = JsonDeserialize<gongzhonghao>(gongzhong);
        string token = hao.access_token;
        string ticket = GetPage("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=FaQRGJggiL4cbyi3YpDKY6RZMltz2MZXfGZbJLpse5MKn4EsxHyA7VbfarQ76kVN9OgtzUuLIxxRdHRroRa0TqXxbtN1EgAvDBvM0FVgcmU&type=jsapi");
       string jstik = Getjsapi_tiket(token);
        string url = context.Request.QueryString["url"].ToString();
        string singture = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile("jsapi_ticket=" + jstik + "&noncestr=" + nonceStr + "&timestamp=" + timeStamp + "&url=" + url + "", "SHA1");
        context.Response.Write(appid + "," + timeStamp + "," + nonceStr + "," + jstik + "," + singture.ToLower() + "," + url);
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    /// <summary>
    /// 获取微信令牌
    /// </summary>
    /// <returns></returns>
    public string Getjsapi_tiket(string token)
    {
        FileStream fs1 = new FileStream("d:/webwz/m/wxtest/jsapi_tiket.txt", FileMode.Open);
        StreamReader sr = new StreamReader(fs1, Encoding.GetEncoding("GBK"));
        string AccToken = sr.ReadToEnd();
        sr.Close();
        fs1.Close();
        getqianming at = JsonDeserialize<getqianming>(AccToken);
        if (DateTime.Now > Convert.ToDateTime(at.expires_in))
        {
            //当前时间大于过期时间就重新获取jsapi_tiket令牌
            //获取到微信返回的json数据
            string ticket = GetPage("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=jsapi");
            getqianming jstiket = JsonDeserialize<getqianming>(ticket);
            string jstik = jstiket.ticket;
            //将返回的数据写入到文件内
            //{"errcode":0,"errmsg":"ok","ticket":"bxLdikRXVbTPdHSM05e5u6THi9cRoPFeaORrzm-Klx3NMKJVnp0u-oa3DL920A6AsEBxM2DZTRCAkXlS5yoIkg","expires_in":7200}
            //E:/work1/wxtest/jsapi_tiket.txt
            WriteToFile("d:/webwz/m/wxtest/jsapi_tiket.txt", "{\"errcode\":" + jstiket.errcode + ",\"errmsg\":\"" + jstiket.errmsg + "\",\"ticket\":\"" + jstik + "\",\"expires_in\":\"" + DateTime.Now.AddSeconds(Convert.ToInt32(jstiket.expires_in) - 300) + "\"}", false);
            return jstik;
        }
        else
        { //未过期就继续使用从文档中获取的AccessToken令牌
            return at.ticket;
        }
    }
    /// <summary>
    /// 写入文件
    /// </summary>
    /// <param name="dizhi">写入地址</param>
    /// <param name="content">写入内容</param>
    public string WriteToFile(string dizhi, string content, bool isfugai)
    {
        string message = string.Empty;
        try
        {
            System.IO.FileInfo file = new System.IO.FileInfo(dizhi);
            //独占方式,因为文件只能由一个进程写入.
            System.IO.StreamWriter writer1 = null;
            writer1 = new System.IO.StreamWriter(file.FullName, isfugai);//文件不存在就创建
            writer1.WriteLine(content);
            writer1.Close();
        }
        catch
        {
            message = "已有人在同步数据请稍后同步";
        }
        return message;
    }


    /// <summary>
    /// 获取gongzhonghao 公众号的access_token
    /// </summary>
    public class gongzhonghao
    {
        /// <summary>
        /// 网页授权接口调用凭证
        /// </summary>
        public string access_token { get; set; }
        /// <summary>
        /// access_token接口调用凭证超时时间
        /// </summary>
        public string expires_in { get; set; }
    }
    /// <summary>
    /// 获取jsapi_ticket
    /// </summary>
    public class getqianming
    {
        public string errcode { get; set; }
        public string errmsg { get; set; }
        public string ticket { get; set; }
        public string expires_in { get; set; }
    }
    public class TenpayUtil
    {
        /// <summary>
        /// 统一支付接口
        /// </summary>
        const string UnifiedPayUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";

        /// <summary>
        /// 网页授权接口
        /// </summary>
        const string access_tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";

        /// <summary>
        /// 微信订单查询接口
        /// </summary>
        const string OrderQueryUrl = "https://api.mch.weixin.qq.com/pay/orderquery";

        /// <summary>
        /// 随机串
        /// </summary>
        public static string getNoncestr()
        {
            Random random = new Random();
            return MD5Util.GetMD5(random.Next(1000).ToString(), "GBK").ToUpper().Replace("s", "S");
        }

        /// <summary>
        /// 时间截,自1970年以来的秒数
        /// </summary>
        public static string getTimestamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }
        /// <summary>
        /// 获取签名
        /// </summary>
        public class Jsapiticket
        {
            public string errcode { get; set; }
            public string errmsg { get; set; }
            public string ticket { get; set; }
            public string expires_in { get; set; }
        }

    }
    public class MD5Util
    {
        public MD5Util()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        /** 获取大写的MD5签名结果 */
        public static string GetMD5(string encypStr, string charset)
        {
            string retStr;
            System.Security.Cryptography.MD5CryptoServiceProvider m5 = new System.Security.Cryptography.MD5CryptoServiceProvider();

            //创建md5对象
            byte[] inputBye;
            byte[] outputBye;

            //使用GB2312编码方式把字符串转化为字节数组.
            try
            {
                inputBye = System.Text.Encoding.GetEncoding(charset).GetBytes(encypStr);
            }
            catch (Exception ex)
            {
                inputBye = System.Text.Encoding.GetEncoding("GB2312").GetBytes(encypStr);
            }
            outputBye = m5.ComputeHash(inputBye);

            retStr = System.BitConverter.ToString(outputBye);
            retStr = retStr.Replace("-", "").ToUpper();
            return retStr;
        }
    }
    /// <summary>
    /// json格式转化
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="jsonString"></param>
    /// <returns></returns>
    public T JsonDeserialize<T>(string jsonString)
    {
        System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
        System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonString));
        T obj = (T)ser.ReadObject(ms);
        return obj;
    }
    public string GetPage(string posturl)
    {
        System.IO.Stream instream = null;
        System.IO.StreamReader sr = null;
        System.Net.HttpWebResponse response = null;
        System.Net.HttpWebRequest request = null;
        System.Text.Encoding encoding = System.Text.Encoding.UTF8;
        // 准备请求...  
        try
        {
            // 设置参数  
            request = System.Net.WebRequest.Create(posturl) as System.Net.HttpWebRequest;
            System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            //发送请求并获取相应回应数据  
            response = request.GetResponse() as System.Net.HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求  
            instream = response.GetResponseStream();
            sr = new System.IO.StreamReader(instream, encoding);
            //返回结果网页(html)代码  
            string content = sr.ReadToEnd();
            string err = string.Empty;
            return content;
        }
        catch (Exception ex)
        {
            string err = ex.Message;
            return "错误";
        }
    }

}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!