Home WeChat Applet WeChat Development WeChat development notes-calling custom sharing interface

WeChat development notes-calling custom sharing interface

Feb 13, 2017 am 11:21 AM
WeChat development

Introduction:

Develop a WeChat website at work, referred to as a microsite. Since the shared content of the microsite is the current URL automatically selected by the system, the customer needs to change the shared content, that is, click the share button in the upper right corner of the screen and choose Send to Friends or Send to Moments. The content and pictures need to be customized. So I looked up the article WeChat JS-SDK Description Document and the experience of many experts on the website. I generally knew the steps of calling, but I didn’t understand how to make the call successful. After some experiments, the two interfaces of Send to Friends and Send to Moments were finally successfully called. The specific process of the call is recorded here.

Step 1: Reference the js file.

Introduce the following JS file into the page that needs to call the JS interface (https is supported): http://res.wx.qq.com/open/js/jweixin-1.0.0.js

Step 2: Inject the permission verification configuration through the config interface


wx.config({
    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    appId: '', // 必填,公众号的唯一标识
    timestamp: , // 必填,生成签名的时间戳
    nonceStr: '', // 必填,生成签名的随机串
    signature: '',// 必填,签名,见附录1
    jsApiList: [] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
Copy after login


Many netizens on the Internet also wrote this , but there is little talk about the specific configuration. Next, we will introduce how to call it in this article.

Debug and appId, needless to say, very simple.

timespan generates the timestamp of the signature:


/// <summary>
        /// 生成时间戳
        /// 从 1970 年 1 月 1 日 00:00:00 至今的秒数,即当前的时间,且最终需要转换为字符串形式
        /// </summary>
        /// <returns></returns>
        public string getTimestamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }
Copy after login


nonceStr generates a random string of the signature :


/// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <returns></returns>
        public string getNoncestr()
        {
            Random random = new Random();
            return MD5Util.GetMD5(random.Next(1000).ToString(), "GBK");
        }
Copy after login


/// <summary>
    /// MD5Util 的摘要说明。    /// </summary>
    public class MD5Util
    {        public MD5Util()
        {            //
            // TODO: 在此处添加构造函数逻辑            
            //        
            }        
            /** 获取大写的MD5签名结果 */
        public static string GetMD5(string encypStr, string charset)
        {            string retStr;
            MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();            
            //创建md5对象
            byte[] inputBye;            byte[] outputBye;            
            //使用GB2312编码方式把字符串转化为字节数组.
            try
            {
                inputBye = Encoding.GetEncoding(charset).GetBytes(encypStr);
            }            catch (Exception ex)
            {
                inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr);
            }
            outputBye = m5.ComputeHash(inputBye);

            retStr = System.BitConverter.ToString(outputBye);
            retStr = retStr.Replace("-", "").ToUpper();            
            return retStr;
        }
    }
Copy after login


View Code

/// <summary>
    /// MD5Util 的摘要说明。
    /// </summary>
    public class MD5Util
    {
        public MD5Util()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

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

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

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

            retStr = System.BitConverter.ToString(outputBye);
            retStr = retStr.Replace("-", "").ToUpper();
            return retStr;
        }
    }
Copy after login


Singature signature generation is more troublesome.

First generate and obtain access_token (validity period is 7200 seconds, developers must cache access_token globally in their own services)


public string Getaccesstoken()
        {
            string appid = System.Configuration.ConfigurationManager.AppSettings["WXZjAppID"].ToString();
            string secret = System.Configuration.ConfigurationManager.AppSettings["WXZjAppSecret"].ToString();
            string urljson = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            string strjson = "";
            UTF8Encoding encoding = new UTF8Encoding();
            HttpWebRequest myRequest =
            (HttpWebRequest)WebRequest.Create(urljson);
            myRequest.Method = "GET";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            HttpWebResponse response;
            Stream responseStream;
            StreamReader reader;
            string srcString;
            response = myRequest.GetResponse() as HttpWebResponse;
            responseStream = response.GetResponseStream();
            reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
            srcString = reader.ReadToEnd();
            reader.Close();
            if (srcString.Contains("access_token"))
            {
                //CommonJsonModel model = new CommonJsonModel(srcString);
                HP.CPS.BLL.WeiXin.CommonJsonModel model = new BLL.WeiXin.CommonJsonModel(srcString);
                strjson = model.GetValue("access_token");
                Session["access_tokenzj"] = strjson;
            }
            return strjson;
        }
