微信分享到朋友,朋友圈 后台.Net ,前台Uniapp

微信JS-SDK分享功能报错?手把手教你解决updateAppMessageShareData权限问题 本文针对微信JS-SDK中updateAppMessageShareData接口常见的“permission denied”报错,提供了一套完整的深度排障指南。文章从公众号安全域名配置、签名生成、前端wx.config调用时机等基础环节入手,重点剖析了jsApiList配置、新旧接口兼容性以及单页应用(SPA)路由变化等核心问题,并给出了具体的解决方案和诊断清单,帮助开发者彻底解决分享功能权限验证失败的问题。 阅读详情

先说下后台代码吧:

接入分享,这个代码可以是小程序分享,或者是公众号分享都可以使用,分享需要一段参数给前台,前台才可以进行分享

代码:

 public static class WxBase
    {
        /// <summary>
        /// 获取微信AccessToken
        /// </summary>
        /// <param name="AppID"></param>
        /// <param name="AppSecret"></param>
        /// <returns></returns>
        public static string GetAccessToken(string AppID, string AppSecret)
        {
            if (CacheHelper.GetCache("AccessToken") == null)
            {
                string data = HttpHelper.HttpGet(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", AppID, AppSecret));
                Dictionary<string, object> dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(data);
                try
                {
                    string access_token = dictionary["access_token"].ToString();
                    CacheHelper.SetCache("AccessToken", access_token, 7000);
                    return access_token;
                }
                catch (Exception)
                {

                    System.Web.HttpContext.Current.Response.Write(dictionary["errcode"] + "  " + dictionary["errmsg"]);
                    System.Web.HttpContext.Current.Response.End();
                }
            }
            return CacheHelper.GetCache("AccessToken").ToString();
        }


        /// <summary>
        ///获取微信jsapi_ticket
        /// </summary>
        /// <returns></returns>
        private static string GetJsapiTicket(string AppID, string AppSecret)
        {
            if (CacheHelper.GetCache("JsapiTicket") == null)
            {
                string AccessToken = GetAccessToken(AppID, AppSecret);
                string data = HttpHelper.HttpGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + AccessToken + "&type=jsapi");
                Dictionary<string, object> dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(data);
                string ticket = dictionary["ticket"].ToString();
                CacheHelper.SetCache("JsapiTicket", ticket, 7000);
                return ticket;

            }
            return CacheHelper.GetCache("JsapiTicket").ToString();
        }

        /// <summary>
        /// 权限签名(返回js需要的json)
        /// </summary>
        /// <param name="AppID"></param>
        /// <param name="AppSecret"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetSignature(string AppID, string AppSecret, string url)
        {
            string noncestr = Function.GetRndNum(10); //随机数
            string jsapi_ticket = GetJsapiTicket(AppID, AppSecret);  //jsapi_ticket
            string timestamp = GetTimeStamp();
            var sb = new StringBuilder();
            sb.Append("jsapi_ticket=").Append(jsapi_ticket).Append("&")
                          .Append("noncestr=").Append(noncestr).Append("&")
                          .Append("timestamp=").Append(timestamp).Append("&")
                          .Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url);
            var signature = Md5Helper.GetSha1String(sb.ToString());
            return "{\"appId\":\"" + AppID + "\",\"timestamp\":\"" + timestamp + "\",\"nonceStr\":\"" + noncestr + "\",\"signature\":\"" + signature + "\"}";
        }

        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }
    }

这个ticket都是需要进行先缓存起来得,缓存得类

 public class CacheHelper
    {
        /// <summary>  
        /// 获取数据缓存  
        /// </summary>  
        /// <param name="cacheKey">键</param>  
        public static object GetCache(string cacheKey)
        {
            var objCache = HttpRuntime.Cache.Get(cacheKey);
            return objCache;
        }
        /// <summary>  
        /// 设置数据缓存  
        /// </summary>  
        public static void SetCache(string cacheKey, object objObject)
        {
            var objCache = HttpRuntime.Cache;
            objCache.Insert(cacheKey, objObject);
        }
        /// <summary>  
        /// 设置数据缓存  
        /// </summary>  
        public static void SetCache(string cacheKey, object objObject, int timeout = 7200)
        {
            try
            {
                if (objObject == null) return;
                var objCache = HttpRuntime.Cache;
                //相对过期  
                //objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null);  
                //绝对过期时间  
                objCache.Insert(cacheKey, objObject, null, DateTime.Now.AddSeconds(timeout), TimeSpan.Zero, CacheItemPriority.High, null);
            }
            catch (Exception)
            {
                //throw;  
            }
        }
        /// <summary>  
        /// 移除指定数据缓存  
        /// </summary>  
        public static void RemoveAllCache(string cacheKey)
        {
            var cache = HttpRuntime.Cache;
            cache.Remove(cacheKey);
        }
        /// <summary>  
        /// 移除全部缓存  
        /// </summary>  
        public static void RemoveAllCache()
        {
            var cache = HttpRuntime.Cache;
            var cacheEnum = cache.GetEnumerator();
            while (cacheEnum.MoveNext())
            {
                cache.Remove(cacheEnum.Key.ToString());
            }
        }
    }

