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>
分享成功後,回調寫積分文件<?php
define('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);
}