Copy after login



public class CommonJsonModelAnalyzer
    {        protected string _GetKey(string rawjson)
        {            if (string.IsNullOrEmpty(rawjson))                return rawjson;
            rawjson = rawjson.Trim();            string[] jsons = rawjson.Split(new char[] { &#39;:&#39; });            if (jsons.Length < 2)                return rawjson;            return jsons[0].Replace("\"", "").Trim();
        }        protected string _GetValue(string rawjson)
        {            if (string.IsNullOrEmpty(rawjson))                return rawjson;
            rawjson = rawjson.Trim();            string[] jsons = rawjson.Split(new char[] { &#39;:&#39; }, StringSplitOptions.RemoveEmptyEntries);            if (jsons.Length < 2)                return rawjson;
            StringBuilder builder = new StringBuilder();            for (int i = 1; i < jsons.Length; i++)
            {
                builder.Append(jsons[i]);
                builder.Append(":");
            }            if (builder.Length > 0)
                builder.Remove(builder.Length - 1, 1);            string value = builder.ToString();            if (value.StartsWith("\""))
                value = value.Substring(1);            if (value.EndsWith("\""))
                value = value.Substring(0, value.Length - 1);            return value;
        }        protected List<string> _GetCollection(string rawjson)
        {            //[{},{}]
            List<string> list = new List<string>();            if (string.IsNullOrEmpty(rawjson))                return list;
            rawjson = rawjson.Trim();
            StringBuilder builder = new StringBuilder();            int nestlevel = -1;            int mnestlevel = -1;            for (int i = 0; i < rawjson.Length; i++)
            {                if (i == 0)                    continue;                else if (i == rawjson.Length - 1)                    continue;                char jsonchar = rawjson[i];                if (jsonchar == &#39;{&#39;)
                {
                    nestlevel++;
                }                if (jsonchar == &#39;}&#39;)
                {
                    nestlevel--;
                }                if (jsonchar == &#39;[&#39;)
                {
                    mnestlevel++;
                }                if (jsonchar == &#39;]&#39;)
                {
                    mnestlevel--;
                }                if (jsonchar == &#39;,&#39; && nestlevel == -1 && mnestlevel == -1)
                {
                    list.Add(builder.ToString());
                    builder = new StringBuilder();
                }                else
                {
                    builder.Append(jsonchar);
                }
            }            if (builder.Length > 0)
                list.Add(builder.ToString());            return list;
        }
    }    public class CommonJsonModel : CommonJsonModelAnalyzer
    {        private string rawjson;        private bool isValue = false;        private bool isModel = false;        private bool isCollection = false;        public CommonJsonModel(string rawjson)
        {            this.rawjson = rawjson;            if (string.IsNullOrEmpty(rawjson))                throw new Exception("missing rawjson");
            rawjson = rawjson.Trim();            if (rawjson.StartsWith("{"))
            {
                isModel = true;
            }            else if (rawjson.StartsWith("["))
            {
                isCollection = true;
            }            else
            {
                isValue = true;
            }
        }        public string Rawjson
        {            get { return rawjson; }
        }        public bool IsValue()
        {            return isValue;
        }        public bool IsValue(string key)
        {            if (!isModel)                return false;            if (string.IsNullOrEmpty(key))                return false;            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);                if (!model.IsValue())                    continue;                if (model.Key == key)
                {
                    CommonJsonModel submodel = new CommonJsonModel(model.Value);                    return submodel.IsValue();
                }
            }            return false;
        }        public bool IsModel()
        {            return isModel;
        }        public bool IsModel(string key)
        {            if (!isModel)                return false;            if (string.IsNullOrEmpty(key))                return false;            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);                if (!model.IsValue())                    continue;                if (model.Key == key)
                {
                    CommonJsonModel submodel = new CommonJsonModel(model.Value);                    return submodel.IsModel();
                }
            }            return false;
        }        public bool IsCollection()
        {            return isCollection;
        }        public bool IsCollection(string key)
        {            if (!isModel)                return false;            if (string.IsNullOrEmpty(key))                return false;            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);                if (!model.IsValue())                    continue;                if (model.Key == key)
                {
                    CommonJsonModel submodel = new CommonJsonModel(model.Value);                    return submodel.IsCollection();
                }
            }            return false;
        }        /// <summary>
        /// 当模型是对象,返回拥有的key        /// </summary>
        /// <returns></returns>
        public List<string> GetKeys()
        {            if (!isModel)                return null;
            List<string> list = new List<string>();            foreach (string subjson in base._GetCollection(this.rawjson))
            {                string key = new CommonJsonModel(subjson).Key;                if (!string.IsNullOrEmpty(key))
                    list.Add(key);
            }            return list;
        }        /// <summary>
        /// 当模型是对象,key对应是值,则返回key对应的值        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetValue(string key)
        {            if (!isModel)                return null;            if (string.IsNullOrEmpty(key))                return null;            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);                if (!model.IsValue())                    continue;                if (model.Key == key)                    return model.Value;
            }            return null;
        }        /// <summary>
        /// 模型是对象,key对应是对象,返回key对应的对象        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public CommonJsonModel GetModel(string key)
        {            if (!isModel)                return null;            if (string.IsNullOrEmpty(key))                return null;            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);                if (!model.IsValue())                    continue;                if (model.Key == key)
                {
                    CommonJsonModel submodel = new CommonJsonModel(model.Value);                    if (!submodel.IsModel())                        return null;                    else
                        return submodel;
                }
            }            return null;
        }        /// <summary>
        /// 模型是对象,key对应是集合,返回集合        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public CommonJsonModel GetCollection(string key)
        {            if (!isModel)                return null;            if (string.IsNullOrEmpty(key))                return null;            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);                if (!model.IsValue())                    continue;                if (model.Key == key)
                {
                    CommonJsonModel submodel = new CommonJsonModel(model.Value);                    if (!submodel.IsCollection())                        return null;                    else
                        return submodel;
                }
            }            return null;
        }        /// <summary>
        /// 模型是集合,返回自身        /// </summary>
        /// <returns></returns>
        public List<CommonJsonModel> GetCollection()
        {
            List<CommonJsonModel> list = new List<CommonJsonModel>();            if (IsValue())                return list;            foreach (string subjson in base._GetCollection(rawjson))
            {
                list.Add(new CommonJsonModel(subjson));
            }            return list;
        }        /// <summary>
        /// 当模型是值对象,返回key        /// </summary>
        private string Key
        {            get
            {                if (IsValue())                    return base._GetKey(rawjson);                return null;
            }
        }        /// <summary>
        /// 当模型是值对象,返回value        /// </summary>
        private string Value
        {            get
            {                if (!IsValue())                    return null;                return base._GetValue(rawjson);
            }
        }
    }
