
主要是步骤二和步骤三,步骤二需要配置,步骤三具体使用相关接口,这里以使用图像接口为例
php页面代码主要用来完成步骤二,也就是配置接口
public function index() {$signPackage = $this->getSignPackage();g("smarty") -> assign("appId", $signPackage['appId']);g("smarty") -> assign("timestamp", $signPackage['timestamp']);g("smarty") -> assign("nonceStr", $signPackage['nonceStr']);g("smarty") -> assign("signature", $signPackage['signature']);$file_name = 'jssdk.html';g("smarty") -> show(SYSTEM_ROOT . 'templates/jssdk/' . $file_name);}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($this->get_php_file("jsapi_ticket.php"));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获取access_token// $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;$this->set_php_file("jsapi_ticket.php", json_encode($data));}} else {$ticket = $data->jsapi_ticket;}return $ticket;}private function getAccessToken() {// access_token 应该全局存储与更新,以下代码以写入到文件中做示例$data = json_decode($this->get_php_file("access_token.php"));if ($data->expire_time < time()) {// 如果是企业号用以下URL获取access_token$url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";- // 如果是第三方服务商用以下URL获取access_token
//$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;$this->set_php_file("access_token.php", 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);// 为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,必须使用下面2行代码打开ssl安全校验。// 如果在部署过程中代码在此处验证失败,请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。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;}private function get_php_file($filename) {return trim(substr(file_get_contents(SYSTEM_DATA . 'jssdk/' . $filename), 15));}private function set_php_file($filename, $content) {$fp = fopen(SYSTEM_DATA . 'jssdk/' . $filename, "w");fwrite($fp, "<?php exit();?>" . $content);fclose($fp);}
html页面代码主要用来完成步骤三,也就是具体调用相关接口
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title></title></head><body><button id="checkJsApi">判断当前客户端是否支持指定JS接口</button><br/><button id="choose_image">拍照或从手机相册中选图接口</button><br/><button id="preview_image">预览图片接口</button><br/><button id="upload_image">上传图片接口</button><br/><button id="download_image">下载图片接口</button></body><script src="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"></script><script>wx.config({debug: false,// 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。appId: '<{$appId}>',// 必填,企业号的唯一标识,此处填写企业号corpidtimestamp: '<{$timestamp}>',// 必填,生成签名的时间戳nonceStr: '<{$nonceStr}>',// 必填,生成签名的随机串signature: '<{$signature}>',// 必填,签名,见附录1jsApiList: ['uploadVoice','downloadVoice','chooseImage', 'previewImage']});wx.ready(function () {//这里写页面加载时就调用的相关接口// 1 判断当前版本是否支持指定 JS 接口,支持批量判断document.querySelector('#checkJsApi').onclick = function () {wx.checkJsApi({jsApiList: ['uploadVoice','downloadVoice','chooseImage', 'previewImage'],success: function (res) {alert(JSON.stringify(res));}});};// 拍照、本地选图var images = {localId: [],serverId: []};document.querySelector('#choose_image').onclick = function () {wx.chooseImage({success: function (res) {images.localId = res.localIds;alert('已选择 ' + res.localIds.length + ' 张图片');}});};// 图片预览document.querySelector('#preview_image').onclick = function () {wx.previewImage({current: 'http://101.200.35.86/frame/data/jssdk/1.png',urls: ['http://101.200.35.86/frame/data/jssdk/2.png','http://101.200.35.86/frame/data/jssdk/3.png','http://101.200.35.86/frame/data/jssdk/4.png']});};// 上传图片document.querySelector('#upload_image').onclick = function () {if (images.localId.length == 0) {alert('请先使用拍照或从手机相册中选图接口');return;}var i = 0, length = images.localId.length;images.serverId = [];function upload() {wx.uploadImage({localId: images.localId[i],success: function (res) {i++;alert('已上传:' + i + '/' + length);//这里实现具体上传的业务逻辑代码images.serverId.push(res.serverId);if (i < length) {upload();}},fail: function (res) {alert(JSON.stringify(res));}});}upload();};// 下载图片document.querySelector('#download_image').onclick = function () {if (images.serverId.length === 0) {alert('请先使用上传图片接口');return;}var i = 0, length = images.serverId.length;images.localId = [];function download() {wx.downloadImage({serverId: images.serverId[i],success: function (res) {i++;alert('已下载:' + i + '/' + length);//这里实现具体下载的业务逻辑代码images.localId.push(res.localId);if (i < length) {download();}}});}download();};});wx.error(function(res){// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。});</script></html>
效果图如下:
