
正文
微信JS-SDK接口,分享到朋友圈”按钮点击状态及自定义分享内容接口
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
jssdk.php 接口文件
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['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 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;
} private function getJsApiTicket() {
// jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode(file_get_contents("wxjs/jsapi_ticket.json"));
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));
//print_r($res);
$ticket = $res->ticket;
if ($ticket) {
$data->expire_time = time() + 7000;
$data->jsapi_ticket = $ticket;
$fp = fopen("wxjs/jsapi_ticket.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
} else {
$ticket = $data->jsapi_ticket;
} return $ticket;
} private function getAccessToken() {
// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode(file_get_contents("wxjs/access_token.json"));
if ($data->expire_time < time()) {
//if (true) {
// 如果是企业号用以下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($this->httpGet($url));
// print_r($res);
$access_token = $res->access_token;
if ($access_token) {
$data->expire_time = time() + 7000;
$data->access_token = $access_token;
$fp = fopen("wxjs/access_token.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
} 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, 500);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_URL, $url); $res = curl_exec($curl);
curl_close($curl); return $res;
}
}
/*
* 微信分享 朋友、朋友圈 基础配置
*
*/
调用jssdk.php文件获取 singnPackage
function insert_share(){
$weixin_info = $GLOBALS['db']->getRow("SELECT * FROM ".$GLOBALS['ecs']->table('weixin_config'));
if($weixin_info['title'] && $weixin_info['appid'] && $weixin_info['appsecret']){
require_once "wxjs/jssdk.php"; $jssdk = new JSSDK($weixin_info['appid'], $weixin_info['appsecret']);
$signPackage = $jssdk->GetSignPackage();
if($signPackage){
//判断是否登陆
if(!empty($_SESSION['user_id'])){
$GLOBALS['smarty']->assign('is_login', '1');
}
// //判断是否微信
$is_weixin = is_weixin();
if($is_weixin){
$GLOBALS['smarty']->assign('is_weixin', '1');
} $need_cache = $GLOBALS['smarty']->caching;
$GLOBALS['smarty']->caching = false;
$GLOBALS['smarty']->assign('weixin_info', $weixin_info);
$GLOBALS['smarty']->assign('signPackage', $signPackage);
$GLOBALS['smarty']->assign ( 'is_thumbnail', $weixin_info['is_thumbnail'] );
$GLOBALS['smarty']->assign ( 'weixin_logo', $weixin_info['weixin_logo'] );$shop_name = $weixin_info['title'];$web_url ='http://'.$_SERVER['HTTP_HOST'];if(preg_match('/goods.php/i', $_SERVER['REQUEST_URI'])){//处理商品详情页分享 $goods_id = intval($_GET['id']);$sql = "select * from ". $GLOBALS['ecs']->table('goods') ." where goods_id=".$goods_id; $row = $GLOBALS['db']->getRow($sql); $goods_price = $row['shop_price']; $sharemsg = sprintf($weixin_info['sharemsg'],$shop_name,$goods_price);//后台自定义描述$share_tiele = $row['goods_name']; if( $weixin_info['is_thumbnail'] == 0){ $share_img = $web_url."/".$row['goods_thumb']; }else{$share_img = $web_url."/mobile/".$weixin_info['weixin_logo'];}
}elseif(preg_match('/tuiguang.php/i', $_SERVER['REQUEST_URI']) || preg_match('/article.php/i', $_SERVER['REQUEST_URI'])){//单品推广/文章详情 $article_id = intval($_GET['id']); $sql = "select * from ". $GLOBALS['ecs']->table('article') ." where article_id=".$article_id; $row = $GLOBALS['db']->getRow($sql);if(!empty($row['description'])){ $sharemsg = $row['description'];//描述 }else{ $sharemsg = $GLOBALS['_CFG']['shop_desc'];//描述 }$share_tiele = $row['title'];//标题 if( $weixin_info['is_thumbnail'] == 0 && !empty($row['file_url'])){//缩略图 $share_img = $web_url."/mobile/".$row['file_url']; }else{$share_img = $web_url."/mobile/".$weixin_info['weixin_logo'];}}elseif(preg_match('/article_detail.php/i', $_SERVER['REQUEST_URI'])){//文章广告植入系统 $article_id = intval($_GET['id']); $sql = "select * from ". $GLOBALS['ecs']->table('article') ." where article_id=".$article_id; $row = $GLOBALS['db']->getRow($sql);if(!empty($row['description'])){ $sharemsg = $row['description'];//描述 }else{ $sharemsg = "转发文章也能赚钱?!不信您也来试试!!";//描述 }$share_tiele = $row['title'];//标题 if( $weixin_info['is_thumbnail'] == 0 && !empty($row['file_url'])){//缩略图 $share_img = $web_url."/mobile/".$row['file_url']; }else{$share_img = $web_url."/mobile/".$weixin_info['weixin_logo'];}}else{$sharemsg = $_CFG['shop_desc'];$sql = "select value from ". $GLOBALS['ecs']->table('ecsmart_shop_config') ." where code= 'shop_name'"; $share_tiele = $GLOBALS['db']->getOne($sql);$sql = "select value from ". $GLOBALS['ecs']->table('ecsmart_shop_config') ." where code= 'shop_desc'"; $sharemsg = $GLOBALS['db']->getOne($sql);$share_img = $web_url."/mobile/".$weixin_info['weixin_logo'];} $user_id = $_SESSION['user_id'];$sql = "select * from ". $GLOBALS['ecs']->table('weixin_user') ." where ecuid= '$user_id'"; $ret = $GLOBALS['db']->getRow($sql);$guide_qrcode = $web_url."/mobile/".$weixin_info['guide_qrcode'];
//echo $_SESSION['user_id'].'-'.$_SESSION['show_guide_qrcode'];
if( $weixin_info['open_guide'] == 1 && $ret['isfollow'] == 0 && $_SESSION['user_id'] && empty($_SESSION['show_guide_qrcode']) ){//是否开启未关注用户引导关注二维码$guide_qrcode = $web_url."/mobile/".$weixin_info['guide_qrcode'];$GLOBALS['smarty']->assign('open_guide', 1);$GLOBALS['smarty']->assign('guide_qrcode', $guide_qrcode);
$_SESSION['show_guide_qrcode']=1;}$GLOBALS['smarty']->assign('share_tiele', $share_tiele);$GLOBALS['smarty']->assign('share_img', $share_img);$GLOBALS['smarty']->assign('sharemsg', $sharemsg); $output = $GLOBALS['smarty']->fetch('library/share.lbi'); $GLOBALS['smarty']->caching = $need_cache; return $output;
} }
}
模板文件中,调用weixin的js接口
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script><script>
wx.config({
debug: false,
appId: '{$signPackage.appId}',
timestamp: '{$signPackage.timestamp}',
nonceStr: '{$signPackage.nonceStr}',
signature: '{$signPackage.signature}',
jsApiList: [
// 所有要调用的 API 都要加到这个列表中
'onMenuShareTimeline','onMenuShareAppMessage','getLocation','translateVoice'
]
});
wx.ready(function () {//分享到朋友圈
wx.onMenuShareTimeline({link: window.location.href, // 分享链接
title: '{$sharemsg}', // 分享标题
imgUrl: '{$share_img}',// 分享图标
<!--{if $is_login}-->
success: function () {
console.log("weixin_share.php?act=mycheck");
$.post("weixin_share.php?act=mycheck",{'id':'1','uid':'1','show':'1','type':'pengyouquan'},function(data,status){
console.log("111111111111111111");
data= eval('(' + data + ')');
if (data.state == 1){
alert('微信分享收益提示:本次分享获得'+data.share_money+'元;'+data.share_point+'积分');
}else{
alert('微信分享收益提示:今天的奖励已赠送过啦!感谢您的分享!!');
}
});
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
<!--{/if}-->
});//分享给朋友
wx.onMenuShareAppMessage({title: '{$share_tiele}',//分享标题
desc: '{$sharemsg}',
link: window.location.href,
imgUrl: '{$share_img}', // 分享图标
type: '', // 分享类型,music、video或link,不填默认为link
dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
<!--{if $is_login}-->
success: function () {
// 用户确认分享后执行的回调函数$.post("weixin_share.php?act=mycheck",{'id':'1','uid':'1','show':'1','type':'pengyou'},function(data,status){
console.log("2222222222222");
data= eval('(' + data + ')');
if (data.state == 1){
alert('微信分享收益提示:本次分享获得'+data.share_money+'元;'+data.share_point+'积分');
}else{
alert('微信分享收益提示:今天的奖励已赠送过啦!感谢您的分享!!');
}});
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
<!--{/if}-->
});
});
</script>
分享成功后,回调写积分文件
<?phpdefine('IN_ECS', true);
define('ECS_ADMIN', true);require('../includes/init.php');
$is_weixin = is_weixin();
if($is_weixin && !empty($_POST['id']) && !empty($_POST['uid']) && !empty($_POST['show']) && !empty($_POST['type']) && !empty($_GET['act']) && !empty($_SESSION['user_id'])){
if($_GET['act'] == 'mycheck')
{
if($_POST['type'] == 'pengyouquan'){
$weixin_info = $db->getRow("select * from ".$ecs->table('weixin_config')." where id='1'");
$share_money = round(randomFloat_share($weixin_info['pengyouquan_money'], $weixin_info['pengyouquan_money_up']),2);
$share_point = round(randomFloat_share($weixin_info['pengyouquan_point'], $weixin_info['pengyouquan_point_up']));
if($weixin_info['appid'] && $weixin_info['appsecret'] && $weixin_info['title'] && $weixin_info['is_pengyouquan'] == '1'){
$nowtime = mktime();
//$yestime = strtotime(date('Y-m-d'));
$yestime = strtotime(date('Y-m-d', time())); $count = $db->getOne("select count(*) from ".$ecs->table('weixin_share')." where type='2' and user_id=".$_SESSION['user_id']." and create_time > '$yestime'");if($weixin_info['is_everyday'] == '1'){if($count <= $weixin_info['pengyouquan_times'] ){
$info = date('Y-m-d H:i:s')."微信分享朋友圈,获得".$share_money.'元,'.$share_point.'积分';
log_account_change($_SESSION['user_id'], $share_money, 0, 0, $share_point, $info);
}else{
$db->query("insert into ".$ecs->table('weixin_share')." (`user_id`,`type`,`create_time`) values ('$_SESSION[user_id]','1','$nowtime') ");
$state = '0';
echo json_encode(array('state'=>$state ));
exit; }
}
else
{
if($count <= $weixin_info['pengyouquan_times'] ){
$info = date('Y-m-d H:i:s')."微信分享朋友圈,获得".$share_money.'元,'.$share_point.'积分';
log_account_change($_SESSION['user_id'], $share_money, 0, 0, $share_point, $info);
}else{
$db->query("insert into ".$ecs->table('weixin_share')." (`user_id`,`type`,`create_time`) values ('$_SESSION[user_id]','1','$nowtime') ");
$state = '0';
echo json_encode(array('state'=>$state ));
exit; }
}
$db->query("insert into ".$ecs->table('weixin_share')." (`user_id`,`type`,`create_time`) values ('$_SESSION[user_id]','2','$nowtime') "); $state = '1';
echo json_encode(array('share_money'=>$share_money,'share_point'=>$share_point,'state'=>$state));
}
}if($_POST['type'] == 'pengyou'){
$weixin_info = $db->getRow("select * from ".$ecs->table('weixin_config')." where id='1'");
$share_money = round(randomFloat_share($weixin_info['pengyou_money'], $weixin_info['pengyou_money_up']),2);
$share_point = round(randomFloat_share($weixin_info['pengyou_point'], $weixin_info['pengyou_point_up']));
if($weixin_info['appid'] && $weixin_info['appsecret'] && $weixin_info['title'] && $weixin_info['is_pengyou'] == '1'){
$nowtime = mktime();
//$yestime = strtotime(date('Y-m-d'));
$yestime = strtotime(date('Y-m-d', time()));
$count = $db->getOne("select count(*) from ".$ecs->table('weixin_share')." where type='1' and user_id=".$_SESSION['user_id']." and create_time > '$yestime'");
if($weixin_info['is_everyday'] == '1'){if($count <= $weixin_info['pengyou_times'] ){
$info = date('Y-m-d H:i:s')."微信分享给朋友,获得".$share_money.'元,'.$share_point.'积分';
log_account_change($_SESSION['user_id'], $share_money, 0, 0, $share_point, $info);
}else{
$db->query("insert into ".$ecs->table('weixin_share')." (`user_id`,`type`,`create_time`) values ('$_SESSION[user_id]','1','$nowtime') ");
$state = '0';
echo json_encode(array('state'=>$state ));
exit; }
}
else
{
if($count <= $weixin_info['pengyou_times'] ){
$info = date('Y-m-d H:i:s')."微信分享给朋友,获得".$share_money.'元,'.$share_point.'积分';
log_account_change($_SESSION['user_id'], $share_money, 0, 0, $share_point, $info);
}else{
$db->query("insert into ".$ecs->table('weixin_share')." (`user_id`,`type`,`create_time`) values ('$_SESSION[user_id]','1','$nowtime') ");
$state = '0';
echo json_encode(array('state'=>$state ));
exit; }
}
$db->query("insert into ".$ecs->table('weixin_share')." (`user_id`,`type`,`create_time`) values ('$_SESSION[user_id]','1','$nowtime') ");
$state = '1';
echo json_encode(array('share_money'=>$share_money,'share_point'=>$share_point,'state'=>$state));}
}
}
}function is_weixin()
{
$useragent = addslashes($_SERVER['HTTP_USER_AGENT']);
if(strpos($useragent, 'MicroMessenger') === false && strpos($useragent, 'Windows Phone') === false )
{
return false;
}
else
{
return true;
}
}//生成随机数 P R I N C E Q Q 120 029 121
function randomFloat_share($min = 0, $max = 1) {
return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}