调用参数

 public ActionResult GetWeiXinJsParams()
        {
            ConfigHelper webConfigHelper = new ConfigHelper();//这个是系统配置

            string AppID = webConfigHelper.GetValueByKey("AppID");
            string AppSecret = webConfigHelper.GetValueByKey("AppSecret");
            var url = Request.Params["url"];//前台传入,需要分享页面得url 
          
            var res = Db.WeiXin.WxBase.GetSignature(AppID, AppSecret, url);
            return Content(res);
        }

前台调用

待测试,等测试完成再给大家写下

终于测试完了,给大家分享一下

首先需要引入微信js文件

!function(e,n){"function"==typeof define&&(define.amd||define.cmd)?define(function(){return n(e)}):n(e,!0)}(window,function(o,e){if(!o.jWeixin){var n,c={config:"preVerifyJSAPI",onMenuShareTimeline:"menu:share:timeline",onMenuShareAppMessage:"menu:share:appmessage",onMenuShareQQ:"menu:share:qq",onMenuShareWeibo:"menu:share:weiboApp",onMenuShareQZone:"menu:share:QZone",previewImage:"imagePreview",getLocation:"geoLocation",openProductSpecificView:"openProductViewWithPid",addCard:"batchAddCard",openCard:"batchViewCard",chooseWXPay:"getBrandWCPayRequest",openEnterpriseRedPacket:"getRecevieBizHongBaoRequest",startSearchBeacons:"startMonitoringBeacons",stopSearchBeacons:"stopMonitoringBeacons",onSearchBeacons:"onBeaconsInRange",consumeAndShareCard:"consumedShareCard",openAddress:"editAddress"},a=function(){var e={};for(var n in c)e[c[n]]=n;return e}(),i=o.document,t=i.title,r=navigator.userAgent.toLowerCase(),s=navigator.platform.toLowerCase(),d=!(!s.match("mac")&&!s.match("win")),u=-1!=r.indexOf("wxdebugger"),l=-1!=r.indexOf("micromessenger"),p=-1!=r.indexOf("android"),f=-1!=r.indexOf("iphone")||-1!=r.indexOf("ipad"),m=(n=r.match(/micromessenger\/(\d+\.\d+\.\d+)/)||r.match(/micromessenger\/(\d+\.\d+)/))?n[1]:"",g={initStartTime:L(),initEndTime:0,preVerifyStartTime:0,preVerifyEndTime:0},h={version:1,appId:"",initTime:0,preVerifyTime:0,networkType:"",isPreVerifyOk:1,systemType:f?1:p?2:-1,clientVersion:m,url:encodeURIComponent(location.href)},v={},S={_completes:[]},y={state:0,data:{}};O(function(){g.initEndTime=L()});var I=!1,_=[],w={config:function(e){B("config",v=e);var t=!1!==v.check;O(function(){if(t)M(c.config,{verifyJsApiList:C(v.jsApiList),verifyOpenTagList:C(v.openTagList)},function(){S._complete=function(e){g.preVerifyEndTime=L(),y.state=1,y.data=e},S.success=function(e){h.isPreVerifyOk=0},S.fail=function(e){S._fail?S._fail(e):y.state=-1};var t=S._completes;return t.push(function(){!function(){if(!(d||u||v.debug||m<"6.0.2"||h.systemType<0)){var i=new Image;h.appId=v.appId,h.initTime=g.initEndTime-g.initStartTime,h.preVerifyTime=g.preVerifyEndTime-g.preVerifyStartTime,w.getNetworkType({isInnerInvoke:!0,success:function(e){h.networkType=e.networkType;var n="https://open.weixin.qq.com/sdk/report?v="+h.version+"&o="+h.isPreVerifyOk+"&s="+h.systemType+"&c="+h.clientVersion+"&a="+h.appId+"&n="+h.networkType+"&i="+h.initTime+"&p="+h.preVerifyTime+"&u="+h.url;i.src=n}})}}()}),S.complete=function(e){for(var n=0,i=t.length;n<i;++n)t[n]();S._completes=[]},S}()),g.preVerifyStartTime=L();else{y.state=1;for(var e=S._completes,n=0,i=e.length;n<i;++n)e[n]();S._completes=[]}}),w.invoke||(w.invoke=function(e,n,i){o.WeixinJSBridge&&WeixinJSBridge.invoke(e,x(n),i)},w.on=function(e,n){o.WeixinJSBridge&&WeixinJSBridge.on(e,n)})},ready:function(e){0!=y.state?e():(S._completes.push(e),!l&&v.debug&&e())},error:function(e){m<"6.0.2"||(-1==y.state?e(y.data):S._fail=e)},checkJsApi:function(e){M("checkJsApi",{jsApiList:C(e.jsApiList)},(e._complete=function(e){if(p){var n=e.checkResult;n&&(e.checkResult=JSON.parse(n))}e=function(e){var n=e.checkResult;for(var i in n){var t=a[i];t&&(n[t]=n[i],delete n[i])}return e}(e)},e))},onMenuShareTimeline:function(e){P(c.onMenuShareTimeline,{complete:function(){M("shareTimeline",{title:e.title||t,desc:e.title||t,img_url:e.imgUrl||"",link:e.link||location.href,type:e.type||"link",data_url:e.dataUrl||""},e)}},e)},onMenuShareAppMessage:function(n){P(c.onMenuShareAppMessage,{complete:function(e){"favorite"===e.scene?M("sendAppMessage",{title:n.title||t,desc:n.desc||"",link:n.link||location.href,img_url:n.imgUrl||"",type:n.type||"link",data_url:n.dataUrl||""}):M("sendAppMessage",{title:n.title||t,desc:n.desc||"",link:n.link||location.href,img_url:n.imgUrl||"",type:n.type||"link",data_url:n.dataUrl||""},n)}},n)},onMenuShareQQ:function(e){P(c.onMenuShareQQ,{complete:function(){M("shareQQ",{title:e.title||t,desc:e.desc||"",img_url:e.imgUrl||"",link:e.link||location.href},e)}},e)},onMenuShareWeibo:function(e){P(c.onMenuShareWeibo,{complete:function(){M("shareWeiboApp",{title:e.title||t,desc:e.desc||"",img_url:e.imgUrl||"",link:e.link||location.href},e)}},e)},onMenuShareQZone:function(e){P(c.onMenuShareQZone,{complete:function(){M("shareQZone",{title:e.title||t,desc:e.desc||"",img_url:e.imgUrl||"",link:e.link||location.href},e)}},e)},updateTimelineShareData:function(e){M("updateTimelineShareData",{title:e.title,link:e.link,imgUrl:e.imgUrl},e)},updateAppMessageShareData:function(e){M("updateAppMessageShareData",{title:e.title,desc:e.desc,link:e.link,imgUrl:e.imgUrl},e)},startRecord:function(e){M("startRecord",{},e)},stopRecord:function(e){M("stopRecord",{},e)},onVoiceRecordEnd:function(e){P("onVoiceRecordEnd",e)},playVoice:function(e){M("playVoice",{localId:e.localId},e)},pauseVoice:function(e){M("pauseVoice",{localId:e.localId},e)},stopVoice:function(e){M("stopVoice",{localId:e.localId},e)},onVoicePlayEnd:function(e){P("onVoicePlayEnd",e)},uploadVoice:function(e){M("uploadVoice",{localId:e.localId,isShowProgressTips:0==e.isShowProgressTips?0:1},e)},downloadVoice:function(e){M("downloadVoice",{serverId:e.serverId,isShowProgressTips:0==e.isShowProgressTips?0:1},e)},translateVoice:function(e){M("translateVoice",{localId:e.localId,isShowProgressTips:0==e.isShowProgressTips?0:1},e)},chooseImage:function(e){M("chooseImage",{scene:"1|2",count:e.count||9,sizeType:e.sizeType||["original","compressed"],sourceType:e.sourceType||["album","camera"]},(e._complete=function(e){if(p){var n=e.localIds;try{n&&(e.localIds=JSON.parse(n))}catch(e){}}},e))},getLocation:function(e){},previewImage:function(e){M(c.previewImage,{current:e.current,urls:e.urls},e)},uploadImage:function(e){M("uploadImage",{localId:e.localId,isShowProgressTips:0==e.isShowProgressTips?0:1},e)},downloadImage:function(e){M("downloadImage",{serverId:e.serverId,isShowProgressTips:0==e.isShowProgressTips?0:1},e)},getLocalImgData:function(e){!1===I?(I=!0,M("getLocalImgData",{localId:e.localId},(e._complete=function(e){if(I=!1,0<_.length){var n=_.shift();wx.getLocalImgData(n)}},e))):_.push(e)},getNetworkType:function(e){M("getNetworkType",{},(e._complete=function(e){e=function(e){var n=e.errMsg;e.errMsg="getNetworkType:ok";var i=e.subtype;if(delete e.subtype,i)e.networkType=i;else{var t=n.indexOf(":"),o=n.substring(t+1);switch(o){case"wifi":case"edge":case"wwan":e.networkType=o;break;default:e.errMsg="getNetworkType:fail"}}return e}(e)},e))},openLocation:function(e){M("openLocation",{latitude:e.latitude,longitude:e.longitude,name:e.name||"",address:e.address||"",scale:e.scale||28,infoUrl:e.infoUrl||""},e)},getLocation:function(e){M(c.getLocation,{type:(e=e||{}).type||"wgs84"},(e._complete=function(e){delete e.type},e))},hideOptionMenu:function(e){M("hideOptionMenu",{},e)},showOptionMenu:function(e){M("showOptionMenu",{},e)},closeWindow:function(e){M("closeWindow",{},e=e||{})},hideMenuItems:function(e){M("hideMenuItems",{menuList:e.menuList},e)},showMenuItems:function(e){M("showMenuItems",{menuList:e.menuList},e)},hideAllNonBaseMenuItem:function(e){M("hideAllNonBaseMenuItem",{},e)},showAllNonBaseMenuItem:function(e){M("showAllNonBaseMenuItem",{},e)},scanQRCode:function(e){M("scanQRCode",{needResult:(e=e||{}).needResult||0,scanType:e.scanType||["qrCode","barCode"]},(e._complete=function(e){if(f){var n=e.resultStr;if(n){var i=JSON.parse(n);e.resultStr=i&&i.scan_code&&i.scan_code.scan_result}}},e))},openAddress:function(e){M(c.openAddress,{},(e._complete=function(e){e=function(e){return e.postalCode=e.addressPostalCode,delete e.addressPostalCode,e.provinceName=e.proviceFirstStageName,delete e.proviceFirstStageName,e.cityName=e.addressCitySecondStageName,delete e.addressCitySecondStageName,e.countryName=e.addressCountiesThirdStageName,delete e.addressCountiesThirdStageName,e.detailInfo=e.addressDetailInfo,delete e.addressDetailInfo,e}(e)},e))},openProductSpecificView:function(e){M(c.openProductSpecificView,{pid:e.productId,view_type:e.viewType||0,ext_info:e.extInfo},e)},addCard:function(e){for(var n=e.cardList,i=[],t=0,o=n.length;t<o;++t){var r=n[t],a={card_id:r.cardId,card_ext:r.cardExt};i.push(a)}M(c.addCard,{card_list:i},(e._complete=function(e){var n=e.card_list;if(n){for(var i=0,t=(n=JSON.parse(n)).length;i<t;++i){var o=n[i];o.cardId=o.card_id,o.cardExt=o.card_ext,o.isSuccess=!!o.is_succ,delete o.card_id,delete o.card_ext,delete o.is_succ}e.cardList=n,delete e.card_list}},e))},chooseCard:function(e){M("chooseCard",{app_id:v.appId,location_id:e.shopId||"",sign_type:e.signType||"SHA1",card_id:e.cardId||"",card_type:e.cardType||"",card_sign:e.cardSign,time_stamp:e.timestamp+"",nonce_str:e.nonceStr},(e._complete=function(e){e.cardList=e.choose_card_info,delete e.choose_card_info},e))},openCard:function(e){for(var n=e.cardList,i=[],t=0,o=n.length;t<o;++t){var r=n[t],a={card_id:r.cardId,code:r.code};i.push(a)}M(c.openCard,{card_list:i},e)},consumeAndShareCard:function(e){M(c.consumeAndShareCard,{consumedCardId:e.cardId,consumedCode:e.code},e)},chooseWXPay:function(e){M(c.chooseWXPay,V(e),e)},openEnterpriseRedPacket:function(e){M(c.openEnterpriseRedPacket,V(e),e)},startSearchBeacons:function(e){M(c.startSearchBeacons,{ticket:e.ticket},e)},stopSearchBeacons:function(e){M(c.stopSearchBeacons,{},e)},onSearchBeacons:function(e){P(c.onSearchBeacons,e)},openEnterpriseChat:function(e){M("openEnterpriseChat",{useridlist:e.userIds,chatname:e.groupName},e)},launchMiniProgram:function(e){M("launchMiniProgram",{targetAppId:e.targetAppId,path:function(e){if("string"==typeof e&&0<e.length){var n=e.split("?")[0],i=e.split("?")[1];return n+=".html",void 0!==i?n+"?"+i:n}}(e.path),envVersion:e.envVersion},e)},openBusinessView:function(e){M("openBusinessView",{businessType:e.businessType,queryString:e.queryString||"",envVersion:e.envVersion},(e._complete=function(n){if(p){var e=n.extraData;if(e)try{n.extraData=JSON.parse(e)}catch(e){n.extraData={}}}},e))},miniProgram:{navigateBack:function(e){e=e||{},O(function(){M("invokeMiniProgramAPI",{name:"navigateBack",arg:{delta:e.delta||1}},e)})},navigateTo:function(e){O(function(){M("invokeMiniProgramAPI",{name:"navigateTo",arg:{url:e.url}},e)})},redirectTo:function(e){O(function(){M("invokeMiniProgramAPI",{name:"redirectTo",arg:{url:e.url}},e)})},switchTab:function(e){O(function(){M("invokeMiniProgramAPI",{name:"switchTab",arg:{url:e.url}},e)})},reLaunch:function(e){O(function(){M("invokeMiniProgramAPI",{name:"reLaunch",arg:{url:e.url}},e)})},postMessage:function(e){O(function(){M("invokeMiniProgramAPI",{name:"postMessage",arg:e.data||{}},e)})},getEnv:function(e){O(function(){e({miniprogram:"miniprogram"===o.__wxjs_environment})})}}},T=1,k={};return i.addEventListener("error",function(e){if(!p){var n=e.target,i=n.tagName,t=n.src;if("IMG"==i||"VIDEO"==i||"AUDIO"==i||"SOURCE"==i)if(-1!=t.indexOf("wxlocalresource://")){e.preventDefault(),e.stopPropagation();var o=n["wx-id"];if(o||(o=T++,n["wx-id"]=o),k[o])return;k[o]=!0,wx.ready(function(){wx.getLocalImgData({localId:t,success:function(e){n.src=e.localData}})})}}},!0),i.addEventListener("load",function(e){if(!p){var n=e.target,i=n.tagName;n.src;if("IMG"==i||"VIDEO"==i||"AUDIO"==i||"SOURCE"==i){var t=n["wx-id"];t&&(k[t]=!1)}}},!0),e&&(o.wx=o.jWeixin=w),w}function M(n,e,i){o.WeixinJSBridge?WeixinJSBridge.invoke(n,x(e),function(e){A(n,e,i)}):B(n,i)}function P(n,i,t){o.WeixinJSBridge?WeixinJSBridge.on(n,function(e){t&&t.trigger&&t.trigger(e),A(n,e,i)}):B(n,t||i)}function x(e){return(e=e||{}).appId=v.appId,e.verifyAppId=v.appId,e.verifySignType="sha1",e.verifyTimestamp=v.timestamp+"",e.verifyNonceStr=v.nonceStr,e.verifySignature=v.signature,e}function V(e){return{timeStamp:e.timestamp+"",nonceStr:e.nonceStr,package:e.package,paySign:e.paySign,signType:e.signType||"SHA1"}}function A(e,n,i){"openEnterpriseChat"!=e&&"openBusinessView"!==e||(n.errCode=n.err_code),delete n.err_code,delete n.err_desc,delete n.err_detail;var t=n.errMsg;t||(t=n.err_msg,delete n.err_msg,t=function(e,n){var i=e,t=a[i];t&&(i=t);var o="ok";if(n){var r=n.indexOf(":");"confirm"==(o=n.substring(r+1))&&(o="ok"),"failed"==o&&(o="fail"),-1!=o.indexOf("failed_")&&(o=o.substring(7)),-1!=o.indexOf("fail_")&&(o=o.substring(5)),"access denied"!=(o=(o=o.replace(/_/g," ")).toLowerCase())&&"no permission to execute"!=o||(o="permission denied"),"config"==i&&"function not exist"==o&&(o="ok"),""==o&&(o="fail")}return n=i+":"+o}(e,t),n.errMsg=t),(i=i||{})._complete&&(i._complete(n),delete i._complete),t=n.errMsg||"",v.debug&&!i.isInnerInvoke&&alert(JSON.stringify(n));var o=t.indexOf(":");switch(t.substring(o+1)){case"ok":i.success&&i.success(n);break;case"cancel":i.cancel&&i.cancel(n);break;default:i.fail&&i.fail(n)}i.complete&&i.complete(n)}function C(e){if(e){for(var n=0,i=e.length;n<i;++n){var t=e[n],o=c[t];o&&(e[n]=o)}return e}}function B(e,n){if(!(!v.debug||n&&n.isInnerInvoke)){var i=a[e];i&&(e=i),n&&n._complete&&delete n._complete,console.log('"'+e+'",',n||"")}}function L(){return(new Date).getTime()}function O(e){l&&(o.WeixinJSBridge?e():i.addEventListener&&i.addEventListener("WeixinJSBridgeReady",e,!1))}});

