Home  >  Article  >  WeChat Applet  >  Detailed explanation of PHP WeChat sharing development

Detailed explanation of PHP WeChat sharing development

高洛峰
高洛峰Original
2017-01-16 14:00:161534browse

Share an experience in PHP WeChat development. Sometimes when a project or project needs to be shared on WeChat and then do a series of events, then we need to get the WeChat sharing action, which means we already know that the current thing has been has been shared, then it is obviously not possible to use WeChat's default sharing. We need to configure WeChat sharing ourselves. When users share, they follow our predetermined procedures, so we can easily achieve what they do after sharing.

On the page side, there is mainly a js as follows:

<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
 
<script>
wx.config({
   debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
   appId: &#39;{$appid}&#39;, // 必填,公众号的唯一标识
   timestamp:{$timestamp} , // 必填,生成签名的时间戳
   nonceStr: &#39;{$nonceStr}&#39;, // 必填,生成签名的随机串
   signature: &#39;{$signature}&#39;,// 必填,签名,见附录1
   jsApiList: [&#39;onMenuShareAppMessage&#39;,&#39;onMenuShareTimeline&#39;] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
 });
 
 wx.ready(function(){
  //分享给朋友
  wx.onMenuShareAppMessage({
    title: {$title}, // 分享标题 此处$title可在控制器端传递也可在页面传递 页面传递讲解在下面哦
    desc: {$desc}, //分享描述
    link: {$link}, // 分享链接
    imgUrl: {$imgurl}, // 分享图标
    type: &#39;&#39;, // 分享类型,music、video或link,不填默认为link
    dataUrl: &#39;&#39;, // 如果type是music或video,则要提供数据链接,默认为空
    success: function () {
       alert(&#39;分享成功&#39;);
    },
    cancel: function () {
      // 用户取消分享后执行的回调函数
      // alert(&#39;取消分享&#39;);
    }
  });
  //分享到朋友圈
   wx.onMenuShareTimeline({
    title: {$title}, // 分享标题
    desc: {$desc}, // 分享描述
    link: {$link}, // 分享链接
    imgUrl: {$imgurl}, // 分享图标
    success: function () {
      // 用户确认分享后执行的回调函数
    },
    cancel: function () {
      // 用户取消分享后执行的回调函数
    }
  });
 });
 
</script>

When wx.config is configured, the program will proceed to the following sharing. For debugging here, you can change false to true if configured properly. Then if the normal pop-up ok and other information are not configured, changing this to true will not have any pop-up effect

wx.config requires four parameters from the controller, namely appId, timestamp, nonceStr, and signature; control The device code is as follows:

<?php
 
$jssdk = new \Home\Util\JSSDK(C(&#39;APPID&#39;), C(&#39;SECRET&#39;));//此处C里面的东西为你所使用的公众号的appid和secret,这俩个东西可在微信公众平台获取到 不详细解释 找不到追加评论(讲解) JSSDK文件代码在下
$signPackage = $jssdk->GetSignPackage();
 
$this->assign(&#39;appid&#39;,$signPackage["appId"]);
$this->assign(&#39;timestamp&#39;,$signPackage["timestamp"]);
$this->assign(&#39;nonceStr&#39;,$signPackage["nonceStr"]);
 $this->assign(&#39;signature&#39;,$signPackage["signature"]);

Wx.config is configured here, and you can also pass in title and other information. Here is an example

$this->assign('title', $title);

JSSDK file code:

<?php
namespace Home\Util;
use Think\Controller;
class JSSDK{
 private $appId;
 private $appSecret;
 public function __construct($appId, $appSecret) {
  $this->appId = $appId;
  $this->appSecret = $appSecret;
 }
 public function getSignPackage() {
  $jsapiTicket = $this->getJsApiTicket();
  // 注意 URL 一定要动态获取,不能 hardcode.
  $protocol = (!empty($_SERVER[&#39;HTTPS&#39;]) && $_SERVER[&#39;HTTPS&#39;] !== &#39;off&#39; || $_SERVER[&#39;SERVER_PORT&#39;] == 443) ? "https://" : "http://";
  $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  $timestamp = time();
  $nonceStr = $this->createNonceStr();
  // 这里参数的顺序要按照 key 值 ASCII 码升序排序
  $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url";
  $signature = sha1($string);
  $signPackage = array(
   "appId"   => $this->appId,
   "nonceStr" => $nonceStr,
   "timestamp" => $timestamp,
   "url"    => $url,
   "signature" => $signature,
   "rawString" => $string
  );
  return $signPackage;
 }
 private function createNonceStr($length = 16) {
  $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  $str = "";
  for ($i = 0; $i < $length; $i++) {
   $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  }
  return $str;
 }
 public function getJsApiTicket() {
  // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
  $data = json_decode($this->get_php_file("jsapi_ticket.php"));
  if ($data->expire_time < time()) {
   $accessToken = $this->getAccessToken();  
   // 如果是企业号用以下 URL 获取 ticket
   // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
   $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$accessToken&type=jsapi";
   $res = json_decode($this->httpGet($url));
   $ticket = $res->ticket;
   // var_dump($url);
   if ($ticket) {
    $data->expire_time = time() + 7000;
    $data->jsapi_ticket = $ticket;
    $this->set_php_file("jsapi_ticket.php", json_encode($data));
   }
  } else {
   $ticket = $data->jsapi_ticket;
  }
  return $ticket;
 }
 public function getAccessToken() {
  // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
  $data = json_decode($this->get_php_file("access_token.php")); 
  if ($data->expire_time < time()) {
   // 如果是企业号用以下URL获取access_token
   // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
   $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
   $res = $this->getJson($url);
   $access_token = $res[&#39;access_token&#39;];
   // var_dump($res);
   if ($access_token) {
    $data->expire_time = time() + 7000;
    $data->access_token = $access_token;
    $this->set_php_file("access_token.php", json_encode($data));
   }
  } else {
   $access_token = $data->access_token;
  }
  return $access_token;
  // $aa = $access_token;
  // var_dump($aa);
 }
 //获取access_token
 public function getJson($url){
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   $output = curl_exec($ch);
   curl_close($ch);
   // var_dump(json_decode($output, true));
   return json_decode($output, true);
 }
 //获取ticket
 private function httpGet($url) {
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  // curl_setopt($curl, CURLOPT_TIMEOUT, 500);
  // 为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,必须使用下面2行代码打开ssl安全校验。
  // 如果在部署过程中代码在此处验证失败,请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  $res = curl_exec($curl);
  // var_dump($res);
  curl_close($curl);  
  return $res;
 }
 private function get_php_file($filename) {
  return trim(substr(file_get_contents($filename), 15));
  // echo trim(substr(file_get_contents($filename), 15));die;
  // $aa = trim(substr(file_get_contents($filename), 15));
 }
 private function set_php_file($filename, $content) {
  $fp = fopen($filename, "w");
  fwrite($fp, "<?php exit();?>" . $content);
  fclose($fp);
 }
}

At this point, WeChat sharing comes to an end, but there are flaws. What if we want to dynamically pass parameters? That is to say, when the page information wx. After config is configured, what should we do if we suddenly want to reassign variable information such as $title?

We can write sharing in a method as follows (rough code):

<script>
var zl= function (title,link,imgurl,desc){
 wx.ready(function(){
  //分享给朋友
  wx.onMenuShareAppMessage({
    title: title, // 分享标题
    desc: desc, //分享描述
    link: link, // 分享链接
    imgUrl: imgurl, // 分享图标
    type: &#39;&#39;, // 分享类型,music、video或link,不填默认为link
    dataUrl: &#39;&#39;, // 如果type是music或video,则要提供数据链接,默认为空
    success: function () {
       alert(&#39;分享成功&#39;);
    },
    cancel: function () {
      // 用户取消分享后执行的回调函数
      // alert(&#39;取消分享&#39;);
    }
  });
  //分享到朋友圈
   wx.onMenuShareTimeline({
    title: title, // 分享标题
    desc: desc, // 分享描述
    link: link, // 分享链接
    imgUrl: imgurl, // 分享图标
    success: function () {
      // 用户确认分享后执行的回调函数
    },
    cancel: function () {
      // 用户取消分享后执行的回调函数
      // alert(&#39;已取消分享&#39;);
    }
  });
 });
};
</script>

Explain that the title and other information in the share have been configured when entering the page from the controller. Then configure After that, I want to give the title value again on the page, so this is the method. The page copy code is as follows

<script>
zl(title,link,imgurl,desc);
</script>

easy. If you want to know more about this and other functions on WeChat, you can Reference Manual

The above is the entire content of this article. I hope it will be helpful to everyone's learning, and I also hope that everyone will support the PHP Chinese website.

For more articles related to PHP WeChat sharing and development details, please pay attention to the PHP Chinese website!

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
Previous article:js WeChat sharing APINext article:js WeChat sharing API