微信-JSSDK网页调用-(微信扫一扫)

网页调用微信扫一扫接口

1、准备工作:

   1.1微信浏览器

      1.2微信APPID,nonceStr

2、使用方式快速预览

      调用扫一扫微信接口。

       1需要获取access_token

       2获取 $jsapi_ticket

       3加密

       4返回前端

        5前端Js实现接口

3、错误,坑点提示

      1、获取的access_token 一定要加缓存,原因是有次数限制,3000

      2、组装的url 地址一定要全。 http,https一定 一定不能少

      3、Js安全接口一定要配置到域名地址。

 

二、代码实现

JSSDK类,提供大家参考,建议大家写成一个完整的类包,方便管理,和运用

<?php
/**
 * Created by PhpStorm.
 * User: JOJO
 * Date: 2019/8/4
 * Time: 14:53
 */

class JSSDK
{
    public $appId;
    private $appSecret;

    /**
     * @name         初始化参数
     * @author       JOJO         
     * @copyright    
     */
    public function __construct($appId, $appSecret)
    {

        $this->appId = $appId;

        $this->appSecret = $appSecret;
    }




    /**
     * @name         获取config接口注入权限验证配置
     * @author       JOJO         
     * @copyright    
     */
    public function getWxConfig()
    {

        $jsapiTicket = $this->getJsapiTicket();
        # - 获取调用页面的url
        $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 码升序排序
        # - 亦可把参数以数组存值,ksort() - 以升序对关联数组进行排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        # - 页面所需注入参数
        $WxConfig = array(
            "appId" => $this->appId,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string
        );

        return $WxConfig;
    }
    
    public function getJsapiTicket()
    {
        if (\Yii::$app->cache->exists('jsapi_ticket')) {
            return \Yii::$app->cache->get('jsapi_ticket');
        }
        $access_token = $this->getAccessToken();
        if ($access_token == false) {
            return false;
        }
        $url = sprintf("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi", $access_token);
        $res = wx_tools::getCurl($url);
        $res = json_decode($res, true);
        if (isset($res['errcode']) && $res['errcode'] != 0) {
            return false;
        }
        //这里应该把access_token缓存起来,有效期是7200s
        \Yii::$app->cache->set('jsapi_ticket', $res['ticket'], 7000);
        return $res['ticket'];
    }

    
    public function getAccessToken()
    {
        if (\Yii::$app->cache->exists('access_token')) {
            return \Yii::$app->cache->get('access_token');
        }
        $AppID =$this->appId;//AppID(应用ID)
        $AppSecret = this->appSecret;//AppSecret(应用密钥)
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $AppID . '&secret=' . $AppSecret;
        $res = $this->getCurl($url);
        $res = json_decode($res, true);
        if (isset($res['errcode']) && $res['errcode'] != 0) {
            return false;
        }
        \Yii::$app->cache->set('access_token', $res['access_token'], 7000);
        return $res['access_token'];
    }
    
    /**
     * CURL GET 请求
     * @param $url
     * @return bool|mixed
     */
    public  function getCurl($url)
    {
        $curl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $content = curl_exec($curl);
        $status = curl_getinfo($curl);

        if (intval($status["http_code"]) == 200) {
            curl_close($curl);
            return $content;
        } else {
            $error = curl_errno($curl);
            curl_close($curl);
            file_put_contents('../web/logs/notify/error' . date('YmdHi') . '.txt', $error);

            return false;
        }
    }
    
    /**
     * @name         产生随机字符串
     * @author       JOJO         
     * @copyright    
     */
    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;
    }
}

 

 

  1、controller

$app_id = 'wx4868b98f52c67445';
$app_secret = '016c26ce85e14d19dac305fa1ba05c91';
$obj = new JSSDK($app_id, $app_secret);
$signPackage = $obj->getWxConfig();

2.view

<?php
$web = \yii\helpers\Url::base();
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>ttt</title>

    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">


    <!--通用js-->
    <script src="<?= $web ?>/js/jquery-2.1.4.js"></script>
    <script src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js" charset="utf-8"></script>

</head>
<body>
<div style="display: block">
    <a  id="saoyisao">扫一扫</a>

</div>
<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 都要加到这个列表中
            "scanQRCode"
        ]
    });


    wx.ready(function () {
        // 在这里调用 API
        $(document).on("click", "a", function () {
            debugger;
            wx.scanQRCode({
                needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
                scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码,默认二者都有
                success: function (res) {
                }
            });

        })
    });
</script>
</body>
</html>

  

 

posted @ 2019-08-04 21:43  鲜花满月楼  阅读(485)  评论(0编辑  收藏  举报