我这个文件方的位置是这样的:

然后再自己疯转一个wchat.js方便使用

// 自己封装的 uni.request 工具类
var utils = require("../utils/util.js");
var api = require("../config/api.js");
var jweixin = require('../components/jweixin-module/index.js');

export default {
    //判断是否在微信中  
    isWechat: function() {
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/micromessenger/i) == 'micromessenger') {
            // console.log('是微信客户端')
            return true;
        } else {
            // console.log('不是微信客户端')
            return false;
        }
    },
    //初始化sdk配置  
    initJssdkShare: function(callback, url) {
        
        // 这是我这边封装的 request 请求工具,实际就是 uni.request 方法。
		utils.request(api.GetWeiXinJsParams,{url:url}).then(function(res) {
					
					jweixin.config({
					                        debug: false,
					                        appId: res.appId,
					                        timestamp: res.timestamp,
					                        nonceStr: res.nonceStr,
					                        signature: res.signature,
					                        jsApiList: [
					                            'checkJsApi',
					                            'onMenuShareTimeline',
					                            'onMenuShareAppMessage'
					                        ]
					                    });
					                    //配置完成后,再执行分享等功能  
					                    if (callback) {
					                        callback(res);
					                    }
				});
        
    },
    //在需要自定义分享的页面中调用  
    share: function(data, url) {
        url = url ? url : window.location.href;
       console.log(url);
        if (!this.isWechat()) {
            return;
        }
        //每次都需要重新初始化配置,才可以进行分享  
        this.initJssdkShare(function(signData) {
            jweixin.ready(function() {
                var shareData = {
                    title: data && data.title ? data.title : signData.site_name,
                    desc: data && data.desc ? data.desc : signData.site_description,
                    link: url,
                    imgUrl: data && data.img ? data.img : signData.site_logo,
                    success: function(res) {
                        // 分享后的一些操作,比如分享统计等等
                    },
                    cancel: function(res) {}
                };
                //分享给朋友接口  
                jweixin.onMenuShareAppMessage(shareData);
                //分享到朋友圈接口  
                jweixin.onMenuShareTimeline(shareData);
            });
        }, url);
    },
}

 

 

