天天看點

微信sdk使用

<?php
namespace Home\Controller;
use Think\Controller;
use Com\Wechat;
use Com\WechatAuth;
class SdkController extends Controller {
	private	 $appid="wx38ff738";
    private  $appSecret="8b4efedf96";
    private  $WechatAuth="";//初始化WechatAuth類
    private  $access_token="";//緩存token
    private  $jsapi_ticket="";//緩存jsapi_ticket

    /**
     * 微信api根路徑
     * @var string
     */
    private $apiURL = 'https://api.weixin.qq.com/cgi-bin';
    public function __construct(){
    		parent::__construct();

    		if(!session('token')){
    			$this->WechatAuth=new WechatAuth($this->appid,$this->appSecret);//初始化WechatAuth類
    			$WechatAuth=$this->WechatAuth;
    			$token=$WechatAuth->getAccessToken();
    			session(array('expire'=>$token['expires_in']));//設定過期時間
    			session('token',$token['access_token']);//緩存token
    			$this->access_token=$token;
    		}else{
    			$token=session('token');
    			$this->WechatAuth=new WechatAuth($this->appid,$this->appSecret,$token);//初始化WechatAuth類
    			$this->access_token=$token;//緩存token
    		}


            // jsapi_ticket 應該全局存儲與更新,以下代碼以寫入到檔案中做示例
           
            if (!session('jsapi_ticket')) {
              $accessToken = $this->access_token;
              // 如果是企業号用以下 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));
              $this->jsapi_ticket = $res->ticket;
              session(array('expire'=>7000));//設定過期時間
              session('jsapi_ticket', $this->jsapi_ticket);
            } else {
              $this->jsapi_ticket = session('jsapi_ticket');
            }

           
       

    }

    public function index(){
        $data=$this->getSignPackage();
        $this->assign('data',$data);
        $this->display();
    }

    
  public function getSignPackage() {
    $jsapiTicket = $this->jsapi_ticket;

    // 注意 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×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 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;
  }


}
           

html

<html >
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
		<button  id="btn1"  style="width:80%;height:300px;font-size:100px;background:green;">圖像接口的使用</button>
		<button  id="btn2"  style="width:80%;height:300px;font-size:100px;background:green;">掃一掃接口的使用</button>
</body>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
  /*
   * 注意:
   * 1. 所有的JS接口隻能在公衆号綁定的域名下調用,公衆号開發者需要先登入微信公衆平台進入“公衆号設定”的“功能設定”裡填寫“JS接口安全域名”。
   * 2. 如果發現在 Android 不能分享自定義内容,請到官網下載下傳最新的包覆寫安裝,Android 自定義分享接口需更新至 6.0.2.58 版本及以上。
   * 3. 常見問題及完整 JS-SDK 文檔位址:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
   *
   * 開發中遇到問題詳見文檔“附錄5-常見錯誤及解決辦法”解決,如仍未能解決可通過以下管道回報:
   * 郵箱位址:[email protected]
   * 郵件主題:【微信JS-SDK回報】具體問題
   * 郵件内容說明:用簡明的語言描述問題所在,并交代清楚遇到該問題的場景,可附上截屏圖檔,微信團隊會盡快處理你的回報。
   */
  wx.config({
    debug: false,
    appId: '<?php echo $data["appId"];?>',
    timestamp: <?php echo $data["timestamp"];?>,
    nonceStr: '<?php echo $data["nonceStr"];?>',
    signature: '<?php echo $data["signature"];?>',
    jsApiList: [
      'checkJsApi',
     'chooseImage',
     'scanQRCode'
    ]
  });

  var bnt1=document.getElementById("btn1");
  var bnt2=document.getElementById('btn2');
  	bnt1.οnclick=function(){
  		 wx.chooseImage({
			    count: 1, // 預設9
			    sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,預設二者都有
			    sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,預設二者都有
			    success: function (res) {
			        var localIds = res.localIds; // 
			        document.write("<img src="+localIds+">");
			    }
			});
  	}

  	bnt2.οnclick=function(){
  		 wx.scanQRCode({
			    needResult: 0, // 預設為0,掃描結果由微信處理,1則直接傳回掃描結果,
			    scanType: ["qrCode","barCode"], // 可以指定掃二維碼還是一維碼,預設二者都有
			    success: function (res) {
			    var result = res.resultStr; // 當needResult 為 1 時,掃碼傳回的結果
			}
			});
  	}
 




  wx.ready(function () {
    wx.checkJsApi({
        jsApiList: ['chooseImage'], // 需要檢測的JS接口清單,所有JS接口清單見附錄2,
        success: function(res) {
            // 以鍵值對的形式傳回,可用的api值true,不可用為false
            // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
        }
    });
  });
</script>
</html>
           

繼續閱讀