Home  >  Article  >  Backend Development  >  Detailed explanation of php WeChat browser sharing settings and callbacks_php example

Detailed explanation of php WeChat browser sharing settings and callbacks_php example

WBOY
WBOYOriginal
2016-08-17 13:02:35824browse

The function of sharing to friends/sharing to Moments in WeChat should be relatively common. Take sharing to Moments as an example. The shared content is displayed in Moments with a small picture + a simple introduction. The form is for friends to see, and the details are revealed after clicking. In this way, this small picture and this small introduction directly become the top priority of the click-through rate of the shared content. By default, this image will load as the first large image in the topic section of the content, while the introduction will only load a URL. This kind of display method is still quite unsatisfactory, so let’s take a look at how these contents are set up. Take PHP as an example:

First we need to have a public account and obtain the appid and appsecret.

Then, we can exchange the access_token from the WeChat platform through the appid and appsecret.

define("APPID", $appid);
define("APPSECRET", $appsecret);
 
// 获取access_token
$token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . APPID . "&secret=" . APPSECRET;
$res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
$result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
$access_token = $result['access_token'];

Through access_token, we can request a jsapi_ticket from the WeChat platform:

 // 获取jsapi_ticket
$ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=TOKEN";

$res = file_get_contents($ticket_url); //获取文件内容或获取网络请求的内容
$result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
$ticket = $result['ticket']; 

Okay, the preparations are ready, we can start our settings.

WeChat sharing settings are set through wx.config.

<script>
wx.config({
  debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
  appId: '<&#63;php echo APPID;&#63;>', // 必填,公众号的唯一标识
  timestamp: <&#63;php echo $timestamp;&#63;>, // 必填,生成签名的时间戳
  nonceStr: '<&#63;php echo $noncestr;&#63;>', // 必填,生成签名的随机串
  signature: '<&#63;php echo $signature;&#63;>',// 必填,签名
  jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage'] // 必填,需要使用的JS接口列表
});
</script>

The middle appid is the appid of our WeChat official account, timestamp is the current timestamp, noncestr is a random string used to generate signatures, signature is the generated signature, jsapilist is the WeChat interface we need to use, here we Just use the two interfaces of sharing to friends and sharing to Moments.

Briefly list the generation process of timestamp, noncestr, and signature:

// 生成签名
 // 生成随机字符串
class RandChar{
 function getRandChar($length){
  $str = null;
  $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  $max = strlen($strPol)-1;

  for($i=0;$i<$length;$i++){
  $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
  }
  return $str;
 }
}
$randCharObj = new RandChar();
$noncestr = $randCharObj->getRandChar(16);


$timestamp = time();
if ($_SERVER['QUERY_STRING']){
  $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'&#63;'.$_SERVER['QUERY_STRING'];
}else{
  $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
}

$parameters = array("noncestr" => $noncestr,
            "jsapi_ticket" => $ticket,
            "timestamp" => $timestamp,
            "url" => $url);
ksort($parameters);

$string1 = "";
foreach ($parameters as $key => $val){
  $string1 .= $key."=".$val."&";
}
$string1 = substr($string1,0,-1);
$signature = sha1($string1);

At this point, we have completed a configuration of wx.config. Next, we can freely set the small pictures and introduction content we just mentioned:

  wx.ready(function(){
    // 分享到朋友圈设置
    wx.onMenuShareTimeline({
      title: '测试标题', // 分享标题
      link: 'http://www.baidu.com', // 分享链接
      imgUrl: 'http://mp.weixin.qq.com/wiki/static/assets/dc5de672083b2ec495408b00b96c9aab.png', // 分享图标
      success: function () { 
        alert("分享成功");
      },
      cancel: function () { 
        alert("分享失败");
      }
    });
    // 分享给好友
    wx.onMenuShareAppMessage({
      title: '测试标题', // 分享标题
      desc: '测试分享描述', // 分享描述
      link: 'http://www.baidu.com', // 分享链接
      imgUrl: 'http://mp.weixin.qq.com/wiki/static/assets/dc5de672083b2ec495408b00b96c9aab.png', // 分享图标
      type: '', // 分享类型,music、video或link,不填默认为link
      dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
      success: function () { 
        alert("分享成功");
      },
      cancel: function () { 
        alert("分享失败");
      }
    });
  })

In the middle, the values ​​​​success and cancel are also very commonly used. They represent the js callback after successful sharing and the callback after canceling sharing respectively. They are used to judge whether the user will display psychological test answers after sharing in the circle of friends. Small functions are still very useful.

The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope that everyone will support Script Home.

Statement:
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