Copy after login


##View Code

public class CommonJsonModelAnalyzer
    {
        protected string _GetKey(string rawjson)
        {
            if (string.IsNullOrEmpty(rawjson))
                return rawjson;
            rawjson = rawjson.Trim();
            string[] jsons = rawjson.Split(new char[] { &#39;:&#39; });
            if (jsons.Length < 2)
                return rawjson;
            return jsons[0].Replace("\"", "").Trim();
        }
        protected string _GetValue(string rawjson)
        {
            if (string.IsNullOrEmpty(rawjson))
                return rawjson;
            rawjson = rawjson.Trim();
            string[] jsons = rawjson.Split(new char[] { &#39;:&#39; }, StringSplitOptions.RemoveEmptyEntries);
            if (jsons.Length < 2)
                return rawjson;
            StringBuilder builder = new StringBuilder();
            for (int i = 1; i < jsons.Length; i++)
            {
                builder.Append(jsons[i]);
                builder.Append(":");
            }
            if (builder.Length > 0)
                builder.Remove(builder.Length - 1, 1);
            string value = builder.ToString();
            if (value.StartsWith("\""))
                value = value.Substring(1);
            if (value.EndsWith("\""))
                value = value.Substring(0, value.Length - 1);
            return value;
        }
        protected List<string> _GetCollection(string rawjson)
        {
            //[{},{}]
            List<string> list = new List<string>();
            if (string.IsNullOrEmpty(rawjson))
                return list;
            rawjson = rawjson.Trim();
            StringBuilder builder = new StringBuilder();
            int nestlevel = -1;
            int mnestlevel = -1;
            for (int i = 0; i < rawjson.Length; i++)
            {
                if (i == 0)
                    continue;
                else if (i == rawjson.Length - 1)
                    continue;
                char jsonchar = rawjson[i];
                if (jsonchar == &#39;{&#39;)
                {
                    nestlevel++;
                }
                if (jsonchar == &#39;}&#39;)
                {
                    nestlevel--;
                }
                if (jsonchar == &#39;[&#39;)
                {
                    mnestlevel++;
                }
                if (jsonchar == &#39;]&#39;)
                {
                    mnestlevel--;
                }
                if (jsonchar == &#39;,&#39; && nestlevel == -1 && mnestlevel == -1)
                {
                    list.Add(builder.ToString());
                    builder = new StringBuilder();
                }
                else
                {
                    builder.Append(jsonchar);
                }
            }
            if (builder.Length > 0)
                list.Add(builder.ToString());
            return list;
        }
    }

    public class CommonJsonModel : CommonJsonModelAnalyzer
    {
        private string rawjson;
        private bool isValue = false;
        private bool isModel = false;
        private bool isCollection = false;
        public CommonJsonModel(string rawjson)
        {
            this.rawjson = rawjson;
            if (string.IsNullOrEmpty(rawjson))
                throw new Exception("missing rawjson");
            rawjson = rawjson.Trim();
            if (rawjson.StartsWith("{"))
            {
                isModel = true;
            }
            else if (rawjson.StartsWith("["))
            {
                isCollection = true;
            }
            else
            {
                isValue = true;
            }
        }
        public string Rawjson
        {
            get { return rawjson; }
        }
        public bool IsValue()
        {
            return isValue;
        }
        public bool IsValue(string key)
        {
            if (!isModel)
                return false;
            if (string.IsNullOrEmpty(key))
                return false;
            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);
                if (!model.IsValue())
                    continue;
                if (model.Key == key)
                {
                    CommonJsonModel submodel = new CommonJsonModel(model.Value);
                    return submodel.IsValue();
                }
            }
            return false;
        }
        public bool IsModel()
        {
            return isModel;
        }
        public bool IsModel(string key)
        {
            if (!isModel)
                return false;
            if (string.IsNullOrEmpty(key))
                return false;
            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);
                if (!model.IsValue())
                    continue;
                if (model.Key == key)
                {
                    CommonJsonModel submodel = new CommonJsonModel(model.Value);
                    return submodel.IsModel();
                }
            }
            return false;
        }
        public bool IsCollection()
        {
            return isCollection;
        }
        public bool IsCollection(string key)
        {
            if (!isModel)
                return false;
            if (string.IsNullOrEmpty(key))
                return false;
            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);
                if (!model.IsValue())
                    continue;
                if (model.Key == key)
                {
                    CommonJsonModel submodel = new CommonJsonModel(model.Value);
                    return submodel.IsCollection();
                }
            }
            return false;
        }

        /// <summary>
        /// 当模型是对象,返回拥有的key
        /// </summary>
        /// <returns></returns>
        public List<string> GetKeys()
        {
            if (!isModel)
                return null;
            List<string> list = new List<string>();
            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                string key = new CommonJsonModel(subjson).Key;
                if (!string.IsNullOrEmpty(key))
                    list.Add(key);
            }
            return list;
        }
        /// <summary>
        /// 当模型是对象,key对应是值,则返回key对应的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetValue(string key)
        {
            if (!isModel)
                return null;
            if (string.IsNullOrEmpty(key))
                return null;
            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);
                if (!model.IsValue())
                    continue;
                if (model.Key == key)
                    return model.Value;
            }
            return null;
        }
        /// <summary>
        /// 模型是对象,key对应是对象,返回key对应的对象
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public CommonJsonModel GetModel(string key)
        {
            if (!isModel)
                return null;
            if (string.IsNullOrEmpty(key))
                return null;
            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);
                if (!model.IsValue())
                    continue;
                if (model.Key == key)
                {
                    CommonJsonModel submodel = new CommonJsonModel(model.Value);
                    if (!submodel.IsModel())
                        return null;
                    else
                        return submodel;
                }
            }
            return null;
        }
        /// <summary>
        /// 模型是对象,key对应是集合,返回集合
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public CommonJsonModel GetCollection(string key)
        {
            if (!isModel)
                return null;
            if (string.IsNullOrEmpty(key))
                return null;
            foreach (string subjson in base._GetCollection(this.rawjson))
            {
                CommonJsonModel model = new CommonJsonModel(subjson);
                if (!model.IsValue())
                    continue;
                if (model.Key == key)
                {
                    CommonJsonModel submodel = new CommonJsonModel(model.Value);
                    if (!submodel.IsCollection())
                        return null;
                    else
                        return submodel;
                }
            }
            return null;
        }
        /// <summary>
        /// 模型是集合,返回自身
        /// </summary>
        /// <returns></returns>
        public List<CommonJsonModel> GetCollection()
        {
            List<CommonJsonModel> list = new List<CommonJsonModel>();
            if (IsValue())
                return list;
            foreach (string subjson in base._GetCollection(rawjson))
            {
                list.Add(new CommonJsonModel(subjson));
            }
            return list;
        }


        /// <summary>
        /// 当模型是值对象,返回key
        /// </summary>
        private string Key
        {
            get
            {
                if (IsValue())
                    return base._GetKey(rawjson);
                return null;
            }
        }
        /// <summary>
        /// 当模型是值对象,返回value
        /// </summary>
        private string Value
        {
            get
            {
                if (!IsValue())
                    return null;
                return base._GetValue(rawjson);
            }
        }
    }
