javascriptを使用してwx.config内部フィールドを取得し、微信共有を解決

9136 ワード

背景
WeChatが開発を共有するときの一般的な流れは
 <?php
    require_once "jssdk.php";
    $jssdk = new JSSDK("yourAppID", "yourAppSecret");
    $signPackage = $jssdk->GetSignPackage();
?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>    </title>
    </head>
    <body>
    </body>
    <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <script>
        wx.config({
            appId: '<?php echo $signPackage["appId"];?>',
            timestamp: <?php echo $signPackage["timestamp"];?>,
            nonceStr: '<?php echo $signPackage["nonceStr"];?>',
            signature: '<?php echo $signPackage["signature"];?>',
            jsApiList: ['onMenuShareTimeline'
                'onMenuShareAppMessage'
            ]
        });

        wx.ready(function() {
            
            wx.onMenuShareTimeline({
                title: '', //     
                link: '', //     
                imgUrl: '', //     
                success: function() {
                    //               
                },
                cancel: function() {
                    //               
                }
            });

            wx.onMenuShareAppMessage({
                title: '', //     
                desc: '', //     
                link: '', //     
                imgUrl: '', //     
                type: '', //     ,music、video link,     link
                dataUrl: '', //   type music video,        ,    
                success: function() {
                    //               
                },
                cancel: function() {
                    //               
                }
            });

        });
    </script>

    </html>

上はphpファイルですが、このようなコードの大きな欠点は、前後の未分離結合度が高すぎることです.さらに、ハイブリッド書き込みが美しくないことです.だから、PHPとHTMLを分離し、共有機能を実現するには、まず微信のjssdk Apiを呼び出して構成パラメータを取得することです.これはphpバックグラウンド言語で取得しなければなりません.次に、これらのパラメータをwx.configに構成し、wx.configの前に導入します.http://res.wx.qq.com/open/js/jweixin-1.0.0.js それから分かち合う関数を書くことができて、彼らの依存関係はwx.configがjsライブラリとconfig内部のパラメータを必要とするので、分かち合うのはwx.configに依存するので最も重要なのはphpの配置パラメータを分離して単独で取得することができます
ソリューション
構成パラメータを取得したPHPをインタフェースとして書き、jsでajax呼び出しを使用してパラメータを取得してオブジェクトに変換し、コールバック関数でajax取得したパラメータをwx.configに詰める
コード構造及び機能
  • index.htmlページエントリ
  • weixin.phpサーバ側取得構成パラメータ
  • configdata.phpは構成を口実出力
  • に変換する
  • getconfig.js ajaxでconfigdata.phpのデータを取得
  • share.js共有コールバック
  • webpack.config.js webpackプロファイル
  • index.jsパッケージ後最終html呼び出しjsファイル
  • index.html静的ファイル
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>          </title>
    </head>
    <body>
        <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
            <script src="statics/js/index.js"></script>
    </body>
    </html>

    configdata.phpバックグラウンド構成のパラメータを取得urlが共有されているページurlを書くように注意してください.そうしないとinvalid signatureエラーが発生します.
     
    <?php
    class JSSDK {
      private $appId;
      private $appSecret;
    
      public function __construct($appId, $appSecret) {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
      }
    
      public function getSignPackage() {
        $jsapiTicket = $this->getJsApiTicket();
        $url = "http://$_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          ,              
        $data = json_decode(file_get_contents("jsapi_ticket.json"));
        if ($data->expire_time < time()) {
          $accessToken = $this->getAccessToken();
          $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 = "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_URL, $url);
    
        $res = curl_exec($curl);
        curl_close($curl);
    
        return $res;
      }
    }
    
    

    Weixin.php構成パラメータをフォーマット出力
     <?php
    
        require_once "weixin.php";
        $jssdk = new JSSDK(appId, appSecretecret);
        $signPackage = $jssdk->GetSignPackage();
      
        class Config{  
            var $appId;  
            var $timestamp;  
            var $nonceStr;  
            var $signature;  
            var $url;
        }  
          
        $config = new Config();  
          
        $config -> appId = $signPackage["appId"];  
        $config -> timestamp = $signPackage["timestamp"];  
        $config -> nonceStr = $signPackage["nonceStr"];  
        $config -> signature = $signPackage["signature"];
        $config -> url = $signPackage["url"]; 
          
        echo json_encode($config);
    ?>
    
    
    

    getconfig.js ajaxを使用してインタフェースデータを取得する(構成パラメータ)
    var getConfig = function(callback) {
        $.ajax({
            url: "http://www.goxueche.com/api/configdata.php",
            type: "get",
            success: function(data) {
                callback(data);
            }
        })
    }
    
    module.exports = getConfig;

    share.js共有関数
    var getWeixincofig = require("./getconfig.js");
    getWeixincofig(shareweixin);
    
    
    function shareweixin(data) {
    
      var data = JSON.parse(data);
      console.log(data);
    
      window.wx.config({
        debug:true,
        appId: data.appId,
        timestamp: data.timestamp,
        nonceStr: data.nonceStr,
        signature: data.signature,
        jsApiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage']
      });
    
      wxShare();
    }
    
    function wxShare() {
      //  api    
      wx.ready(function() {
        wx.checkJsApi({
          jsApiList: [
            'getNetworkType',
            'previewImage'
          ],
          success: function(res) {
            console.log(JSON.stringify(res));
          }
        });
        //     
        wx.onMenuShareAppMessage({
          title: '   -         ',
          desc: '    ,    !',
          link: 'http://www.goxueche.com',
          imgUrl: 'http://www.goxueche.com/....png'
        });
        
        //      
        wx.onMenuShareTimeline({
          title: '   -         ',
          desc: '    ,    !',
          link: 'http://www.goxueche.com',
          imgUrl: 'http://www.goxueche.com/....png'
        });
    
      });
    }

    webpack.config.js
    var webpack = require('webpack'); 
    module.exports = {   
        entry: {
            index: './share.js',
        },
        output: {
            path: './',
            filename: '[name].js'
        }
    };

    Webpackパッケージ
    共有効果の表示
    リファレンスドキュメント
    http://203.195.235.76/jssdk/http://www.cnblogs.com/txw1958/p/weixin-js-sdk-demo.html