[公众号]微信分享网页显示图片(个人号)

9471次阅读 590人点赞 作者: WuBin 发布时间: 2021-02-19 15:01:07
扫码到手机查看

本文主页介绍如何在微站里面实现分享网页给朋友和朋友圈,显示图片和简介,这么简单的功能是如何实现的。

申请公众号

1、首先在这个页面申请一个公众号申请公众号。(前提需要有一个服务器)

2、特别注意!个人帐号无法微信认证!必须是企业或者个体工商户!

2、公众平台官网登录之后,找到“开发-基本配置”菜单栏。
3、找到“服务器配置”,点修改配置。
Token:自主设置,这个token与公众平台wiki中常提的access_token不是一回事。这个token只用于验证开发者服务器。
url填写:https://www.wubin.work/api/xxx.php(用于验证请求地址), xxx.php参考如下:
<?php
define("TOKEN","注册时候自定义的Token");
function checkSignature()
{
    //从GET参数中读取三个字段的值
    $signature = $_GET["signature"];
    $timestamp = $_GET["timestamp"];
    $nonce = $_GET["nonce"];
    //读取预定义的TOKEN
    $token = TOKEN;
    //对数组进行排序
    $tmpArr = array($token, $timestamp, $nonce);
    sort($tmpArr, SORT_STRING);
    //对三个字段进行sha1运算
    $tmpStr = implode( $tmpArr );
    $tmpStr = sha1( $tmpStr );
    //判断我方计算的结果是否和微信端计算的结果相符
    //这样利用只有微信端和我方了解的token作对比,验证访问是否来自微信官方.
    if( $tmpStr == $signature ){
        return true;
    }else{
        return false;
    }
}

if(checkSignature()){
    echo $_GET["echostr"];
}
else{
    echo 'error';
}

附加逻辑流程图

之后点击,返回值成功的话,会提示成功。官方链接  【微信开发】基本配置怎么填写服务器配置

使用微信的jssdk

先需要在微信公众号后台进行设置:公众号设置-->功能设置-->JS接口安全域名。打开这个页面之后你会看到下面的提示。需要先下载这个文件并上传到指定域名的根目录。

这个文件里面是一个字符串,是用来校验用的。先上传了这个文件,你才能保存成功。之后就可以使用jssdk了(注意需要确保txt文件可以被访问到,服务器不能做TXT文件的禁止访问)。

注意:将下载下来的txt文件放在域名www.wubin.work/mywx/xxx.txt的目录下,之后填写www.wubin.work/mywx即可

添加微信白名单

要申请access_token必须要先将服务器地址以及开发者IP地址添加入白名单

添加好之后,发送的请求才可以接收到回执。(IP地址之间用回车分割!)

获取access_token

首先编写两个PHP文件

1、jssdk.class.php(功能正常 但非完全版 根据情况进行修改)

<?php
class JSSDK {
    // https://www.cnblogs.com/LXJ416/p/6133536.html
    //微信公众号的id
    private $appId;
    //微信公众号密码
    private $appSecret;
    // 存储的access_token.json的文件名
    private $accessTokenFile = 'access_token.json';
    // 存储的jsapi_ticket.json的文件名
    private $jdkTicketFile = 'jsapi_ticket.json';
    // 当前的时间戳
    private $nowTime;
    // 返回的结果是一个数组
    private $result;

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

    // 获取微信的配置信息
    public function getSignPackage($url)
    {
        $jsapiTicket = $this->getJsApiTicket();

        // $url = "https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
        $timestamp = $this->nowTime;
        $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,
            // 加密前的字符串不返回
            // "rawSting" => $string
        );