Copy after login


Then get jsapi_ticket:

Use the access_token obtained in the first step to request jsapi_ticket using http GET method (

The validity period is 7200 seconds. Developers must cache jsapi_ticket globally in their own services)


public string Getjsapi_ticket()
        {
            string accesstoken = (string)Session["access_tokenzj"];
            string urljson = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accesstoken + "&type=jsapi";
            string strjson = "";
            UTF8Encoding encoding = new UTF8Encoding();
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(urljson);
            myRequest.Method = "GET";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            HttpWebResponse response = myRequest.GetResponse() as HttpWebResponse;
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
            string srcString = reader.ReadToEnd();
            reader.Close();
            if (srcString.Contains("ticket"))
            {
                HP.CPS.BLL.WeiXin.CommonJsonModel model = new BLL.WeiXin.CommonJsonModel(srcString);
                strjson = model.GetValue("ticket");
                Session["ticketzj"] = strjson;
            }

            return strjson;
        }
Copy after login


Finally generate signature:


public string Getsignature(string nonceStr, string timespanstr)
        {
            if (Session["access_tokenzj"] == null)
            {
                Getaccesstoken();
            }
            if (Session["ticketzj"] == null)
            {
                Getjsapi_ticket();
            }

            string url = Request.Url.ToString();

            string str = "jsapi_ticket=" + (string)Session["ticketzj"] + "&noncestr=" + nonceStr +
                "&timestamp=" + timespanstr + "&url=" + url;// +"&wxref=mp.weixin.qq.com";
            string singature = SHA1Util.getSha1(str);
            string ss = singature;
            return ss;
        }
