實戰微信JS SDK開發:賀卡製做與播放(1)

前段時間忙於CanTK 2.0的開發,因此博客一直沒有更新。CanTK 2.0主要加強了遊戲和富媒體的開發,如今編碼和測試基本完成了,等文檔完成了再正式發佈,裏面有很多激動人心的功能大笑,等發佈時再一一細說吧。php

最近同事用CanTK開發了一個基於微信的賀卡製做APP,我雖然沒有參與開發,可是提供CanTKGameBuilder的技術支持,以爲有些東西比較有意思,寫幾篇博客和你們分享吧。這個賀卡APP徹底開源,有須要的朋友能夠隨意修改和發佈。html

CanTK(Canvas ToolKit)是一個開源的遊戲引擎和APP框架,是開發HTML5遊戲和APP的利器,若是你喜歡它,請在github上給它加星,您的支持是咱們努力的動力:https://github.com/drawapp8/cantkgit


0.先Show一下最終成果:

在線運行: http://gamebuilder.duapp.com/apprun.php?appid=osgames1-821423377846894

在線編輯: http://gamebuilder.duapp.com/gamebuilder.php?appid=osgames1-821423377846894


微信掃碼:github


1.生成微信JS SDK配置json


生成微信JS SDK配置的資料,網上已經很多,咱們拿來時作些幾點改進:
  1. 緩存放到臨時目錄,而不是當前目錄。
  2. 過時時間改爲3600秒,而不是官方的兩個小時。
  3. 把它作成一個服務,APP經過AJAX來生成當前URL須要的配置,方便CanTK的調用。
代碼以下:
<?php
class JSSDK {
  private $appId;
  private $appSecret;
  public function __construct($appId, $appSecret) {
    $this->appId = $appId;
    $this->appSecret = $appSecret;
  }
  public function getSignPackage($url) {
    $jsapiTicket = $this->getJsApiTicket();
    if(!$url) {
    	$url = "http://$_SERVER[HTTP_HOST]" . '/weixin/demo/index.html';
    }
    $timestamp = time();
    $nonceStr = $this->createNonceStr();
    // 這裏參數的順序要按照 key 值 ASCII 碼升序排序
    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$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 getFileName($name) {
  	$fileName = sys_get_temp_dir() . "/weixin-" . $name;
  	return $fileName;
  }

  private function saveData($name, $content) {
  	$fileName = $this->getFileName($name);

    $fp = fopen($fileName, "wb+");
    if($fp) {
    	fwrite($fp, $content);
    	fclose($fp);
    }

  	return;
  }
  
  private function loadData($name, $defaultContent) {
  	$fileName = $this->getFileName($name);
  	$content = file_get_contents($fileName);

  	if($content) {
  		return $content;
  	}
  	else {
  		return $defaultContent;
  	}

  	return;
  }

  private function getJsApiTicket() {
    $data = json_decode($this->loadData("jsapi_ticket.json", '{"jsapi_ticket":"", "expire_time":0}'));
    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() + 3600;
        $data->jsapi_ticket = $ticket;
        $this->saveData("jsapi_ticket.json",  json_encode($data));
      }
    } else {
      $ticket = $data->jsapi_ticket;
    }
    return $ticket;
  }
  private function getAccessToken() {
    $data = json_decode($this->loadData("access_token.json", '{"access_token":"", "expire_time": 0}'));
    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));
      if(!isset($res->access_token)) {
      	print_r($res);
      	exit;
      }

      $access_token = $res->access_token;
      if ($access_token) {
        $data->expire_time = time() + 3000;
        $data->access_token = $access_token;
        $this->saveData("access_token.json", json_encode($data));
      }
    } 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;
  }
}

session_start();
if(!isset($_REQUEST['url'])) {
	echo "invalid arguments";
	exit;
}

$appID = "xxxxx";
$appSecret = "xxxxx";

$url = $_REQUEST['url'];
$url = base64_decode($url);

$jssdk = new JSSDK($appID, $appSecret);
$signPackage = $jssdk->getSignPackage($url); 
$signPackage['jsApiList'] = [
        'checkJsApi',
        'chooseImage',
        'previewImage',
        'uploadImage',
        'downloadImage',
        'getNetworkType'
      ];

echo json_encode($signPackage);
?>
相關文章
相關標籤/搜索