WeChat secondary sharing

Q: When using WeChat for secondary sharing, the title is truncated, the description becomes a link, and there is no picture.

solution

Documentation

  1. WeChat JS-SDK documentation

  2. JS-SDK usage steps

    2.1 Bind domain name

    Log in to the WeChat public platform and enter "Official Account Settings"-->>"Function Settings"-->>"JS Interface Security Domain Name", and fill in according to the prompts.

    front end

    2.2 Introducing js files

    在需要调用JS接口的页面引入如下JS文件,http://res.wx.qq.com/open/js/jweixin-1.2.0.js

    2.3 Inject 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
    });

    2.4 Handle successful verification through the ready interface

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

    2.5 Handling failed verification through the error interface

    wx.error(function(res){
    
        // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
    
    });

    share interface

    Get the "Share to Moments" button click status and customize the sharing content interface

    wx.onMenuShareTimeline({
        title: '', // 分享标题
        link: '', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: '', // 分享图标
        success: function () {
        // 用户确认分享后执行的回调函数
    },

    Get the "Share to friends" button click status and customize the sharing content interface

    wx.onMenuShareAppMessage({
        title: '', // 分享标题
        desc: '', // 分享描述
        link: '', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: '', // 分享图标
        type: '', // 分享类型,music、video或link,不填默认为link
        dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
        success: function () {
            // 用户确认分享后执行的回调函数
        },
    });

    rear end

    1. Obtain the access_token interface invocation credentials. get access_token

      Developers need to cache access_token globally

    2. Use the first step to obtain access_token to obtain (get) jsapi_ticket https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
      developers need to cache jsapi_ticket globally

      response json example:

      {
      "errcode":0,
      "errmsg":"ok",
      "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
      "expires_in":7200
      }
    3. get signature

      The signature generation rules are as follows: the fields involved in the signature include noncestr (random string), valid jsapi_ticket, timestamp (timestamp), url (the URL of the current web page, excluding # and its following parts). After sorting all the parameters to be signed according to the ASCII code of the field name from small to large (lexicographical order), use the URL key-value pair format (ie key1=value1&key2=value2…) to concatenate them into a string string1. Note here that all parameter names are lowercase characters. Encrypt string1 with sha1, and use original values ​​for field names and field values ​​without URL escaping.

      Step 1. After sorting all the parameters to be signed according to the ASCII code of the field name from small to large (lexicographical order), use the URL key-value pair format (ie key1=value1&key2=value2...) to spliced ​​into a string

      Step 2. Perform sha1 signature on string1 to get signature:

    Precautions:

    1. The noncestr and timestamp used for signature must be the same as the nonceStr and timestamp in wx.config.

    2. The url used for signature must be the full URL of the page calling the JS interface.

    3. For security reasons, developers must implement the signature logic on the server side.

Common errors and solutions

invalid url domain

The domain name of the current page is not bound to the appid used. Please make sure to fill in the bound domain name correctly. Only two ports are supported: 80 (http) and 443 (https), so there is no need to fill in the port number (one appid can be bound to three valid domain name.).

invalid signature (recommended to verify in order)

1. Confirm that the signature algorithm is correct. You can use the http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign page tool for verification.

2. Confirm that the nonceStr in config (the standard uppercase S in camel case in js) and the timestamp are consistent with the corresponding noncestr and timestamp in the signature.

3. Confirm that the url is the complete url of the page (please confirm it on the current page alert(location.href.split('#')[0])), including the 'http(s)://' part, and the '? ' followed by the GET parameter part, but not the part after the '#' hash.

4. Confirm that the appid in config is the same as the appid used to get jsapi_ticket.

5. Make sure to cache access_token and jsapi_ticket.

6. Make sure that the url you get for signing is obtained dynamically. For dynamic pages, please refer to the implementation of php in the example code. If it is a static page of html, the url is passed to the background signature through ajax on the front end, the front end needs to use js to get the link of the current page to remove the '#' hash part (can be obtained by location.href.split('#')[0], and EncodeURIComponent is required), because once the page is shared, the WeChat client will add other parameters at the end of your link. If the current link is not dynamically obtained, the shared page signature will fail.

code example

Backend (python)


import time
import random
import string
import hashlib


nonce_str = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(15))

timestamp = int(time.time())

jsapi_ticket = ""  # 用access_token获取
url = ""  # 当前请求页面的url,url是动态获取的

ret = {
    "nonceStr": nonce_str,
    "jsapi_ticket": jsapi_ticket,
    "timestamp": timestamp,
    "url": url
}

string_ = '&'.join(['%s=%s' % (key.lower(), ret[key]) for key in sorted(ret)])

ret['signature'] = hashlib.sha1(string).hexdigest()

return ret

front end

<!DOCTYPE html>
<html>
<head>
    <!--这个js必须引入-->
    <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
</head>
<body>
<script type="text/javascript">
    wx.config({
        //debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
        appId: '', // 必填,公众号的唯一标识
        timestamp: "", // 必填,生成签名的时间戳
        nonceStr: '', // 必填,生成签名的随机串
        signature: '',// 必填,签名,
        jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone'] // 必填,需要使用的JS接口列表
    });
    wx.ready(function(){
        wx.onMenuShareTimeline({//分享到朋友圈
            title: '', // 分享标题
            link: '', // 分享链接
            imgUrl: '' // 分享图标
        });
        wx.onMenuShareAppMessage({//分享给朋友
            title: '', // 分享标题
            desc: '', // 分享描述
            link: '', // 分享链接
            imgUrl: '', // 分享图标
            type: '', // 分享类型,music、video或link,不填默认为link
            dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
            success: function () {
                // 用户确认分享后执行的回调函数
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
        // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
    });

</script>
<div class="wrap">
    
</div>
</body>
</html>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324933349&siteId=291194637