关于微信分享到朋友圈(Thinkphp框架下实现)

时间:2022-03-11 04:00:14

PHP部分

扩展类代码部分:

<?php
namespace Think; class JsSdk {
private $appId;
private $appSecret;
public $debug = false; public function __construct($appId, $appSecret) {
$this->appId = $appId;
$this->appSecret = $appSecret;
} public function getSignPackage() {
$jsapiTicket = $this->getJsApiTicket();
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$timestamp = time();
$nonceStr = $this->createNonceStr(); // 这里参数的顺序要按照 key 值 ASCII 码升序排序
$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$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 = ) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for ($i = ; $i < $length; $i++) {
$str .= substr($chars, mt_rand(, strlen($chars) - ), );
}
return $str;
} private function getJsApiTicket() {
//debug模式
if ($this->debug) {
// jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode(file_get_contents("jsapi_ticket.json"));
} else {
//从cache中读取,基于ThinkPHP的缓存机制
$data = (object)(S('jsapi_ticket_json'));
} if ($data->expire_time < time()) {
$accessToken = $this->getAccessToken();
$url = "http://api.weixin.qq.com/cgi-bin/ticket/getticket?type=1&access_token=$accessToken";
$res = json_decode($this->httpGet($url));
$ticket = $res->ticket; if ($ticket) {
$data->expire_time = time() + ;
$data->jsapi_ticket = $ticket; //debug模式
if ($this->debug) {
$fp = fopen("jsapi_ticket.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
} else {
//将对象以数组的形式进行缓存
S('jsapi_ticket_json', (array)$data);
} }
} else {
$ticket = $data->jsapi_ticket;
} return $ticket;
} private function getAccessToken() { //debug模式
if ($this->debug) {
// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode(file_get_contents("access_token.json"));
dump($data);
die();
} else {
//从缓存中读取数组并转成对象
$data = (Object)(S('access_token.json'));
} if ($data->expire_time < time()) {
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential
&appid=$this->appId&secret=$this->appSecret";
$res = json_decode($this->httpGet($url));
$access_token = $res->access_token; if ($access_token) {
$data->expire_time = time() + ;
$data->access_token = $access_token; //debug模式
if ($this->debug) {
$fp = fopen("access_token.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
} else {
//缓存数组
S('access_token.json', (array)$data);
} }
} else {
$access_token = $data->access_token;
}
return $access_token;
} private function httpGet($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, );
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
//错误检测
$error = curl_error($curl);
curl_close($curl); //发生错误,抛出异常
if($error) throw new \Exception('请求发生错误(表检查是否在授权域名下访问):' . $error); return $res;
}
}

控制器部分代码:

public function reurnWeixinCode() {
$jssdk = new \Think\Jssdk(WX_GONGZHONGHAO_APPID, WX_GONGZHONGHAO_APPSECRET);
$signPackage = $jssdk->GetSignPackage();
return $signPackage;
}

Html部分

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