        return $signPackage;
    }

    // 请求微信的jdk,jsapi_ticket 应该全局存储与更新
    private function getJsApiTicket() {
        $data = $this->getJsonFile($this->jdkTicketFile);

        if (!$data || $data['expire_time'] < $this->nowTime) {
          // 获取access_token
          $accessToken = $this->getAccessToken();
          $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=";
          $url = $url . $accessToken;
          $res = json_decode($this->httpGet($url), true);
          $ticket = $res['ticket'];
          if ($ticket) {
            $data = array(
                'expire_time' => $this->nowTime + $res['expires_in'],
                'jsapi_ticket' => $ticket
            );
            !$this->saveFile($this->jdkTicketFile, $data) && $this->showError();
          }
        } else {
          $ticket = $data['jsapi_ticket'];
        }
        return $ticket;
    }

    // 请求微信接口的access_token,access_token 应该全局存储与更新
    private function getAccessToken() {
        $data = $this->getJsonFile($this->accessTokenFile);

        if (!$data || $data['expire_time'] < $this->nowTime) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
            $url = $url."{$this->appId}&secret={$this->appSecret}";
            // 将获取到token-JSON字符串转化为数组
            $res = json_decode($this->httpGet($url), true);
            // 获取返回的access_token
            $access_token = $res['access_token'];
            if ($access_token) {
                // $data是一个数组
                $data = array(
                    // 过期时间 = 当前时间 + 返回的有效期
                    'expire_time' => $this->nowTime + $res['expires_in'],
                    'access_token' => $access_token
                );
                !$this->saveFile($this->accessTokenFile, $data) && $this->showError();
            }
        } else {
          $access_token = $data['access_token'];
        }
        return $access_token;
    }

    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;
    }

    // 使用curl请求地址
    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_URL, $url);
        // 请求的是https需要加上下面2句
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $res = curl_exec($curl);
        if (!$res) {
            echo 'Curl error: ' . curl_error($curl);
            exit();
        }
        curl_close($curl);
        return $res;
    }

    // 打开JSON文件
    private function getJsonFile($filename)
    {
        // 如果文件不存在 抑制报错
        $resource = @file_get_contents($filename);
        return $resource ? json_decode($resource, true) : false;
    }

    /**
     * [saveFile 保存文件]
     * @DateTime 2021-03-04T14:07:01+0800
     * @param    [string]                 $filename [文件名]
     * @param    [array]                  $data     [将要写入文件的数组]
     * @return   [boolean]                          [文件写入成功或者失败]
     */
    private function saveFile($filename, $data)
    {
        $fp = fopen($filename, 'w');
        $fwrite_res = fwrite($fp, json_encode($data));
        fclose($fp);
        return $fwrite_res ? true : false;
    }

    private function showError($msg = '')
    {
        $this->result = array(
            'error' => true,
            'msg' => $msg
        );
        exit($this->result);
    }
}

2、同级目录下,再新建wx_share.php(仅基本功能,具体需要根据情况修改)

<?php
header('content-type:application/json;charset=utf8');
require('jssdk.class.php');

$appId = 'xxxxxxxxxxx';
$appSecret = 'xxxxxxxxxxxxxxxxxxx';

// 要分享的页面的链接
$url = isset($_GET['url']) ? $_GET['url'] : false;
if (!$url) {
    exit('请输入url');
}

$jssdk = new JSSDK($appId, $appSecret);
$signPackage = $jssdk->getSignPackage($url);

echo json_encode($signPackage);

至此,访问 https://www.wubin.work/mychat/wx_share.php 可以拿到返回的json数据

前台页面进行获取

1、HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>微信分享测试</title>
    <meta name="description" content="分享希望成功!!">
</head>
<body>
    <script src="https://wechatfe.github.io/vconsole/lib/vconsole.min.js?v=3.2.0"></script>
    <script type="text/javascript">
        var vConsole = new VConsole();
        var t_pic = 'https://www.wubin.work/statics/userinfo/.....png';
    </script>
    <script src="https://vip.qdxin.cn/navmenu/js/jxinq111.js"></script>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <script src="https://www.wubin.work/mychat/js/wx_share_jq.js"></script>
</body>
</html>

2、mychat/js/wx_share_jq.js

var description = document.getElementsByName("description");
var t_summary = (description.length > 0) ? description[0].content.substr(0, 120) : "";

var t_url = window.location.href.split('#')[0];

var t_title = document.title ? document.title : 'wubin.work博客空间 | 一介武夫';
// console.log(typeof t_pic);
var t_pic = (typeof t_pic == 'undefined' || t_pic == '') ? 'https://...default.jpg' : t_pic;

var wxShareData = {
    title: t_title,
    desc: t_summary,
    link: t_url,
    imgUrl: t_pic,
    success: function() {
        alert('aa');
    }
};