最后再main.js中进行声明下

// #ifdef H5
import wechat from './wechat/wechat.js';
if(wechat.isWechat()){
    Vue.prototype.$wechat =wechat;
}
// #endif

在你需要分享的页面中进行调用:

if (that.$wechat && that.$wechat.isWechat()) {
					    that.$wechat.share({
							title:that.goods.name,
					        desc: that.goods.goods_desc,  
					        img: that.imgUrl+that.gallery[0].img_url 
					    },shareurl);
					}//这个shareurl是你分享的页面的url,如果不传递,默认是当前页面

这样在页面的三个小圆点处进行分享,就可以了,帮到你了,给点个赞吧

UniApp跨端应用安全获取微信小程序URL Link的HTTPS调用实战 在移动应用开发中,实现不同应用或页面间的无缝跳转是提升用户体验的关键技术,其核心在于深度链接(Deep Linking)机制。该机制通过特定的URI协议或链接,将用户精准引导至应用内的指定内容。其技术价值在于打破应用孤岛,实现场景化服务串联,尤其在电商、社交、内容分发等场景中至关重要。微信小程序生态提供的URL Link服务,正是一种云生成的动态深度链接,它基于HTTPS协议保障了通信安全与可靠性。本文聚焦于如何在UniApp这一跨端框架中,通过规范的HTTPS接口调用,安全、高效地获取并利用URL Lin 阅读详情