Copy after login
class SHA1Util
    {
        public static String getSha1(String str)
        {
            //建立SHA1对象
            SHA1 sha = new SHA1CryptoServiceProvider();
            //将mystr转换成byte[] 
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] dataToHash = enc.GetBytes(str);
            //Hash运算
            byte[] dataHashed = sha.ComputeHash(dataToHash);
            //将运算结果转换成string
            string hash = BitConverter.ToString(dataHashed).Replace("-", "");
            return hash;
        }
    }
Copy after login
class SHA1Util
    {        public static String getSha1(String str)
        {            //建立SHA1对象
            SHA1 sha = new SHA1CryptoServiceProvider();            //将mystr转换成byte[] 
            ASCIIEncoding enc = new ASCIIEncoding();            byte[] dataToHash = enc.GetBytes(str);            //Hash运算
            byte[] dataHashed = sha.ComputeHash(dataToHash);            //将运算结果转换成string
            string hash = BitConverter.ToString(dataHashed).Replace("-", "");            return hash;
        }
    }
Copy after login


View Code

Call example in this article:


<script type="text/javascript">
        wx.config({
            debug: false,
            appId: &#39;<%=corpid %>&#39;,
            timestamp: <%=timestamp%>,
            nonceStr: &#39;<%=nonceStr%>&#39;,
            signature: &#39;<%=signature %>&#39;,
            jsApiList: [&#39;onMenuShareTimeline&#39;, &#39;onMenuShareAppMessage&#39;]
        });
    </script>
Copy after login


##Step 3: Call the interface

After completion After the second step is called, step three becomes very easy.

wx.ready(function(){    // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。});
Copy after login

The calling example of this article is:

<script type="text/javascript" >
    wx.ready(function () {
        wx.onMenuShareAppMessage({
            title: &#39;<%=shareTitle %>&#39;,
            desc: &#39;<%=shareContent %>&#39;,
            link: &#39;<%=currentUrl %>&#39;,
            imgUrl: &#39;<%=shareImageUrl %>&#39;
        });

        wx.onMenuShareTimeline({
            title: &#39;<%=shareContent %>&#39;,
            link: &#39;<%=currentUrl %>&#39;,
            imgUrl: &#39;<%=shareImageUrl %>&#39;
        });
    })     
</script>
Copy after login
<script type="text/javascript" >
    wx.ready(function () {
        wx.onMenuShareAppMessage({
            title: &#39;<%=shareTitle %>&#39;,
            desc: &#39;<%=shareContent %>&#39;,
            link: &#39;<%=currentUrl %>&#39;,
            imgUrl: &#39;<%=shareImageUrl %>&#39;
        });

        wx.onMenuShareTimeline({
            title: &#39;<%=shareContent %>&#39;,
            link: &#39;<%=currentUrl %>&#39;,
            imgUrl: &#39;<%=shareImageUrl %>&#39;
        });
    })     
</script>
Copy after login

This article is basically summarized here.

Common problems:

1. Check whether the background is set: public account name in the upper right corner--function settings--JS interface security domain name

2. Check the code Is the appid consistent with the id of the public account backend?

3. The calling address of the picture is an absolute path (relative paths don’t seem to work).

For more WeChat development notes-calling custom sharing interface related articles, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
PHP WeChat development: How to implement message encryption and decryption PHP WeChat development: How to implement message encryption and decryption May 13, 2023 am 11:40 AM

PHP is an open source scripting language that is widely used in web development and server-side programming, especially in WeChat development. Today, more and more companies and developers are starting to use PHP for WeChat development because it has become a truly easy-to-learn and easy-to-use development language. In WeChat development, message encryption and decryption are a very important issue because they involve data security. For messages without encryption and decryption methods, hackers can easily obtain the data, posing a threat to users.

Using PHP to develop WeChat mass messaging tools Using PHP to develop WeChat mass messaging tools May 13, 2023 pm 05:00 PM

With the popularity of WeChat, more and more companies are beginning to use it as a marketing tool. The WeChat group messaging function is one of the important means for enterprises to conduct WeChat marketing. However, if you only rely on manual sending, it is an extremely time-consuming and laborious task for marketers. Therefore, it is particularly important to develop a WeChat mass messaging tool. This article will introduce how to use PHP to develop WeChat mass messaging tools. 1. Preparation work To develop WeChat mass messaging tools, we need to master the following technical points: Basic knowledge of PHP WeChat public platform development Development tools: Sub

PHP WeChat development: How to implement user tag management PHP WeChat development: How to implement user tag management May 13, 2023 pm 04:31 PM

In the development of WeChat public accounts, user tag management is a very important function, which allows developers to better understand and manage their users. This article will introduce how to use PHP to implement the WeChat user tag management function. 1. Obtain the openid of the WeChat user. Before using the WeChat user tag management function, we first need to obtain the user's openid. In the development of WeChat public accounts, it is a common practice to obtain openid through user authorization. After the user authorization is completed, we can obtain the user through the following code

Steps to implement WeChat public account development using PHP Steps to implement WeChat public account development using PHP Jun 27, 2023 pm 12:26 PM

How to use PHP to develop WeChat public accounts WeChat public accounts have become an important channel for promotion and interaction for many companies, and PHP, as a commonly used Web language, can also be used to develop WeChat public accounts. This article will introduce the specific steps to use PHP to develop WeChat public accounts. Step 1: Obtain the developer account of the WeChat official account. Before starting the development of the WeChat official account, you need to apply for a developer account of the WeChat official account. For the specific registration process, please refer to the official website of WeChat public platform

PHP WeChat development: How to implement group message sending records PHP WeChat development: How to implement group message sending records May 13, 2023 pm 04:31 PM

As WeChat becomes an increasingly important communication tool in people's lives, its agile messaging function is quickly favored by a large number of enterprises and individuals. For enterprises, developing WeChat into a marketing platform has become a trend, and the importance of WeChat development has gradually become more prominent. Among them, the group sending function is even more widely used. So, as a PHP programmer, how to implement group message sending records? The following will give you a brief introduction. 1. Understand the development knowledge related to WeChat public accounts. Before understanding how to implement group message sending records, I

PHP WeChat development: How to implement voting function PHP WeChat development: How to implement voting function May 14, 2023 am 11:21 AM

In the development of WeChat public accounts, the voting function is often used. The voting function is a great way for users to quickly participate in interactions, and it is also an important tool for holding events and surveying opinions. This article will introduce you how to use PHP to implement WeChat voting function. Obtain the authorization of the WeChat official account. First, you need to obtain the authorization of the WeChat official account. On the WeChat public platform, you need to configure the API address of the WeChat public account, the official account, and the token corresponding to the public account. In the process of our development using PHP language, we need to use the PH officially provided by WeChat

PHP WeChat development: How to implement customer service chat window management PHP WeChat development: How to implement customer service chat window management May 13, 2023 pm 05:51 PM

WeChat is currently one of the social platforms with the largest user base in the world. With the popularity of mobile Internet, more and more companies are beginning to realize the importance of WeChat marketing. When conducting WeChat marketing, customer service is a crucial part. In order to better manage the customer service chat window, we can use PHP language for WeChat development. 1. Introduction to PHP WeChat development PHP is an open source server-side scripting language that is widely used in the field of Web development. Combined with the development interface provided by WeChat public platform, we can use PHP language to conduct WeChat

How to use PHP for WeChat development? How to use PHP for WeChat development? May 21, 2023 am 08:37 AM

With the development of the Internet and mobile smart devices, WeChat has become an indispensable part of the social and marketing fields. In this increasingly digital era, how to use PHP for WeChat development has become the focus of many developers. This article mainly introduces the relevant knowledge points on how to use PHP for WeChat development, as well as some of the tips and precautions. 1. Development environment preparation Before developing WeChat, you first need to prepare the corresponding development environment. Specifically, you need to install the PHP operating environment and the WeChat public platform

See all articles