欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

微信分享(微信好友、微信朋友圈、新浪微博、QQ好友、QQ空间)

程序员文章站 2022-06-26 20:02:19
...

index.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
	<meta charset="utf-8" />
	<title>微信分享</title>
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="renderer" content="webkit">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />   
	<meta name="baidu-site-verification" content="8X1bKAjuxm"/>

	<script src="https://cdn.bootcss.com/jquery/1.9.1/jquery.min.js"></script>
	<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
	<script src="./wxshare.js'"></script>
</head>
<body>
	微信分享
</body>
</html>

wxshare.js


let share = {
	//分享标题
	title: '分享标题',
	//分享右侧图片
	imgUrl: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
	//分享文字描述
	desc: '分享文本',
	//分享出去后 通过分享点击进入的url
	link: 'http://www.xxxh5.com/mbr_test/wx_share/jump.php'
}


startwxshare();

//1.微信分享调用
function startwxshare()
{
	var pageurl = encodeURIComponent(location.href.split('#')[0]);
	//请求后端分享参数(真j8坑逼,此处参数须拼在url中传输,即GET传参)
	$.ajax({
		url : "http://www.xxxh5.com/mbr_test/wx_share/weixinshare.php?type=wxshare&pageurl="+pageurl, 
		type : "GET",
		timeout:6000,  
		dataType : "jsonp",
		jsonp: "callback",
		jsonpCallback:"success_jsonpCallback_wxshare",
		cache : false,
		success : function(data)
		{
			if( !data ) return;

			//调用微信分享
			wxshare( data.appid, data.timestamp, data.noncestr, data.signature );	

		},
		error:function(textStatus, errorThrown)
		{
			console.log(textStatus);
		}
	}); 	
}


//2.微信分享函数
function wxshare(appid,timestamp,noncestr,signature){	
	//alert(encodeURIComponent(location.href.split('#')[0]));
	// alert( 'appid = ' + appid );
	// alert( 'timestamp = ' + timestamp );
	// alert( 'noncestr = ' + noncestr );
	// alert( 'signature = ' + signature );
	// alert( sharetitle + ' ; ' + sharedes + ' ; ' + shareimg );
	
	wx.config({
	  debug: false,//调试模式
	  appId: appid,
	  timestamp: timestamp,
	  nonceStr: noncestr,
	  signature: signature,
	  jsApiList: [
	  	'checkJsApi',
		'onMenuShareTimeline',
		'onMenuShareAppMessage',
		'onMenuShareQQ',
		'onMenuShareWeibo',
		'onMenuShareQZone'
	  ]
	});
	 

	wx.ready(function(){
		wx.checkJsApi({
			jsApiList: ['chooseImage'], // 需要检测的JS接口列表,所有JS接口列表见附录2,
			success: function(res) {		
				// 以键值对的形式返回,可用的api值true,不可用为false
				// 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
			}
		});

		// 转发给微信好友
		wx.onMenuShareAppMessage(title: share.title,
		  desc: share.desc,
		  link: share.link,
		  imgUrl: share.imgUrl,
		  trigger: function (res) {
			// 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回
			// alert('用户触发分享按钮');
		  },
		  success: function (res) {
			// alert('已分享');		
		  },
		  cancel: function (res) {
			// alert('已取消');
		  },
		  fail: function (res) {
		});
		

		// 分享到微信朋友圈
		wx.onMenuShareTimeline(title: share.title,
		  desc: share.desc,
		  link: share.link,
		  imgUrl: share.imgUrl,
		  trigger: function (res) {
			// alert('用户触发分享按钮');
		  },
		  success: function (res) {
			// alert('已分享');		
		  },
		  cancel: function (res) {
			// alert('已取消');
		  },
		  fail: function (res) {
		});


	  	// 分享到QQ好友
		wx.onMenuShareQQ(title: share.title,
		  desc: share.desc,
		  link: share.link,
		  imgUrl: share.imgUrl,
		  trigger: function (res) {
			// alert('用户触发分享按钮');
		  },
		  success: function (res) {
			// alert('已分享');		
		  },
		  cancel: function (res) {
			// alert('已取消');
		  },
		  fail: function (res) {
		  });
	 
	  	// 分享到微博
		wx.onMenuShareWeibo(title: share.title,
		  desc: share.desc,
		  link: share.link,
		  imgUrl: share.imgUrl,
		  trigger: function (res) {
			// alert('用户触发分享按钮');
		  },
		  success: function (res) {
			// alert('已分享');		
		  },
		  cancel: function (res) {
			// alert('已取消');
		  },
		  fail: function (res) {
		});
	 

	  	// 分享到QQ空间
		wx.onMenuShareQZone(title: share.title,
		  desc: share.desc,
		  link: share.link,
		  imgUrl: share.imgUrl,
		  trigger: function (res) {
			//alert('用户触发分享按钮');
		  },
		  success: function (res) {
			// alert('已分享');		
		  },
		  cancel: function (res) {
			// alert('已取消');
		  },
		  fail: function (res) {
		});
		
	});  			
}