$.ajax({
    type: 'GET',
    url: 'https://www.wubin.work/mychat/wx_share.php',
    data: { url: t_url },
    error: function(e) {
        console.log('has error!');
        return false;
    },
    success: function(json) {
        // console.log(json);
         var json2 = { 
            debug: true,
            jsApiList: [
                'checkJsApi','onMenuShareTimeline','onMenuShareAppMessage',
                'onMenuShareQQ','onMenuShareWeibo','updateAppMessageShareData',
                'updateTimelineShareData','previewImage','chooseImage','openLocation',
                'getLocation','scanQRCode','hideMenuItems','showMenuItems','closeWindow'
                ] 
        };
         var wxcfg = $.extend({}, json, json2);
         console.log(wxcfg);
         wx.config(wxcfg);
    }
});

 wx.ready(function(){
    wx.checkJsApi({
      jsApiList: ['updateAppMessageShareData'],
      success: function(res) {
        // 个人帐号没有权限
        wx.onMenuShareAppMessage(wxShareData);
        wx.onMenuShareTimeline(wxShareData);
        wx.onMenuShareQQ(wxShareData);
        wx.onMenuShareWeibo(wxShareData);
      }
    });
    if( typeof wx.updateAppMessageShareData == 'function' ) {
        wx.updateAppMessageShareData(wxShareData);
        wx.updateTimelineShareData(wxShareData);
    }
});

至此 个人主体帐号的配置就结束了,可以在微信上访问,但是提示updateAppMessageShareData: permission denied 代表个人号没有权限,无法通过微信认证,需要使用个体工商户或者企业。

相关资料

点赞 支持一下 觉得不错?客官您就稍微鼓励一下吧!
关键词:微信分享图
推荐阅读
  • uniapp实现被浏览器唤起的功能

    当用户打开h5链接时候,点击打开app若用户在已经安装过app的情况下直接打开app,若未安装过跳到应用市场下载安装这个功能在实现上主要分为两种场景,从普通浏览器唤醒以及从微信唤醒。

    8757次阅读 562人点赞 发布时间: 2022-12-14 16:34:53 立即查看
  • Vue

    盘点Vue2和Vue3的10种组件通信方式

    Vue中组件通信方式有很多,其中Vue2和Vue3实现起来也会有很多差异;本文将通过选项式API组合式API以及setup三种不同实现方式全面介绍Vue2和Vue3的组件通信方式。

    3674次阅读 274人点赞 发布时间: 2022-08-19 09:40:16 立即查看
  • JS

    几个高级前端常用的API

    推荐4个前端开发中常用的高端API,分别是MutationObserver、IntersectionObserver、getComputedstyle、getBoundingClientRect、requ...

    13775次阅读 888人点赞 发布时间: 2021-11-11 09:39:54 立即查看
  • PHP

    【正则】一些常用的正则表达式总结

    在日常开发中,正则表达式是非常有用的,正则表达式在每个语言中都是可以使用的,他就跟JSON一样,是通用的。了解一些常用的正则表达式,能大大提高你的工作效率。

    12532次阅读 422人点赞 发布时间: 2021-10-09 15:58:58 立即查看
  • 【中文】免费可商用字体下载与考证

    65款免费、可商用、无任何限制中文字体打包下载,这些字体都是经过长期验证,经得住市场考验的,让您规避被无良厂商起诉的风险。

    11032次阅读 881人点赞 发布时间: 2021-07-05 15:28:45 立即查看
  • Vue

    Vue3开发一个v-loading的自定义指令

    在vue3中实现一个自定义的指令,有助于我们简化开发,简化复用,通过一个指令的调用即可实现一些可高度复用的交互。

    15139次阅读 1207人点赞 发布时间: 2021-07-02 15:58:35 立即查看
  • JS

    关于手机上滚动穿透问题的解决

    当页面出现浮层的时候,滑动浮层的内容,正常情况下预期应该是浮层下边的内容不会滚动;然而事实并非如此。在PC上使用css即可解决,但是在手机端,情况就变的比较复杂,就需要禁止触摸事件才可以。

    14612次阅读 1191人点赞 发布时间: 2021-05-31 09:25:50 立即查看
  • Vue

    Vue+html2canvas截图空白的问题

    在使用vue做信网单页专题时,有海报生成的功能,这里推荐2个插件:一个是html2canvas,构造好DOM然后转canvas进行截图;另外使用vue-canvas-poster(这个截止到2021年3月...

    28356次阅读 2230人点赞 发布时间: 2021-03-02 09:04:51 立即查看
  • Vue

    vue-router4过度动画无效解决方案

    在初次使用vue3+vue-router4时候,先后遇到了过度动画transition进入和退出分别无效的情况,搜遍百度没没找到合适解决方法,包括vue-route4有一些API都进行了变化,以前的一些操...

    24476次阅读 1885人点赞 发布时间: 2021-02-23 13:37:20 立即查看
交流 收藏 目录