H5链接分享给微信好友,显示标题、描述、缩略图

效果展示

image.png

1.公众号设置

1.1公众号需要经过认证,具有分享接口功能
image.png

1.2填写正确的域名(域名需要经过备案)

将文件MP_verify_X2HaCEnsvmqinQ55.txt(点击下载)上传至填写域名或路径指向的web服务器(或虚拟主机)的目录

image.png
1.3 保存好AppID、AppSecret、设置好ip白名单(非常重要)
image.png

2.php代码(需要有php环境下,放到域名目录下)

2.1展示下目录结构-wxDemo
image.png
image.png

2.2index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta name="wap-font-scale" content="no">
    <meta name="format-detection" content="telephone=no" />
</head>

<body>
	wxDome
	<script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
	<script>
		document.write("<script src='http://xxxxx.cn/wxDemo/accessToken/signPackage.php?originUrl=" + window.location.href + "' type='text/javascript'><\/script>");
	</script>
	<script>
		
		/*填写路径是公众号上的安全域名*/
		var baseUrl = "http://xxxxx.cn/wxDemo/index.html";
		var wxData = {
			"imgUrl" : 'http://xxxxx.cn/wxDemo/wx300.jpg',
			"link"   : baseUrl,
			"title"  : 'wxDemo-标题',
			"desc"   : 'wxDemo-描述信息!'
		};
		wx.config({
			debug: false,
			appId: signPackage.appId,
			timestamp: parseInt(signPackage.timestamp),
			nonceStr: signPackage.nonceStr,
			signature: signPackage.signature,
			jsApiList: [
                'onMenuShareAppMessage',
                'onMenuShareTimeline',
				'updateAppMessageShareData',
				'updateTimelineShareData'
			]
		});
		wx.ready(function () {	
          wx.onMenuShareAppMessage({
				title: wxData.title,
				desc: wxData.desc,
				link: wxData.link,
				imgUrl: wxData.imgUrl,
				type: 'link',
				dataUrl: '',
				success: function () {
				}
			});
			wx.onMenuShareTimeline({
				title: wxData.title,
				desc: wxData.desc,
				link: wxData.link,
				imgUrl: wxData.imgUrl,
				type: 'link',
				dataUrl: '',
				success: function () {
				}
			});					 
			wx.updateAppMessageShareData({
				title: wxData.title,
				desc: wxData.desc,
				link: wxData.link,
				imgUrl: wxData.imgUrl,
				type: 'link',
				dataUrl: '',
				success: function () {
				}
			});
			wx.updateTimelineShareData({
				title: wxData.title,
				desc: wxData.desc,
				link: wxData.link,
				imgUrl: wxData.imgUrl,
				type: 'link',
				dataUrl: '',
				success: function () {
				}
			});
		});

	</script>

</body>

</html>

2.3 signPackage.php

<?php
	// 实现微信分享功能
	// 通过script标签引入该文件,通过url参数传递原网页的完整url
	error_reporting(0);
	$queryString = $_SERVER["QUERY_STRING"];// 获取PHP后的网址参数,格式为:originUrl=...
	$url = substr($queryString,10);	// 截取原网页的完整url
	
	require_once "jssdk.php";
	$jssdk = new JSSDK("xxxxxx", "xxxxxx", $url);// 改为自己公众号的AppID、AppSecret
	$signPackage = $jssdk->GetSignPackage();
	echo "var signPackage=";
 	die(json_encode($signPackage));// 返回微信分享所需参数
 ?>

2.4 jssdk.php

<?php
class JSSDK {
  private $appId;
  private $appSecret;
  private $url;

  public function __construct($appId, $appSecret, $url) {
    $this->appId = $appId;
    $this->appSecret = $appSecret;
    $this->url = $url;
  }

  public function getSignPackage() {
    $jsapiTicket = $this->getJsApiTicket();

    // 注意 URL 一定要动态获取,不能 hardcode.
	$url = $this->url;

    $timestamp = time();
    $nonceStr = $this->createNonceStr();

    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$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("jsapi_ticket.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));
      $ticket = $res->ticket;
      if ($ticket) {
        $data->expire_time = time() + 7000;
        $data->jsapi_ticket = $ticket;
        $fp = fopen("jsapi_ticket.php", "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("access_token.php"));
    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($this->httpGet($url));
      $access_token = $res->access_token;
      if ($access_token) {
        $data->expire_time = time() + 7000;
        $data->access_token = $access_token;
        $fp = fopen("access_token.php", "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;
  }
}

2.5 jsapi_ticket.php

{"expire_time":1588134786,"jsapi_ticket":"kgt8ON7yVITDhtdwci0qeUFZYyjmx63aUn0jr944H7-QrUdILt6kff8cY3ujO0GNYP4dewtFw5od1LVZl2u9-g"}

2.6 access_token.php

获取access_token expires_in值为7200表示成功
将获取到的access_token写到access_token.php里

image.png

image.png

{"expire_time":1588134785,"access_token":"32_4MgWOCPonWbReM49JBL7VNN3RFLDFF6-7Vx04S3Pv3lIglbAvr9RNrDT14F5jKXbtNdPBee8C9QJuDql2oI5dqnn1JzTLt2a_3G3-u1DwzRmW47AHU22P1v73goT16-CKRxAOcc6wHtPwq1ZJGPaAJAOLU"}

3. 服务器

我的服务器是远程服务器(window serve 2012 r2)
服务器一定要保证可以完全写入文件(这就是我在那坑待了很久的原因)

image.png

文件下载地址

https://github.com/bc-ax/wxDemo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值