微信分享类

<?php
/**
 * 微信分享相关
 *
 * @since 2017-07-15
 */
use Yaf\Registry;
class Service_WxShare{

    private $appId;
    private $appSecret;

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

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

        // 注意 URL 一定要动态获取,不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        $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 应该全局存储与更新
        $redis = Registry::get('redis');
        $jsapi_ticket = $redis->get('jsapi_ticket');
        $data = json_decode($jsapi_ticket);
        if (!$data) {
            $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['jsapi_ticket'] = $ticket;
                $redis->set('jsapi_ticket',json_encode($data));
                $redis->expire('jsapi_ticket',7000);
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }


        return $ticket;
    }

    private function getAccessToken() {
        // access_token 应该全局存储与更新
        $redis= Registry::get('redis');
        $access_token = $redis->get('access_token');
        $data = json_decode($access_token);
        if (!$data) {
            // 如果是企业号用以下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['access_token'] = $access_token;
                $redis->set('access_token',json_encode($data));
                $redis->expire('access_token',7000);
            }
        } 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;
    }
}

使用  

//微信配置
$config = (new Service_WxShare($appid,$appsecret))->getSignPackage();

JS:

<script type="text/javascript"  src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>

<script>
wx.config({
debug: false,
appId: '{{ js_config.appId }}',
timestamp: '{{ js_config.timestamp }}',
nonceStr: '{{ js_config.nonceStr }}',
signature: '{{ js_config.signature }}',
jsApiList: ['onMenuShareAppMessage',
'onMenuShareTimeline',
'chooseWXPay',
'showOptionMenu',
"updateAppMessageShareData",
"hideMenuItems",
"showMenuItems",
"onMenuShareTimeline",
'onMenuShareAppMessage']
});
wx.ready(function () {
wx.onMenuShareAppMessage({
title: '标题',
desc: '描述',
link: '分享链接',
imgUrl: '图片路径',
success: function () {

}
});
wx.onMenuShareTimeline({
title: '标题',
desc: '描述',
link: '分享链接',
imgUrl: '图片路径',
success: function () {

}
})
});
</script>

  

posted @ 2020-02-12 15:41  TOPHP  阅读(264)  评论(0编辑  收藏  举报