相关推荐

uniapp绘制个人名片分享

【代码】uniapp绘制个人名片分享。

m0_46701899的博客 849

记录--微信调用jssdk--Invalid Signature, updateAppMessageShareData: denied等问题

这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助 最近在做安卓内嵌入H5活动页拉新活动,遇到的棘手问题记录下, 一是为了日后遇到同样问题好回顾,二是希望能帮到有同样问题的兄弟。 废话不多说,先从最棘手的问题直接开始: 一、Invalid Signature 1.因为项目内是Vue中的hash模式,所以遇到这个问题时,一直怀疑hash模式是不是不可以。——其实可以,hash和hi...

林恒的博客 4179

记录vue做微信自定义分享的一些问题

前言 众所周知,在使用vue做项目的时候,微信自定义分享一直是一个坑,只是ios上坑明显的多。 然后每次遇到问题都要度娘很久。 奇怪的是貌似和很多人遇到的问题一样,但是他们写的解决方案都没办法直接解决我遇到的问题。 这里就记录一下遇到过的一些坑,和解决方式。 目前项目里面,安卓和ios上面的自定义分享已经没有什么问题了。 问题及解决方式 hash模式 在微信的官方文档中,提到关于jsapi_tic...

weixin_43958892的博客 500

【解决】updateAppMessageShareData:fail, the permission value is offline verifying

