WeChat public account to share with friends

To implement the function of sharing with friends in the WeChat official account, you can use onMenuShareAppMessagethe interface . This interface will be triggered when the Share to Friends menu item is clicked.

Here is sample code:

// 配置分享给好友信息
wx.onMenuShareAppMessage({
    
    
  title: '分享标题',
  desc: '分享描述',
  link: '分享链接',
  imgUrl: '分享图标',
  success: function () {
    
    
    // 分享成功回调
    console.log('分享给好友成功!');
  },
  cancel: function () {
    
    
    // 分享取消回调
    console.log('分享给好友取消!');
  }
});

in:

  • titleIndicates the title shared with friends.
  • descIndicates the description shared with friends.
  • linkIndicates a link to share with friends.
  • imgUrlAn icon representing sharing with friends.
  • successCallback function indicating the success of sharing to friends.
  • cancelIndicates the callback function to cancel sharing to friends.

It should be noted that to use onMenuShareAppMessagethe interface , the WeChat JS-SDK must be introduced first, and can be executed wx.configand obtained after the page is loaded wx.ready.

Here is sample code:

// 引入微信 JS-SDK
<script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>

// 配置微信 JS-SDK
wx.config({
    
    
  // 必填,公众号的唯一标识
  appId: 'YOUR_APP_ID',
  // 必填,生成签名的时间戳
  timestamp: TIMESTAMP,
  // 必填,生成签名的随机串
  nonceStr: 'YOUR_NONCESTR',
  // 必填,签名,见附录1
  signature: 'YOUR_SIGNATURE',
  // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
  jsApiList: ['onMenuShareAppMessage']
});

// 获取微信 JS-SDK
wx.ready(function () {
    
    
  // 配置分享给好友信息
  wx.onMenuShareAppMessage({
    
    
    title: '分享标题',
    desc: '分享描述',
    link: '分享链接',
    imgUrl: '分享图标',
    success: function () {
    
    
      // 分享成功回调
      console.log('分享给好友成功!');
    },
    cancel: function () {
    
    
      // 分享取消回调
      console.log('分享给好友取消!');
    }
  });
});

Among them, YOUR_APP_ID, TIMESTAMP, YOUR_NONCESTR, YOUR_SIGNATURErepresent the unique identifier of your Official Account, the timestamp of generating the signature, the random string of generating the signature, and the signature, respectively. You need to fill in these values ​​according to the actual situation.

If an error occurs when using wx.configto configure the WeChat JS-SDK config:fail,invalid signature, it is usually due to a problem with the generation of the signature.

Here are some possible causes and solutions for signature generation issues:

  1. Check if the parameters of the signature are correct

The generation of the signature requires some parameters, such as: noncestr, timestamp, url, ticket, etc. You need to make sure that the values ​​of these parameters are correct, complete and ready for use.

  1. Check that the signed URL is correct

Signed URLs cover web page URLs using WeChat JS-SDK, encodeURIComponentwhich encoded before signing.

You can check that the encoded URL is correct with the following code:

function getUrl() {
    
    
  var url = window.location.href.split('#')[0];
  return encodeURIComponent(url);
}
  1. Check if the signature algorithm is correct

The signature algorithm needs to be consistent with the place where the signature is used. You need to ensure that the signature algorithm used wx.configwhen consistent with the algorithm used when actually generating the signature.

  1. Check if the list of JSAPI interfaces is correct

When wx.configconfiguring WeChat JS-SDK, you need to pass in an array to specify the JSAPI list to be used, and you need to ensure that the array contains the JSAPI to be used.

For example:

wx.config({
    
    
  debug: true,
  appId: '',
  timestamp: ,
  nonceStr: '',
  signature: '',
  jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'onVoicePlayEnd', 'pauseVoice', 'stopVoice', 'uploadVoice', 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'translateVoice', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'closeWindow']
});
  1. Check if the server configuration is correct

If you use the server to generate signatures, you need to ensure that the signature generation interface has been configured correctly. Usually this interface needs to use the GET method, and the return value should be a JSON object, including parameters such as "nonceStr", "timestamp", and "signature".

The above are some causes and solutions that may cause problems in signature generation, and you can check and eliminate them according to the actual situation.

The following is a piece of PHP code for generating the wx.config configuration related to WeChat JS-SDK:

<?php
$noncestr = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 16);  // 随机字符串
$timestamp = time();  // 时间戳
$url = $_POST['url'];  // 当前网页的 URL,需使用 JS 获取

// 使用 access_token 获取 jsapi_ticket
$access_token = get_access_token();  // 先获取 access_token,详见:https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
$url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token='.$access_token;
$ticket_json = file_get_contents($url);
$ticket_data = json_decode($ticket_json, true);
$ticket = $ticket_data['ticket'];

// 对 string1 进行 sha1 加密,得到 signature 
$string1 = 'jsapi_ticket='.$ticket.'&noncestr='.$noncestr.'&timestamp='.$timestamp.'&url='.$url;
$signature = sha1($string1);

$config = [
    'appId'     => '<your_appid>',
    'timestamp' => $timestamp,
    'nonceStr'  => $noncestr,
    'signature' => $signature,
    'jsApiList' => ['chooseImage', 'previewImage', 'uploadImage', 'downloadImage']  // 需使用的 jsapi 列表
];

echo json_encode($config);
?>

This code will obtain jsapi_ticket by calling the WeChat interface, then generate relevant parameters and return to the front end. You need to <your_appid>replace with the AppID of your official account.

Note that since you need to use $_POST['url']this parameter to call the WeChat interface, you need to pass the URL of the current webpage on the front-end page. It is recommended to use JS to generate and deliver based on the page URL.

In addition, the code only lists a part of the commonly used JSAPI list, and you need to modify it according to your business needs.

Guess you like

Origin blog.csdn.net/qq_27487739/article/details/131138087