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, // 開啟調(diào)試模式,調(diào)用的所有api的返回值會(huì)在客戶端alert出來,若要查看傳入的參數(shù),可以在pc端打開,參數(shù)信息會(huì)通過log打出,僅在pc端時(shí)才會(huì)打印。 appId: '{$appid}', // 必填,公眾號(hào)的唯一標(biāo)識(shí) timestamp:{$timestamp} , // 必填,生成簽名的時(shí)間戳 nonceStr: '{$nonceStr}', // 必填,生成簽名的隨機(jī)串 signature: '{$signature}',// 必填,簽名,見附錄1 jsApiList: ['onMenuShareAppMessage','onMenuShareTimeline'] // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2 }); wx.ready(function(){ //分享給朋友 wx.onMenuShareAppMessage({ title: {$title}, // 分享標(biāo)題 此處$title可在控制器端傳遞也可在頁(yè)面?zhèn)鬟f 頁(yè)面?zhèn)鬟f講解在下面哦 desc: {$desc}, //分享描述 link: {$link}, // 分享鏈接 imgUrl: {$imgurl}, // 分享圖標(biāo) type: '', // 分享類型,music、video或link,不填默認(rèn)為link dataUrl: '', // 如果type是music或video,則要提供數(shù)據(jù)鏈接,默認(rèn)為空 success: function () { alert('分享成功'); }, cancel: function () { // 用戶取消分享后執(zhí)行的回調(diào)函數(shù) // alert('取消分享'); } }); //分享到朋友圈 wx.onMenuShareTimeline({ title: {$title}, // 分享標(biāo)題 desc: {$desc}, // 分享描述 link: {$link}, // 分享鏈接 imgUrl: {$imgurl}, // 分享圖標(biāo) success: function () { // 用戶確認(rèn)分享后執(zhí)行的回調(diào)函數(shù) }, cancel: function () { // 用戶取消分享后執(zhí)行的回調(diào)函數(shù) } }); }); </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('APPID'), C('SECRET'));//此處C里面的東西為你所使用的公眾號(hào)的appid和secret,這倆個(gè)東西可在微信公眾平臺(tái)獲取到 不詳細(xì)解釋 找不到追加評(píng)論(講解) JSSDK文件代碼在下 $signPackage = $jssdk->GetSignPackage(); $this->assign('appid',$signPackage["appId"]); $this->assign('timestamp',$signPackage["timestamp"]); $this->assign('nonceStr',$signPackage["nonceStr"]); $this->assign('signature',$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 一定要?jiǎng)討B(tài)獲取,不能 hardcode. $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $timestamp = time(); $nonceStr = $this->createNonceStr(); // 這里參數(shù)的順序要按照 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 應(yīng)該全局存儲(chǔ)與更新,以下代碼以寫入到文件中做示例 $data = json_decode($this->get_php_file("jsapi_ticket.php")); if ($data->expire_time < time()) { $accessToken = $this->getAccessToken(); // 如果是企業(yè)號(hào)用以下 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 應(yīng)該全局存儲(chǔ)與更新,以下代碼以寫入到文件中做示例 $data = json_decode($this->get_php_file("access_token.php")); if ($data->expire_time < time()) { // 如果是企業(yè)號(hào)用以下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['access_token']; // 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); // 為保證第三方服務(wù)器與微信服務(wù)器之間數(shù)據(jù)傳輸?shù)陌踩?,所有微信接口采用https方式調(diào)用,必須使用下面2行代碼打開ssl安全校驗(yàn)。 // 如果在部署過程中代碼在此處驗(yàn)證失敗,請(qǐng)到 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, // 分享標(biāo)題 desc: desc, //分享描述 link: link, // 分享鏈接 imgUrl: imgurl, // 分享圖標(biāo) type: '', // 分享類型,music、video或link,不填默認(rèn)為link dataUrl: '', // 如果type是music或video,則要提供數(shù)據(jù)鏈接,默認(rèn)為空 success: function () { alert('分享成功'); }, cancel: function () { // 用戶取消分享后執(zhí)行的回調(diào)函數(shù) // alert('取消分享'); } }); //分享到朋友圈 wx.onMenuShareTimeline({ title: title, // 分享標(biāo)題 desc: desc, // 分享描述 link: link, // 分享鏈接 imgUrl: imgurl, // 分享圖標(biāo) success: function () { // 用戶確認(rèn)分享后執(zhí)行的回調(diào)函數(shù) }, cancel: function () { // 用戶取消分享后執(zhí)行的回調(diào)函數(shù) // alert('已取消分享'); } }); }); }; </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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)