【问题】 使用微信SDK的分享接口wx.updateAppMessageShareData时,控制台出现‘updateAppMessageShareData:fail, the permission value is offline verifying’错误提示。 【解决】 jsApiList里面声明updateAppMessageShareData方法。 示例代码如下: wx.config({ debug: false, appId: data.appId, timestamp: dat

huangfuyk.的博客 1万+

微信JS-SDK分享功能避坑指南:为什么你的updateAppMessageShareData总报错?

本文深入解析微信JS-SDK分享功能中updateAppMessageShareData接口常见的“permission denied”等报错原因,提供从权限配置、签名生成到前端集成的完整实战解决方案。重点剖析了jsApiList声明、URL签名、SPA兼容性等核心避坑点,帮助开发者实现稳定可靠的自定义分享功能。

a3b4c5的博客 180

【实战】微信JS-SDK分享权限验证全解析:从updateAppMessageShareData报错到完美解决

本文深入解析微信JS-SDK分享功能中常见的updateAppMessageShareData报错问题,提供从公众号后台配置、后端签名到前端初始化的完整排查链路。针对“offline verifying”和“permission denied”等典型错误,文章揭示了其根本原因在于SPA动态URL签名和jsApiList兼容性声明,并给出了具体的解决方案与终极排查清单,帮助开发者彻底解决微信分享权限验证难题。

weixin_28432777的博客 489

记录下公众号中禁止网页缩放的解决

这段时间第一次接触微信公众号开发 其实我是一个后端开发,因为公司前段后不分,所以慢慢的我变成了我们部分的‘前端开发工程师’,哎,不知道是好还是坏。 废话不多说,这段时间我发现做的一个基于vue的微信公众号,使用了很多ui框架,有nutui,是一个京东开发的新的UI框架,也有mintui框架,这二个都是很不错的开发公众号等其他移动端的框架。我遇到的问题就是使用一个文本域组件, 在苹果手机聚焦的时候会将拼命放大一点,但是发现方法之后没有自动的缩回,这就导致了在继续浏览其他页面的时候会出现滚动条。。。。用户体验极

mataodehtml的博客 1190

微信 JSSDK 调用出现无效签名、updateAppMessageShareData 被拒等问题的解决方案

前端开发中,使用微信 JSSDK 调用时,可能会遇到一些常见问题,例如无效签名(Invalid Signature)错误以及 updateAppMessageShareData 被拒等问题。通过以上解决方案,你可以处理微信 JSSDK 调用中的一些常见问题,包括无效签名错误和 updateAppMessageShareData 被拒问题。当调用微信 JSSDK 时出现无效签名错误时,通常是由于签名计算不正确导致的。一种常见的原因是该方法必须在用户触发事件(例如点击按钮)后调用,而不能在页面加载时立即调用。

api_git355的博客 2425

【uniapp分享微信小程序卡片报错 share:fail [Share微信分享:-3]Unable to send, https://ask.dcloud.net.cn/article/287】

uniapp分享小程序卡片,分享报错

前端-CV全粘工程师 7280

.net微网页分享到微信朋友圈插件代码(亲测可用)

.net微网页分享到微信朋友圈插件代码(亲测可用)

gesp c++ 五级知识点

gesp c++ 五级知识点

MMD.然大大 2009

通过咸虾米项目的开发经历,了解Uniapp项目整体开发过程(微信小程序名称:月色东升壁纸)

本文记录了作者从Java后端开发者转型全栈开发的完整历程。一年前因前端知识欠缺而放弃的小程序项目,通过系统学习HTML/CSS/JavaScript、Vue框架后,选用Uniapp实现多端适配开发。文章详细分享了学习路径(B站咸虾米教程)、设计工具(即时设计)的使用技巧、微信小程序注册流程,以及如何基于若依框架自建SpringBoot后端服务。作者不仅重写了所有接口,还完成了数据库设计、前后端联调,并实践了小程序上线全流程(包括ICP备案)。整个过程涵盖了原型设计、开发环境配置、接口对接、项目部署等全栈开发

qq_42449963的博客 460

转录组分析中的Fastp和FastQC:如何快速检测数据质量并优化流程

本文深入探讨了转录组分析中数据质量控制的核心流程,重点介绍了Fastp和FastQC两款工具的组合应用。FastQC负责对原始测序数据进行全面质量评估,生成可视化报告;Fastp则能一站式完成接头切除、低质量序列过滤、长度筛选等关键质控步骤。文章提供了详细的参数解读、实战脚本和自动化流程构建指南,帮助研究人员快速检测数据质量并优化预处理流程,为下游的差异表达等分析奠定可靠基础。

weixin_28452161的博客 181

微信分享报错errMsg: “updateAppMessageShareData:fail, the permission value is offline verifying“

微信分享报错errMsg: "updateAppMessageShareData:fail, the permission value is offline verifying"1.可能是手机微信版本不支持最新的分享方法,可以尝试使用旧版本2.使用的方法应该先声明一下,确定你使用的方法声明了。3.如果上面的两种方法都做了,或者之前运行没问题,也没改代码,就报错了,可能就是你的微信公众号认证到期了,记得去申请一下。 之前写的微信分享的功能,今天突然发现分享配置不对,排查下,发现报此错误;总结一下,希望可以给大

qq_34164814的博客 2万+

PVE 9.0 保姆级安装及优化教程(换源、网络配置、远程唤醒等)【基础篇】

最近,Proxmox VE 推出了基于 Debian 13 的 9.0 版本。正巧我手头有一台闲置的老电脑,与其闲置,不如装上 PVE,让它化身 All in One,继续发挥它的余热。G4560 算是一颗 NAS 神 U,十几元的售价就能有双核四线程,比起什么 J1900 不知道强到哪里去了,尽管定位上是奔腾处理器,但性能甚至能和同代的酷睿 i3-7100 掰掰手腕,并且它还自带 HD 610 的核显,对于解码的支持也还不错。

zc_mk的博客 7511

死区补偿---学习笔记

最近调试中发现,死区补偿对电流谐波和电流带宽影响挺大,于是对死区补偿产生浓厚兴趣,找来几篇文章粗读并做一下笔记。 传统做法 无非就是根据电流方向补偿,假如svpwm计算出的A相理论导通实践为T1,死区时间是Td,则实际导通时间T = T1-Td(when ia >0 ),于是在svpwm计算出的导通时间T1的基础上加上Td。这样经过PWM模块后,实际的导通时间即为T1. 但存在两个难点(个人总结): 1,受电流检测精度影响,尤其是在过零点检测困难。 2,真实的二极管导通需要一定电压,并非..

圆桌骑士的博客 2万+

h5分享微信好友朋友圈

微信分享朋友分享朋友圈 1.准备工作 1.1.获取微信公众号的appid 和 密钥 1.2公众号设置中添加js安全域名,需要将文件放在默认的80端口下。可做映射,可更改tomcat配置 1.2.1端口映射 一 .添加映射将80端口映射到8080 iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080 二. 删除映射(不需要时删除) 查看映射编号 iptables -t nat -L -nv --line-num

m0_46151944的博客 990

如何理解Fourier Neural Operator (FNO)

2022年Nvidia发表在arXiv上的的FourcastNet作为几乎是最早的一篇气象大模型的工作(之前Google Research的MetNet主要还是对于降水的预报)。除了Transformer的backbone之外,使用到了2021年发表在ICLR上的Fourier Neural Operator。为了更好的理解模型的理论基础,可以详细学习一下以及他的前期工作GNOFNO作者对这两篇文章的解析blog。

momo的博客 1万+

2024年前端最新前端必备技能~H5网页无法转发给朋友和分享朋友圈,解决方法汇总,2024年最新前端面试录音在线听

函数式编程其实是一种编程思想,它追求更细的粒度,将应用拆分成一组组极小的单元函数,组合调用操作数据流;它提倡着 纯函数 / 函数复合 / 数据不可变, 谨慎对待函数内的 状态共享 / 依赖外部 / 副作用;

2401_84616399的博客 936

即插即用系列(代码实践) | WACV 2024 CSAM:面向各向异性医学图像分割的 2.5D 跨切片注意力模块

文章摘要: 论文《CSAM: A 2.5D Cross-Slice Attention Module for Anisotropic Volumetric Medical Image Segmentation》提出了一种解决医学图像各向异性问题的创新模块CSAM。针对MRI/CT数据中切片间分辨率差异大的挑战,该模块通过2.5D跨切片注意力机制,结合2D卷积的轻量性和3D上下文感知能力。核心包括语义注意力(通道级)、位置注意力(空间级)和跨切片注意力(支持不确定性建模),能在几乎不增加参数量的情况下有效捕捉

分享顶会顶刊论文即插即用模块 104

App爬虫实战篇-以华为真机手机爬取集换社的app为例

在开始学习这篇文章之前,建议你先按照之前2篇文章(和),配置必要的环境,才可以继续完成本章节内容。

youbingchen的博客 780

微信支付趟过的坑

这段时间在做微信支付开发,在公司的公众号审批下来后,我这边的测试用例也已经开发完毕,于是拿着具体的数据来调试了,大段大段的代码就不贴了,demo里有,这里就说说调试过程中遇到的坑。         第一坑:redirect_url参数错误。因为我选择的的“JS API”支付,这种支付需要网页授权,先获取code,再拿code去获取openid和prepay_id。这个网页授权需要登录微信

molaifeng的专栏 9万+

大数据分析利器:Tableau实战教程从入门到精通

你有3家分店,每月收集1000条销售数据(日期、分店、口味、销售额、订单数);想用Excel分析“哪家分店最赚钱”,但要做透视表→改格式→画柱状图,耗时30分钟,还经常因为公式错误返工;想看看“草莓味奶茶的月度销量趋势”,得手动筛选数据、调整折线图轴范围,稍不注意就漏看关键节点;想把分析结果分享给合伙人,Excel表格太抽象,对方盯着数字问“你到底想告诉我什么?

AI架构师小马 1492

微信开发笔记-调用自定义分享接口

引言:   工作中开发微信网站,简称微网站。由于微网站的分享内容是系统自动选取的当前网址,客户需要改变分享的内容,即点击屏幕右上角的分享按钮,选择发送给朋友和发送到朋友圈,其中的内容和图片需要自定义。于是查找文档微信JS-SDK说明文档一文和网站众多高手的经验,大体知道了调用的步骤,但是具体如何调用才能成功却是不了解的。经过一番试验,终于成功调用发送朋友和发送到朋友圈两个接口,此处记录...

aq8008的博客 321

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

微信支付常见问题

1getBrandWCPayRequest:fail_nopermission to execute undefined 出现此问题的原因是:微信支付的开发配置中的测试授权目录或授权目录没有设置正确 2缺少必填参数openid! Appsecret 填写不对。可以检查或者重置Appsecret,编辑该公众号重填appsecret 3点击支...

weixin_33979745的博客 570

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

上一篇: c# Winform 打开浏览器并附带参数的问题
下一篇: Uniapp 获取首页的参数
Little_Code
博客等级 码龄10年 62粉丝 77原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值