美文网首页前端框架
linux+vue+php+nginx微信分享网页链接带图标和摘

linux+vue+php+nginx微信分享网页链接带图标和摘

作者: 程序猿TODO | 来源:发表于2021-07-07 21:09 被阅读0次

一、Linux安装php7.3以及相关环境配置

安装相关环境

yum install -y gcc gcc-c++  make zlib zlib-devel pcre pcre-devel  libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel openssl openssl-devel openldap openldap-devel nss_ldap openldap-clients openldap-servers

php官网,找到https://www.php.net/downloads.php下载地址,找到php-7.3.24.tar.gz,右键复制地址,然后用wget下载(下载有点慢,可以用浏览器下载,然后再传到服务器上解压)。

wget https://www.php.net/distributions/php-7.3.24.tar.gz

解压:

tar -xzvf php-7.3.24.tar.gz
cd php-7.3.24

php参数配置:

./configure \
--prefix=/usr/local/php \
--exec-prefix=/usr/local/php \
--bindir=/usr/local/php/bin \
--sbindir=/usr/local/php/sbin \
--includedir=/usr/local/php/include \
--libdir=/usr/local/php/lib/php \
--mandir=/usr/local/php/php/man \
--with-config-file-path=/usr/local/php/etc \
--with-openssl \
--enable-mbstring \
--with-pdo-mysql \
--enable-fpm \
--with-curl

编译:

make && make install

在之前编译的源码包中,找到 php.ini-production,复制到/usr/local/php/etc下,并改名为php.ini:

cp php.ini-production /usr/local/php/etc/php.ini

将php源码编译目录下的 sapi/fpm/init.d.php-fpm 文件拷贝到系统配置 /etc/init.d 目录下并重命名为 php-fpm

[root@localhost php-7.3.24]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm 
[root@localhost php-7.3.24]# chmod +x /etc/init.d/php-fpm

添加 php-fpm 配置文件
将php安装目录下的 /usr/local/php/etc/php-fpm.conf.default 文件拷贝同目录下并重命名为 php-fpm.conf

[root@localhost php-7.3.24]# cp /usr/local/php/etc/php-fpm.conf.default /usr/local/php/etc/php-fpm.conf 

添加 www.conf 配置文件
将php安装目录下的 /usr/local/php/etc/php-fpm.d/www.conf.default 文件拷贝同目录下并重命名为 www.conf

[root@localhost php-7.3.24]# cp /usr/local/php/etc/php-fpm.d/www.conf.default /usr/local/php/etc/php-fpm.d/www.conf

添加php安装目录到系统环境变量
创建并打开文件php.sh

[root@localhost php-7.3.24]# vim /etc/profile.d/php.sh 
添加:export PATH=$PATH:/usr/local/php/bin/:/usr/local/php/sbin/ 
使用source立即生效刚刚添加的php环境变量 
[root@localhost php-7.3.24]# source /etc/profile.d/php.sh 

启动php

[root@localhost php-7.3.24]# service php-fpm start
Starting php-fpm  done

查看端口启动:php的fastcgi端口9000

[root@localhost php-7.3.24]# netstat -tnl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 127.0.0.1:9000          0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN     
tcp6       0      0 :::22                   :::*                    LISTEN

设置php开机启动

修改系统配置目录下的 php-fpm 文件可执行权限 
[root@localhost php-7.3.24]# chmod +x /etc/init.d/php-fpm
> 将系统配置目录下的 `php-fpm` 添加到 `系统服务`
[root@localhost php-7.3.24]# chkconfig --add php-fpm
 
> 设置 `php-fpm` `系统服务` 为开机启动
[root@localhost php-7.3.24]# chkconfig php-fpm on

重启电脑后:

[root@localhost ~]# netstat -tnl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 127.0.0.1:9000          0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN     
tcp6       0      0 :::22                   :::*                    LISTEN     
[root@localhost ~]# php -v
PHP 7.3.24 (cli) (built: Nov 13 2020 10:07:15) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.24, Copyright (c) 1998-2018 Zend Technologies

二、公众号的配置以及引入文件

首先你必须有一个认证后的微信公众号(或者点开发者工具-公众平台测试账号-扫码申请一个有分享接口权限的测试号),然后把你的网站ip地址输入公众号ip白名单


步骤一:验证文件并且绑定域名

先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”,并且把下载的xxxx.txt文件放至域名根目录下,下面说的jssdk.php我们也是放在域名根目录下

步骤二:引入JS文件

