Yii2下使用微信分享JSDK

2019-11-07 10:24:14 浏览数 (1)

后端签名

代码语言:php复制
public function getToken()
    {
        //获取access_token
        $app = Yii::$app->wechat->getApp();
        $appId = $app->config['app_id'];
        $appSecret = $app->config['secret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$url); //要访问的地址
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//跳过证书验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        $data = json_decode(curl_exec($ch));
        $token = $data->access_token;
        //设置session
        $shareInfo = ['access_token' => $token,'expire_time' => time()   7200];
        Yii::$app->session->set('share',$shareInfo);
    }

    //获取jsapi_ticket
    public function getjsapi_ticket(){
        $token = Yii::$app->session->get('share');
        $access_token = $token['access_token'];
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token={$access_token}";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
        $data = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($data,true);
        return $data['ticket'];
    }

    //默认生成16位随机数
    public 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;
    }

    //获取要排序的signature相关代码
    public function getSignPackage() {
        $jsapiTicket = $this->getjsapi_ticket();
        $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);
        $app = Yii::$app->wechat->getApp();
        $signPackage = array(
            "appId"     => $app->config['app_id'],
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

前端使用

代码语言:html复制
<!doctype html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>微信分享</title>
	</head>
	 <script src="http://res2.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
	 <script>
			 wx.config({
            debug: false,
            appId: '<?php echo $signPackage["appId"];?>',
            timestamp: <?php echo $signPackage["timestamp"];?>,
            nonceStr: '<?php echo $signPackage["nonceStr"];?>',
            signature: '<?php echo $signPackage["signature"];?>',
            jsApiList: [
                //要使用的API加到这里
                'onMenuShareTimeline',
                'onMenuShareAppMessage'
            ]
        });
        wx.ready(function () {
            //分享给朋友
            wx.onMenuShareAppMessage({
                title: "标题", // 分享标题
                desc: "描述", // 分享描述
                link: "链接", // 分享链接
                imgUrl: "缩略图", // 分享图标
                success: function () {
                    alert('分享成功');
                    // 用户确认分享后执行的回调函数
                },
                cancel: function () {
                    alert('分享失败');
                    // 用户取消分享后执行的回调函数
                }
            });
        });
	</script>
	<body>
代码语言:javascript复制
如遇签名相关问题请检查自己的URL是否一致

0 人点赞