微信jssdk配置的问题,使用MVC制作的demo

一,view代码

<script src="~/Scripts/jquery-3.3.1.js"></script>
<script src="~/Scripts/jweixin-1.4.0.js"></script>
@*<script src="~/Scripts/jweixin-1.0.0.js"></script>*@
<script>
    wx.config({
        debug: true,
                appId: "@ViewBag.AppId",
                timestamp: "@ViewBag.timestamp",
                nonceStr: "@ViewBag.nonceStr",
                signature: "@ViewBag.signature",

        jsApiList: [
                    "checkJsApi",
                    "onMenuShareAppMessage",
                ]
    });
    wx.ready(function () {
        wx.checkJsApi({
            jsApiList: ['onMenuShareAppMessage'], // 需要检测的JS接口列表,所有JS接口列表见附录2,
            success: function (res) {
                // 以键值对的形式返回,可用的api值true,不可用为false
                // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
            }
        });

        wx.error(function (res) {
            //alert(res);
        });
        wx.onMenuShareAppMessage({
            title: '测试', // 分享标题
            desc: '测试', // 分享描述
            link: 'http://chwmay.51mypc.cn/Home/Index', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: 'https://i.vzan.cc/image/liveimg/jpeg/2018/4/13/185209cf7bdd0050fd4ced84b0a64aded068ef.jpeg', // 分享图标
            type: 'link',
            dataUrl: '',
            success: function () {
                alert(1);
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
    })
</script>

二,控制器代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebTestDemo.Code;

namespace WebTestDemo.Controllers
{
    /// <summary>
    /// 微信JSSDK的使用
    /// </summary>
    public class JssdkController : BaseController
    {
        public static string AppId = "";
        public static string timestamp = "";
        public static string nonceStr = "";
        public static string signature = "";

        public ActionResult Index()
        {
            timestamp = JssdkHelper.ConvertDateTimeInt(DateTime.Now).ToString();   //时间戳获取当前时间
            nonceStr = "Test" + new Random().Next(1, 1000) + "Demo";               //随机字符串没有固定的字符和没有特定的格式
            string url = HttpContext.Request.Url.ToString();  // url(当前网页的URL,不包含#及其后面部分)
            url = url.Substring(0, url.IndexOf('#') == -1 ? url.Length : url.IndexOf('#'));
            signature = JssdkHelper.ReturnSignature(timestamp, nonceStr, url);
            ViewBag.AppId = JssdkHelper.appid;
            ViewBag.timestamp = timestamp;
            ViewBag.nonceStr = nonceStr;
            ViewBag.signature = signature;
            return View();
        }
    }
}

三,JSSDK帮助类代码

    public static class JssdkHelper
    {

        public const string appid = "你的appid";
        public const string appsecret = "你的appsecret ";
        public const string baseurl = "https://api.weixin.qq.com/";
        public const string openurl = "https://open.weixin.qq.com/";
        public const string token = "test";

        public static int ConvertDateTimeInt(DateTime time)
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        /// <summary>
        /// 返回签名
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <returns></returns>
        public static string ReturnSignature(string timestamp, string nonce, string url)
        {
            string tmpStr = string.Empty;
            string jsapi_ticket = Getjsapi_ticket();
            SortedList<string, string> SLString = new SortedList<string, string>();

            SLString.Add("jsapi_ticket", jsapi_ticket);
            SLString.Add("noncestr", nonce);
            SLString.Add("timestamp", timestamp);
            SLString.Add("url", url);
            foreach (KeyValuePair<string, string> des in SLString)  //返回的是KeyValuePair,在学习的时候尽量少用var,起码要知道返回的是什么
            {
                tmpStr += des.Key + "=" + des.Value + "&";
            }
            if (tmpStr.Length > 0)
                tmpStr = tmpStr.Substring(0, tmpStr.Length - 1);
            return Utils.SHA1Encrypt(tmpStr);
        }

        /// <summary>
        /// 获取Token
        /// </summary>
        /// <returns></returns>
        public static string GetToken()
        {
            string token = CookieHelper.GetCookie(CookieHelper.StrWXTokenCookieName);
            if (string.IsNullOrEmpty(token))
            {
                string url = string.Format("{0}cgi-bin/token?grant_type=client_credential&appid={1}&secret={2}", baseurl, appid, appsecret);
                string str = Utils.HttpGet(url);
                JObject j = JObject.Parse(str);
                token = j.Value<string>("access_token");
            }

            return token;
        }
        public static string Getjsapi_ticket()
        {
            string access_token = GetToken();
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", access_token);
            string backStr = HttpClientHelper.GetResponse(url);
            //string backStr = "{ \"errcode\":0,\"errmsg\":\"ok\",\"ticket\":\"kgt8ON7yVITDhtdwci0qeZWDYY9llY5RrKsWxKD--zOUIRYqJ1XwMo305bwZhG22b5hOl-TZ-gZAXCbMMHwvCw\",\"expires_in\":7200}";
            string str_ticket = backStr.Split(',')[2].Split(':')[1];
            string Jsapi_ticket = str_ticket.Substring(1, str_ticket.Length - 2);
            return Jsapi_ticket;
        }

    }

四,invalid url domain出现后的解决方法

在微信开发文档中有一个这样的解决方法,当前页面所在域名与使用的appid没有绑定,请确认正确填写绑定的域名,仅支持80(http)和443(https)两个端口,因此不需要填写端口号,但这个是什么意思呢?
1,建议在IIS部署的网站是80端口,如果是还出现问题就看2,就是JS接口安全域名这里的配置有问题,js安全域名怎么配置呢?
2,先去掉http,比如我们的域名是www,xxx.com,我们不能配置成http://www,xxx.com/Jssdk/Index,要去掉http://以及后面的文件目录(/Jssdk/Index),写成www,xxx.com即可

 

posted @ 2018-09-17 16:29  叶丶梓轩  阅读(350)  评论(0编辑  收藏  举报