前几天因为项目所需要实现微信分享接口,在网上搜了一大堆,实现办法大致分为两种,第一:在body之后加一个img标签并且设置display:none,这种方法感觉不科学所以我没有测试过。第二:使用微信的分享接口,但在网上也没用找到完整的示例,还是自己折腾吧,请看下面。
实现工具:GetwxLink
注意:1:jsapi_ticket和access_token需要存在本地,access_token微信一天限制获取2000次
2:获取access_token之前先确认ip地址在白名单内!!!
第一步:
先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
注:认证帐号才有分享权限
第二步
创建一个demo.php文件和wxshare.js
demo.php
// 步骤1.设置appid和appsecret
private $WX_APPID="wx9b1ec4fef5bf666";
private $WX_SECRET="8e3e63698ddac81947f52b0a7be45b6666";
// 步骤2.生成签名的随机串
function nonceStr($length){
$str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';//62个字符
$strlen = 62;
while($length > $strlen){
$str .= $str;
$strlen += 62;
}
$str = str_shuffle($str);
return substr($str,0,$length);
}
// 步骤3.获取access_token
function getAccessToken()
{
// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode(self::get_php_file(WEIXIN."/access_token.php"));
// var_dump($data);exit;
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 = json_decode(self::httpGet($url));
$access_token = $res->access_token;
if ($access_token) {
$data->expire_time = time() + 7000;
$data->access_token = $access_token;
self::set_php_file(WEIXIN."/access_token.php", json_encode($data));
}
} else {
$access_token = $data->access_token;
}
return $access_token;
}
// 步骤4.获取ticket
function ticket()
{
// jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode($this->get_php_file(WEIXIN."/jsapi_ticket.php"));
$data1 = json_decode($this->get_php_file(WEIXIN."/access_token.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?type=jsapi&access_token=$accessToken";
$res = json_decode($this->httpGet($url));
//var_dump($res);exit;
if($res->errcode==40001){//token过期重新生成
$data1->expire_time = 0;
$data1->access_token = '';
$this->set_php_file(WEIXIN."access_token.php", json_encode($data1));
$data->expire_time = 0;
$data->jsapi_ticket = '';
$this->set_php_file(WEIXIN."jsapi_ticket.php", json_encode($data));
$this->getSignPackage();//重新执行下请求token的方法
}
$ticket = $res->ticket;
if ($ticket) {
$data->expire_time = time() + 7000;
$data->jsapi_ticket = $ticket;
$this->set_php_file(WEIXIN."/jsapi_ticket.php", json_encode($data));
}
} else {
$ticket = $data->jsapi_ticket;
}
return $ticket;
}
// 步骤5.生成wx.config需要的参数
function share()
{
$surl = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
// var_dump(self::getAccessToken());exit;
return self::getWxConfig(self::ticket(), $surl, time(), self::nonceStr(16));
}
function getWxConfig($jsapiTicket,$url,$timestamp,$nonceStr) {
$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url";
$signature = sha1 ( $string );
$WxConfig["appId"] = $this->WX_APPID ;
$WxConfig["nonceStr"] = $nonceStr;
$WxConfig["timestamp"] = $timestamp;
$WxConfig["url"] = $url;
$WxConfig["signature"] = $signature;
$WxConfig["rawString"] = $string;
return $WxConfig;
}
function http_get($url){
$oCurl = curl_init();
if(stripos($url,"https://")!==FALSE){
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
}
curl_setopt($oCurl, CURLOPT_URL, $url);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
$sContent = curl_exec($oCurl);
$aStatus = curl_getinfo($oCurl);
curl_close($oCurl);
if(intval($aStatus["http_code"])==200){
return $sContent;
}else{
return false;
}
}
/*get方法*/
private function httpGet($url) {
$curl = curl_init();
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, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);
return $res;
}
/*从文件中获取token*/
public function get_php_file($filename) {
return trim(substr(file_get_contents($filename), 15));
}
/*存储到文件中*/
public function set_php_file($filename, $content) {
$fp = fopen($filename, "w");
fwrite($fp, "<?php exit();?>" . $content);//防止执行php脚本,确保linux文件可写
fclose($fp);
}
网页部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Share Demo</title>
</head>
<body>
</body>
// 步骤6.调用JS接口
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
wx.config({
debug: false,
appId: '<?php echo $detail["share"]["appId"]; ?>',
timestamp: '<?php echo $detail["share"]["timestamp"]; ?>',
nonceStr: '<?php echo $detail["share"]["nonceStr"]; ?>',
signature: '<?php echo $detail["share"]["signature"]; ?>',
jsApiList: [
'checkJsApi',
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo',
'onMenuShareQZone',
]
});
var wstitle = "<?php echo $detail['act_ext2']; ?>号选手:<?php echo $detail['act_name']; ?>";
var wsdesc = "<?php echo $detail['act_beta']; ?>";
var wslink = "<?php echo $detail['share']['url']; ?>";
var wsimg = "http://<?php echo $detail['share_pic']; ?>";
</script>
<script src="wxshare.js"></script>
</html>
wxshare.js
wx.ready(function () {
// 分享到朋友圈
wx.onMenuShareTimeline({
title: wstitle,
link: wslink,
imgUrl: wsimg,
success: function () {
alert('分享成功');
},
cancel: function () {
}
});
// 分享给朋友
wx.onMenuShareAppMessage({
title: wstitle,
desc: wsdesc,
link: wslink,
imgUrl: wsimg,
success: function () {
alert('分享成功');
},
cancel: function () {
}
});
// 分享到QQ
wx.onMenuShareQQ({
title: wstitle,
desc: wsdesc,
link: wslink,
imgUrl: wsimg,
success: function () {
alert('分享成功');
},
cancel: function () {
}
});
// 微信到腾讯微博
wx.onMenuShareWeibo({
title: wstitle,
desc: wsdesc,
link: wslink,
imgUrl: wsimg,
success: function () {
alert('分享成功');
},
cancel: function () {
}
});
// 分享到QQ空间
wx.onMenuShareQZone({
title: wstitle,
desc: wsdesc,
link: wslink,
imgUrl: wsimg,
success: function () {
alert('分享成功');
},
cancel: function () {
}
});
});