天天看點

PHP調用微信JSSDK接口 選擇相冊及拍照、圖檔上傳

流程分析:

通過微信拍照或選擇本地照片接口選擇需要上傳的圖檔,通過圖檔上傳接口上傳到微信的伺服器,微信伺服器返給你一個臨時素材的media_id,使用token與這個media_id擷取到圖檔(通過微信的擷取臨時素材接口),儲存到自己伺服器即可。

1、通過微信js接口,調用底層程式。

     需要引入js檔案,并進行配置。

<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>

wx.config({

  debug: false,

  appId: 'wxed7996e9ad58345d',

  timestamp: 1449717454,

  nonceStr: 'asdfasdfasdf',

  signature:'b74fb4ab4790172d2ab7e58f0051a1523aaa4803',

  jsApiList: [

    'chooseImage',

    'uploadImage'

  ]

});

其中appId為微信公衆平台id,timestamp為目前時間戳,nonceStr為随機字元串,signature為簽名。signature是最重要參數。

2、首先擷取access_token,能存活兩小時,每天允許擷取2000次。超過就不能擷取了。

// 擷取access_token 兩小時有效

private function get_access_token(){

    $appid = C('oauth_config.appid');

    $appsecret =C('oauth_config.appsecret');

    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;

    $rurl = file_get_contents($url);

    $rurl = json_decode($rurl,true);

    if(array_key_exists('errcode',$rurl)){

      return false;

    }else{

      $access_token = $rurl['access_token'];

      return $access_token;

    }

}

3、 然後擷取jsticket

// 擷取jsticket 兩小時有效

private function getjsticket(){ // 隻允許本類調用,繼承的都不可以調用,公開調用就更不可以了

    $access_token =$this->get_access_token();

    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";// 兩小時有效

    $rurl = file_get_contents($url);

    $rurl = json_decode($rurl,true);

    if($rurl['errcode'] != 0){

      return false;

    }else{

      $jsticket = $rurl['ticket'];

      return $jsticket;

    }

}

4、然後擷取signature,它是由多個參數拼接加密形成的,有實效性

// 擷取 signature

private function getsignature(){

    $noncestr = '';

    $jsapi_ticket =$this->getjsticket();

    $timestamp = time();

    $url = 'http://zhudianbao.diandodo.com/index.php?g=Opener&m=Merchant&a=open';

    $string1 ='jsapi_ticket='.$jsapi_ticket.'&noncestr='.$noncestr.'×tamp='.$timestamp.'&url='.$url;

    $signature = sha1($string1);

    return $signature;

}

5、 配置好之後,就可以使用了。我用了兩個功能,一個是選擇照片,一個是上傳照片。

function chooseImage(obj){

  // 選擇張片

  wx.chooseImage({

    count: 1, // 預設9

    sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,預設二者都有

    sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,預設二者都有

    success: function(res) {

      var localIds = res.localIds;// 傳回標明照片的本地ID清單,localId可以作為img标簽的src屬性顯示圖檔

      $(obj).attr('src', localIds);

      // 上傳照片

      wx.uploadImage({

        localId: '' + localIds,

        isShowProgressTips: 1,

        success: function(res) {

          serverId =res.serverId;

          $(obj).next().val(serverId);// 把上傳成功後擷取的值附上

        }

      });

    }

  });

}

6、

選擇照片傳回的localIds很有意思,可以用于上傳使用,并且可以放在img的src屬性中,展示圖檔。

上傳成功後,擷取一個serverId,通過這個id可以下載下傳上傳到微信伺服器上的圖檔檔案,把它儲存到自己的伺服器中。

// 擷取圖檔位址

private function getmedia($access_token,$media_id,$foldername){

    $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$media_id;

    if (!file_exists("./Uploads/User_cert/".$foldername)){

      mkdir("./Uploads/User_cert/".$foldername,0777, true);

    }

    $targetName ='./Uploads/User_cert/'.$foldername.'/'.date('YmdHis').rand(1000,9999).'.jpg';

    $ch = curl_init($url); // 初始化

    $fp = fopen($targetName, 'wb'); // 打開寫入

    curl_setopt($ch, CURLOPT_FILE, $fp); // 設定輸出檔案的位置,值是一個資源類型

    curl_setopt($ch, CURLOPT_HEADER, 0);

    curl_exec($ch);

    curl_close($ch);

    fclose($fp);

    return $targetName;

}

7、 防止圖檔名稱相同,加一個rand随機數,因為在同一秒鐘可能會上傳多張照片。

$targetName

=

'./Uploads/User_cert/'.$foldername.'/'.date('YmdHis').rand(1000,9999).'.jpg';

8、這個serverId以表單的形式送出到伺服器,然後對其進行寫入檔案,擷取位址,并把位址儲存到伺服器中。

微信的js與jquery不沖突,可以共同使用。

微信JSSDK:

<?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×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 getJsApiTicket() {

  // jsapi_ticket 應該全局存儲與更新,以下代碼以寫入到檔案中做示例

  $data =json_decode(file_get_contents("jsapi_ticket.json"));

  if ($data->expire_time < time()) {

   $accessToken = $this->getAccessToken();

   // 如果是企業号用以下 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;

   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擷取access_token

   // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";

   $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);

  // 為保證第三方伺服器與微信伺服器之間資料傳輸的安全性,所有微信接口采用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;

 }

}