<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script>
window.onload = function (){
    var url = (window.location.href).split('#')[0]
    $.ajax({
        type : "get",
        //我这里是放在域名根目录下,如果在域名根目录下新建文件夹,则url:"http://自己的域名/文件夹名/jssdk.php?url="+url
        url : "http://自己的域名/jssdk.php?url="+encodeURIComponent(url),
        dataType : "jsonp",
        jsonp: "callback",
        jsonpCallback:"success_jsonpCallback",
        success : function(data){
            wx.config({
                debug: false,
                appId: data.appId,
                timestamp: data.timestamp,
                nonceStr: data.nonceStr,
                signature: data.signature,
                jsApiList: [
                    'onMenuShareTimeline',//
                    'onMenuShareAppMessage',
                    'onMenuShareQQ',
                    'onMenuShareWeibo',
                    'onMenuShareQZone'
                ]
            });
        },
        error:function(data){
            alert("连接失败!");
        }
    });
    wx.ready(function () {
        var shareData = {
            title: '这是是分享标题',
            desc: '这是是摘要',
            link: url,
            imgUrl: '域名根目录下的小图标文件的地址或者oss服务器下小图标文件的地址(能在浏览器上访问到图片就ok)'
        };
        wx.onMenuShareAppMessage(shareData);//分享给好友
        wx.onMenuShareTimeline(shareData);//分享到朋友圈
        wx.onMenuShareQQ(shareData);//分享给手机QQ
        wx.onMenuShareWeibo(shareData);//分享腾讯微博
        wx.onMenuShareQZone(shareData);//分享到QQ空间
    });
    wx.error(function (res) {
        //alert(res.errMsg);//错误提示
    });
}
</script>

url : "http://自己的域名/jssdk.php?url="+url,

这个域名不必须是目前的域名,如果你有多个域名,可以引用同一个jssdk.php文件。

步骤三:创建PHP文件 jssdk.php(对于jssdk.php文件我们可以直接放域名根目录,也可新建文件夹,用文件的话注意文件路径!)

<?php
 $url = $_GET['url'];
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();
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        // $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $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.json"));
        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.json", "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.json"));
        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.json", "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, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
}
 
$jssdk = new JSSDK("wx********************a", "*************************",$url);
$signPackage = $jssdk->GetSignPackage();
$tmp=json_encode(array ('appId'=>$signPackage["appId"],'timestamp'=>$signPackage["timestamp"],'nonceStr'=>$signPackage["nonceStr"],'signature'=>$signPackage["signature"],'url'=>$signPackage["url"]));
$callback = $_GET['callback'];
echo $callback.'('.$tmp.')';
exit;
?>

只要改一下这一行为你自己的:

$jssdk = new JSSDK("wx********************", "*************************",$url);

最后,别忘了存放这个PHP的文件夹权限为可写(如果放在域名根目录则将access_token.json、jsapi_ticket.json、MP_verify_xxxxxxxx.txt权限为可写)。

这里我用的是

chmod -R 777 access_token.json
chmod -R 777 jsapi_ticket.json
chmod -R 777 MP_verify_xxxxxxxx.txt

(PS:微信对分享内容大小有限制,如果自定义图标文件过大,不然会导致描述不显示,图片最好控制在30Kb左右,图片比例5:4)

三、nginx配置-php文件的解析

server {
        listen 80;
        listen 443 ssl;
        server_name xxxxx; #域名
        ssl_certificate xxx/xxxxxxxxxx.pem;
        ssl_certificate_key xxx/xxxxxxxxxx.key;
        root /xxx/xxx;
        location / {
            index index.html index.htl index.php;
            try_files $uri $uri/ /index.php?$args;
        }
        location ~ \.php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /xxx/xxx$fastcgi_script_name;#这里的/xxx/xxx写root路径
            include fastcgi_params;
        }
        location ^~ /assets/ {
            gzip_static on;
            expires max;
            add_header Cache-Control public;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
}

四、遇到的问题

(1) 报500

报500

php环境引起问题,没有在php参数配置的时候加配置--with-curl

(2)jssdk config:invalid url domain

切记一定要在自己申请的测试公众号添加安全域名

(3)调用ACCESS_TOKEN失败,直接在容器中CRUL这个接口会有41002的错误

curl 把url用双引号包住就可以了

(3)jssdk config:invalid signature

1.确认签名算法正确
微信 JS 接口签名校验工具
微信公众平台接口调试工具
与.php打印出来的日志相比较,确认signature是否一致,切记将下图中的url中的反斜杠给去掉,不然总会得出签名算法不正确,切记切记!!!


5.确保一定缓存access_token和jsapi_ticket
域名根目录下创建access_token.json、jsapi_ticket.json,并且设置权限:
chmod -R 777 access_token.json
chmod -R 777 jsapi_ticket.json

相关文章

网友评论

    本文标题:linux+vue+php+nginx微信分享网页链接带图标和摘

    本文链接:https://www.haomeiwen.com/subject/tvjoultx.html