weixinshare.php

//微信公众平台配置参数
$APPID = "xxxxxxxxxxxx";
$SECRET = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

//接受前端参数
$pageurl = $_REQUEST['pageurl'];

//2.1 数据库取获取access_token 和 ticket
$access_token = "";
$ticket = "";
$beforetime = date("Y-m-d H:i:s",strtotime("-1 hour"));
$sql = "SELECT id,access_token,ticket,time FROM `weixin_token` where time >'$beforetime' order by id desc limit 1";
$rs = $pdo -> query($sql); 
while( $row = $rs -> fetch() ){ 
	//获取留言,分享,点赞数
	$access_token = $row['access_token'];   
	$ticket = $row['ticket']; 
}

//2.2 判断数据库里是否存在(如果没有)
if( $access_token == "" || $ticket == "" ){
//3.获取access_token
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$APPID."&secret=".$SECRET;
$result = DO_POST( $url );
$result_arr = array();
$result_arr = json_decode($result,true);
$access_token = $result_arr['access_token'];

if(empty($access_token)||$access_token==''||$access_token==null){
	$res = array ('code'=>'0','msg'=>'access_token erro');
	exit( $_GET['callback'].'('.json_encode($res).')');
}

//3.获取ticket
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$access_token&type=jsapi";
$result = DO_POST($url);

$result_arr = array();
$result_arr = json_decode($result,true);
$ticket = $result_arr['ticket'];

//2.3 数据库存入新的值
$sql2 = "INSERT INTO `weixin_token` (`id`, `access_token`, `ticket`, `time`) VALUES (NULL, '$access_token', '$ticket', CURRENT_TIMESTAMP);"; 	
$pdo->exec($sql2);
}

//校验参数
if( empty($ticket) || $ticket == '' || $ticket == null ){
$res = array ('code'=>'0','msg'=>'ticket erro');
exit( $_GET['callback'].'('.json_encode($res).')');
}

//4.进行签名
$jsapi_ticket = $ticket;
$noncestr = md5( uniqid() );	//不能时间戳,要英文数字组合 注意!!!!!
$timestamp = time();

//当前网址
$url = $pageurl;
$sigstr = "jsapi_ticket=$jsapi_ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
$signature = sha1($sigstr);
$res = array ('code'=>'1','appid'=>$APPID,'timestamp'=>$timestamp,'noncestr'=>$noncestr,'signature'=>$signature,'jsapi_ticket'=>$jsapi_ticket,'access_token'=>$access_token );
exit( $_GET['callback'].'('.json_encode($res).')');	

//方法
function DO_POST( $url,$post='',$cookie='',$returnCookie=0 )
{
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
  curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);    //自动301,302跳转;
  curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
  if($post)  {
      curl_setopt($curl, CURLOPT_POST, 1);
      curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  }
  if($cookie) {
      curl_setopt($curl, CURLOPT_COOKIE, $cookie);
  }
  curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
  curl_setopt($curl, CURLOPT_TIMEOUT, 30);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  $data = curl_exec($curl);
  
  if (curl_errno($curl)) {
      return curl_error($curl);
  }

  curl_close($curl);

  if($returnCookie) {
      list($header, $body) = explode("\r\n\r\n", $data, 2);
      preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
      $info['cookie']  = substr($matches[1][0], 1);
      $info['content'] = $body;
      return $info;
  }
  else {
      return $data;
  }
}