document.querySelector('.photobtn').onclick = function () {
wx.chooseImage({
sizeType: ['compressed'],
count: 1,
success: function (res) {
localid = res.localIds.toString();
ajaxupload(localid);
},
fail: function (res) {
alert(JSON.stringify(res));
}
});
};
function ajaxupload(localIds) {
$('#loadingToast').show();
wx.uploadImage({
localId: localIds,
isShowProgressTips: 0,
success: function (res) {
$.ajax({
type: 'POST',
url: "{pigcms::U('Wall/AjaxdownloadMedia')}",
data:{
serverId : res.serverId,
},
success: function (retuendata) {
var data = JSON.parse(retuendata);
//$('#loadingToast').hide();
if(data.status == 1){
$('#loadingToast').hide();
showTip('上传成功!');
}else{
$('#loadingToast').hide();
showTip('上传失败!');
}
},
});
},
fail: function (res) {
$.ajax({
type: 'POST',
url: "{pigcms::U('Wall/AjaxWriteLogo')}",
data:{
data : res,
},
success: function (res) {
},
});
alert(JSON.stringify(res));
}
});
};
/*
@下载微信素材图片
@接收参数素材id $media_id
*/
function downloadMedia($media_id){
//$media_id = $_GET['media_id'];
//$access_token = $_GET['access_token'];
import("@.ORG.wall.WechatShares");
$share = new WechatShares($this->appId,$this->appSecret,$this->wecha_id);
$tokendata = $share->readtext('access_token');
$tokendata = json_decode($tokendata,true);
if(!empty($tokendata['access_token']) && $tokendata['access_token_expires_in'] > time()){
$access_token = $tokendata['access_token'];
}else{
$urls = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appId.'&secret='.$this->appSecret;
$rt=$this->curlGet($urls);
$jsonrt=json_decode($rt,1);
$tokendata['access_token'] = $access_token = isset( $jsonrt['access_token'] ) ? $jsonrt['access_token'] : "" ;
$tokendata['access_token_expires_in'] = time()+$jsonrt['expires_in'];
$share->writetext('access_token',$tokendata);
}
$url ="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$media_id;
$img = $this->curlGet($url);
$fileurl = 'uploads/wall/images/'.date('Y-m-d').'/'.$this->token.'/';
//$fileurl = 'uploads/wall/images/';
$filetype = "jpg";//文件类型,后缀
$randname = rand(1,9).time();//生成的随机名
if(!file_exists($fileurl)){
mkdir($fileurl,0777,true);//生成文件夹
}
$imgurl = $fileurl.$randname.'.'.$filetype;
$filesize = file_put_contents($imgurl,$img);//保存文件,返回图片大小
if($filesize){
$data['imgurl'] = 'http://'.$_SERVER['SERVER_NAME'].'/'.$imgurl;
$data['status'] = 1;
}else{
$data['status'] = 2;
}
return $data;
}
<?php
class WechatShares
{
private $appId = '';
private $appSecret = '';
public $error = array();
public $token = '';
public $wecha_id = '';
//构造函数获取access_token
function __construct($appId,$appSecret,$wecha_id){
$this->appId = $appId;
$this->appSecret = $appSecret;
$this->wecha_id = $wecha_id;
}
public function writetext($file,$conten,$filePath = ''){
if(empty($filePath)){
$filePath = "uploads/wall/WechatConfig/";
}
if (!file_exists($filePath)){
mkdir($filePath);
}
if(!file_exists($filePath)){
mkdir($filePath,0777);
}
$filename = $filePath.'/'.$file;
$json_string = json_encode($conten);
file_put_contents($filename, $json_string);
}
/*
@读取消息
@接收参数文件名称 $filename
@返回json格式的消息内容 $json
@判断当前文件是否存在,存在返回文件内容,不存在则返回文件不存在
*/
public function readtext($file,$filePath = ''){
if(empty($filePath)){
$filePath = "uploads/wall/WechatConfig/";
}
$filename = $filePath.'/'.$file;
if(file_exists($filename)){
$content = file_get_contents($filename);
$json = $content;
}else{
$json = '{"msg":"The file does not exist."}';
}
return $json;
}
public function config(){
$now = time();
$share_data = $this->readtext('share_ticket');
$share_data = json_decode($share_data,true);
if( (empty($share_data['share_ticket']) || empty($share_data['share_dated']) ) || ($share_data['share_ticket']!='' && $share_data['share_dated']!='' && $share_data['share_dated'] < $now ) ){
$tokenData = $this->getToken();
if($tokenData['errcode']){
$this->error['token_error'] = array('errcode'=>$tokenData['errcode'],'errmsg'=>$tokenData['errmsg']);
}else{
$access_token = $tokenData['access_token'];
$ticketData = $this->getTicket($access_token);
if($ticketData['errcode']>0){
$this->error['ticket_error'] = array('errcode'=>$ticketData['errcode'],'errmsg'=>$ticketData['errmsg']);
}else{
$ticketdata = array(
'share_ticket'=>$ticketData['ticket'],
'share_dated'=>$now+$ticketData['expires_in'],
);
$this->writetext('share_ticket',$ticketdata);
$ticket = $ticketData['ticket'];
}
}
}else{
$ticket = $share_data['share_ticket'];
}
//$url = $this->getUrl();
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$sign_data = $this->addSign($ticket,$url);
$html = <<<EOM
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js "></script>
<script type="text/javascript">
wx.config({
debug: false,
appId: '{$sign_data['appId']}',
timestamp: {$sign_data['timestamp']},
nonceStr: '{$sign_data['nonceStr']}',
signature: '{$sign_data['signature']}',
jsApiList: [
'checkJsApi',
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo',
'onMenuShareQZone',
'hideMenuItems',
'showMenuItems',
'hideAllNonBaseMenuItem',
'showAllNonBaseMenuItem',
'translateVoice',
'startRecord',
'stopRecord',
'onVoiceRecordEnd',
'playVoice',
'onVoicePlayEnd',
'pauseVoice',
'stopVoice',
'uploadVoice',
'downloadVoice',
'chooseImage',
'previewImage',
'uploadImage',
'downloadImage',
'getNetworkType',
'openLocation',
'getLocation',
'hideOptionMenu',
'showOptionMenu',
'closeWindow',
'scanQRCode',
'chooseWXPay',
'openProductSpecificView',
'addCard',
'chooseCard',
'openCard'
]
});
</script>
EOM;
return $html;
}
public function getError(){
dump($this->error);
}
public function addSign($ticket,$url){
$timestamp = time();
$nonceStr = rand(100000,999999);
$array = array(
"noncestr" => $nonceStr,
"jsapi_ticket" => $ticket,
"timestamp" => $timestamp,
"url" => $url,
);
ksort($array);
$signPars = '';
foreach($array as $k => $v) {
if("" != $v && "sign" != $k) {
if($signPars == ''){
$signPars .= $k . "=" . $v;
}else{
$signPars .= "&". $k . "=" . $v;
}
}
}
$result = array(
'appId' => $this->appId,
'timestamp' => $timestamp,
'nonceStr' => $nonceStr,
'url' => $url,
'signature' => SHA1($signPars),
);
return $result;
}
public function getUrl(){
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if(isset($_GET['code']) && isset($_GET['state']) && ($_GET['state'] == 'oauth')){
$url = $this->clearUrl($url);
if(isset($_GET['wecha_id'])){
$url .= '&wecha_id='.$this->wecha_id;
}
return $url;
}else{
return $url;
}
}
public function clearUrl($url){
$param = explode('&', $url);
for ($i=0,$count=count($param); $i < $count; $i++) {
if(preg_match('/^(code=|state=|wecha_id=).*/', $param[$i])){
unset($param[$i]);
}
}
return join('&',$param);
}
//获取token
public function getToken(){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appId."&secret=".$this->appSecret;
return $this->https_request($url);
}
public function getTicket($token){
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$token."&type=jsapi";
return $this->https_request($url);
}
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
);
$share_html = $this->createHtml($signPackage);
return $share_html;
//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() {
$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));
$ticket = $res->ticket;
return $ticket;
}
private function getAccessToken() {
$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;
return $access_token;
}
private function httpGet($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT,30);
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;
}
/*创建分享html*/
public function createHtml($sign_data){
$html = <<<EOM
<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: false,
appId: '{$sign_data['appId']}',
timestamp: {$sign_data['timestamp']},
nonceStr: '{$sign_data['nonceStr']}',
signature: '{$sign_data['signature']}',
jsApiList: [
'checkJsApi',
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo',
'onMenuShareQZone',
'hideMenuItems',
'showMenuItems',
'hideAllNonBaseMenuItem',
'showAllNonBaseMenuItem',
'translateVoice',
'startRecord',
'stopRecord',
'onVoiceRecordEnd',
'playVoice',
'onVoicePlayEnd',
'pauseVoice',
'stopVoice',
'uploadVoice',
'downloadVoice',
'chooseImage',
'previewImage',
'uploadImage',
'downloadImage',
'getNetworkType',
'openLocation',
'getLocation',
'hideOptionMenu',
'showOptionMenu',
'closeWindow',
'scanQRCode',
'chooseWXPay',
'openProductSpecificView',
'addCard',
'chooseCard',
'openCard'
]
});
</script>
<script type="text/javascript">
wx.ready(function () {
// 2.2 监听“分享给朋友”按钮点击、自定义分享内容及分享结果接口
if(window.shareData.tContent){
window.shareData.tContent = window.shareData.tContent;
}else{
window.shareData.tContent = window.shareData.tTitle;
}
wx.onMenuShareAppMessage({
title: window.shareData.tTitle,
desc: window.shareData.tContent,
link: window.shareData.sendFriendLink,
imgUrl: window.shareData.imgUrl,
type: '',
dataUrl: '',
success: function () {
shareHandle('frined');
},
cancel: function () {
//alert('用户取消分享后执行的回调函数');
}
});
// 2.2 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口
wx.onMenuShareTimeline({
title: window.shareData.tTitle,
link: window.shareData.sendFriendLink,
imgUrl: window.shareData.imgUrl,
success: function () {
shareHandle('frineds');
//alert('分享朋友圈成功');
},
cancel: function () {
//alert('分享朋友圈失败');
}
});
// 2.4 监听“分享到微博”按钮点击、自定义分享内容及分享结果接口
wx.onMenuShareWeibo({
title: window.shareData.tTitle,
desc: window.shareData.tContent,
link: window.shareData.sendFriendLink,
imgUrl: window.shareData.imgUrl,
success: function () {
shareHandle('weibo');
//alert('分享微博成功');
},
cancel: function () {
//alert('分享微博失败');
}
});
document.querySelector('#closeWindow').onclick = function () {
wx.closeWindow();
};
});
function shareHandle(to) {
var submitData = {
module: window.shareData.moduleName,
moduleid: window.shareData.moduleID,
token:'{$this->token}',
wecha_id:'{$this->wecha_id}',
url: window.shareData.sendFriendLink,
to:to
};
$.post('index.php?g=Wap&m=Share&a=shareData&token={$this->token}&wecha_id={$this->wecha_id}',submitData,function (data) {},'json')
}
</script>
EOM;
return $html;
}
//https请求(支持GET和POST)
protected function https_request($url, $data = null)
{
$curl = curl_init();
$header = "Accept-Charset: utf-8";
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
//curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
$errorno= curl_errno($curl);
if ($errorno) {
return array('curl'=>false,'errorno'=>$errorno);
}else{
$res = json_decode($output,1);
if ($res['errcode']){
return array('errcode'=>$res['errcode'],'errmsg'=>$res['errmsg']);
}else{
return $res;
}
}
curl_close($curl);
}
}
?>