首页 > 代码库 > 公众号js-sdk简

公众号js-sdk简

后台代码

jssdk.PHP——因sae的不可写环境,故需要将accesstoken和JsApiTicket存入数据库。 
数据库字段:id(int 3),accesstoken(string 255),lasttime(int 10)

<?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 一定要动态获取,不能 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() {
        $accessToken = $this -> getAccesstoken();
        $lastAT = M(‘accesstoken‘)->find(2);//1:token;2:ticket
        if(!$lastAT){
            M(‘accesstoken‘) -> add(array(‘id‘=>2,‘accesstoken‘=>‘null‘,‘lasttime‘=>0));
            $lastAT[‘lasttime‘] = 0;
        }
        $ticket = $lastAT[‘accesstoken‘];
        $now = NOW_TIME;
        $timecha = $now - $lastAT[‘lasttime‘];
        if($timecha >= 7200){
//          $url = ‘https://api.weixin.qq.com/cgi-bin/ticket/getticket?‘ . http_build_query ( $param );
//          $content = file_get_contents ( $url );
//          $content = json_decode ( $content, true );
            // 如果是企业号用以下 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;
            $data[‘accesstoken‘] = $ticket;
            $data[‘lasttime‘] = NOW_TIME;
            M(‘accesstoken‘)->where(array(‘id‘=>2))->save($data);
        }
        return $ticket;
  }

  //sae无法写入操作,改从数据库获取
  private function getAccessToken() {
   $param[‘grant_type‘] = ‘client_credential‘;
    $param[‘appid‘] = C("APPID");
    $param[‘secret‘] = C("SECRET");
    $lastAT = M(‘accesstoken‘)->find(1);
    $accesstoken = $lastAT[‘accesstoken‘];
    if(!$lastAT){
        M(‘accesstoken‘) -> add(array(‘id‘=>1,‘accesstoken‘=>‘null‘,‘lasttime‘=>0));
        $lastAT[‘lasttime‘] = 0;
    }
    $now = NOW_TIME;
    $timecha = $now - $lastAT[‘lasttime‘];
    if($timecha >= 7200){
        $url = ‘https://api.weixin.qq.com/cgi-bin/token?‘ . http_build_query ( $param );
        $content = file_get_contents ( $url );
        $content = json_decode ( $content, true );
        $data[‘accesstoken‘] = $content[‘access_token‘];
        $data[‘lasttime‘] = NOW_TIME;
        M(‘accesstoken‘)->where(array(‘id‘=>1))->save($data);
        $accesstoken = $content[‘access_token‘];
    }
    $lastAT = M(‘accesstoken‘)->find(1);
    return $accesstoken;
  }

  private function httpGet($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    // 为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,必须使用下面2行代码打开ssl安全校验。
    // 如果在部署过程中代码在此处验证失败,请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
    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;
  }

  private function get_php_file($filename) {
    return trim(substr(file_get_contents($filename), 15));
  }
  private function set_php_file($filename, $content) {
    $fp = fopen($filename, "w");
    fwrite($fp, "<?php exit();?>" . $content);
    fclose($fp);
  }
}

如果你的服务器是可写环境,可以使用官方提供的包。

前台文件

可以使用include将此文件包含在需要页面

<?php
include(‘jssdk.php‘);
$jssdk = new JSSDK(C(‘APPID‘), C(‘SECRET‘));
if(isWeixinBrowser()){
$signPackage = $jssdk->GetSignPackage();
}
?>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
wx.config({
    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    appId: ‘<?php echo $signPackage["appId"];?>‘, // 必填,公众号的唯一标识
    timestamp: <?php echo $signPackage["timestamp"];?>, // 必填,生成签名的时间戳
    nonceStr: ‘<?php echo $signPackage["nonceStr"];?>‘, // 必填,生成签名的随机串
    signature: ‘<?php echo $signPackage["signature"];?>‘,// 必填,签名,见附录1
    jsApiList: [
        ‘checkJsApi‘,

        ‘onMenuShareTimeline‘,

        ‘onMenuShareAppMessage‘,

        ‘onMenuShareQQ‘,

        ‘onMenuShareWeibo‘

                ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
wx.ready(function () {

      // 1 判断当前版本是否支持指定 JS 接口,支持批量判断

        wx.checkJsApi({

          jsApiList: [

            ‘getNetworkType‘,

            ‘previewImage‘,

             ‘onMenuShareTimeline‘,

            ‘onMenuShareAppMessage‘,

            ‘onMenuShareQQ‘,

            ‘onMenuShareWeibo‘

          ],

          /* success: function (res) {

            alert(JSON.stringify(res));

          } */


        });

        var shareData =http://www.mamicode.com/ {

                title: document.title,

                <notempty name="page_title">
                  desc: ‘我在‘+‘{:C(‘WEB_SITE_TITLE‘)}‘+‘发现了非常不错的宝贝:‘+‘{$page_title}‘+‘快来看看吧!‘,
                  <else/>
                  desc: ‘我发现了个很不错的商城‘+‘{:C(‘WEB_SITE_TITLE‘)}‘+‘快来看看吧!‘,
                  </notempty>

                  link: window.location.href,

                  <notempty name="page_title">
                  imgUrl: document.getElementById("detail_img").src,
                  <else/>
                  imgUrl: ‘{:get_cover(get_cover_id(34),‘path‘)}‘,
                  </notempty>

                 /*  trigger: function (res) {

                    alert(‘用户点击发送给朋友‘);

                  }, */

                  success: function (res) {

                    alert(‘感谢您的分享‘);

                  },

                  cancel: function (res) {

                    alert(‘请主公三思,分享一下吧(ㄒoㄒ)~~‘);

                  },

                  fail: function (res) {

                    alert(JSON.stringify(res));

                  }

              };

      wx.onMenuShareAppMessage(shareData);

      wx.onMenuShareTimeline(shareData);

      wx.onMenuShareQQ(shareData);

      wx.onMenuShareWeibo(shareData);

    });

    /* wx.error(function (res) {

      alert(res.errMsg);

    });  */
</script>

出处:blog.csdn.NET/afanxingzhou 

公众号js-sdk简