h5分享微信,显示缩略图,标题,简介 cc趣味屋

h5分享微信,显示缩略图,标题,简介
发表于:2020-09-19 分类:技术 评论:4 阅读:3560

1.首先必须的是一个认证的订阅号/服务号,非认证的个人账号没有分享接口权限.需要添加调用白名单IP(设置-安全中心)跟域名(公众号设置-功能设置)

 

2.页面需要引入:

<script src="https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script>

 

3.前端html代码

 

var  url=location.href;
    $.ajax({
        type : "get",  //get post都行
        url : "/port/wx/wxapi", //接口地址
        dataType : "json", 
        data:{
            url:url   //当前页面url
        },
        success : function(data){
            wx.config({
                debug: false,  //调试开关
                appId: data.appId, //公众号的appId
                timestamp: data.timestamp, // 时间戳
                nonceStr: data.nonceStr,  //随机字符串
                signature: data.signature,  //签名 后面PHP会讲到
                jsApiList: [                //js接口列表
                    'updateAppMessageShareData',
                    'updateTimelineShareData'
                ]
            });
        },
        error:function(data){
            console.log("连接失败!");
        }
    })
    wx.ready(function () {
        var shareData = {
            title: '分享标题'
            desc: '分享描述',
            link: url, //分享落地页地址,注意,只能填写公众号安全域名地址
            imgUrl: imgUrl  //缩略图
        };
        wx.updateAppMessageShareData(shareData); //分享给好友
        wx.updateTimelineShareData(shareData);    //分享到朋友圈
    });

 

4.后端PHP代码(thinkphp5)

public function wxapi(){  //前端调用获取配置信息函数
    $data = request()->param();
    $url=isset($data['url'])?$data['url']:'';  //参数url
    $signPackage = $this->GetSignPackage($url);  //获取配置信息
    $data=[
        'appId'=>$signPackage['appId'],  //APPID
        'timestamp'=>$signPackage["timestamp"],  //时间搓
        'nonceStr'=>$signPackage["nonceStr"],    //随机16位字符串
        'signature'=>$signPackage["signature"],    //签名
        'url'=>$signPackage["url"]    //页面url
    ];
    echo json_encode($data);
}

public function getSignPackage($url) {   //总配置函数
    $appId='****'; //微信公众号ID
    $jsapiTicket = $this->getJsApiTicket();
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";//拼接域名前缀(不带的情况)
    $timestamp = time();
    $nonceStr = $this->createNonceStr();    //获取16位随机字符串
    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url"; //加密前的顺序
    $signature = sha1($string); //sha1加密
    $signPackage = array(
        "appId"     => $appId,
        "nonceStr"  => $nonceStr,
        "timestamp" => $timestamp,
        "url"       => $url,
        "signature" => $signature,
        "rawString" => $string
    );
    return $signPackage;
}

public function createNonceStr($length = 16) {  //返回16位随机字符串
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

public function getJsApiTicket() {  //获取jsapi_ticket
    // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
    $data = json_decode(file_get_contents("jsapi_ticket.json"));  //获取jsapi_ticket.json文件的数据
    if ($data->expire_time < time()) {   //对比文件中的expire_time有效时间和当前时间 如果过期则重新请求获取
        $accessToken =$this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
        $res = json_decode($this->http_request($url));
        $ticket = $res->ticket;
        if ($ticket) {
            $data->expire_time = time() + 7000;  //有效时间
            $data->jsapi_ticket = $ticket;  //ticket
            $fp = fopen("jsapi_ticket.json", "w");
            fwrite($fp, json_encode($data)); //写入文件
            fclose($fp);
        }
    } else {
        $ticket = $data->jsapi_ticket; //未过期则直接拿来使用
    }
    return $ticket;
}


public function getAccessToken() {  //获取token 跟上面函数注释一样,这里就不写了
    $appId='****'; //公众号appId
    $appSecret='****';  //公众号appSecret
    // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
    $data = json_decode(file_get_contents("access_token.json"));
    if ($data->expire_time < time()) {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
        $res = json_decode($this->http_request($url));
        $access_token = $res->access_token;
        if ($access_token) {
            $data->expire_time = time() + 7000;
            $data->access_token = $access_token;
            $fp = fopen("access_token.json", "w");
            fwrite($fp, json_encode($data));
            fclose($fp);
        }
    } else {
        $access_token = $data->access_token;
    }
    return $access_token;
}

//cur请求函数
function http_request($url, $data = null){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    if (!empty($data)) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}
评论列表
219.140.115.* 2020-09-27
180.167.63.* 2020-10-10
<script>alert("hello world")</script>
180.167.63.* 2020-10-10
14.114.179.* 2021-03-10
1