zoukankan      html  css  js  c++  java
  • 微信企业号-JS-SDK图像接口

    使用JS-SDK需要进行四步
     主要是步骤二和步骤三,步骤二需要配置,步骤三具体使用相关接口,这里以使用图像接口为例
    php页面代码主要用来完成步骤二,也就是配置接口
    1. public function index() {
    2. $signPackage = $this->getSignPackage();
    3. g("smarty") -> assign("appId", $signPackage['appId']);
    4. g("smarty") -> assign("timestamp", $signPackage['timestamp']);
    5. g("smarty") -> assign("nonceStr", $signPackage['nonceStr']);
    6. g("smarty") -> assign("signature", $signPackage['signature']);
    7. $file_name = 'jssdk.html';
    8. g("smarty") -> show(SYSTEM_ROOT . 'templates/jssdk/' . $file_name);
    9. }
    10. public function getSignPackage() {
    11. $jsapiTicket = $this->getJsApiTicket();
    12. // 注意 URL 一定要动态获取,不能 hardcode.
    13. $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    14. $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    15. $timestamp = time();
    16. $nonceStr = $this->createNonceStr();
    17. // 这里参数的顺序要按照 key 值 ASCII 码升序排序
    18. $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
    19. $signature = sha1($string);
    20. $signPackage = array(
    21. "appId" => $this->appId,
    22. "nonceStr" => $nonceStr,
    23. "timestamp" => $timestamp,
    24. "url" => $url,
    25. "signature" => $signature,
    26. "rawString" => $string,
    27. );
    28. return $signPackage;
    29. }
    30. private function createNonceStr($length = 16) {
    31. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    32. $str = "";
    33. for ($i = 0; $i < $length; $i++) {
    34. $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    35. }
    36. return $str;
    37. }
    38. private function getJsApiTicket() {
    39. // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
    40. $data = json_decode($this->get_php_file("jsapi_ticket.php"));
    41. if ($data->expire_time < time()) {
    42. $accessToken = $this->getAccessToken();
    43. // 如果是企业号用以下 URL 获取 ticket
    44. $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
    45. // 如果是第三方服务商用以下URL获取access_token
    46. // $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
    47. $res = json_decode($this->httpGet($url));
    48. $ticket = $res->ticket;
    49. if ($ticket) {
    50. $data->expire_time = time() + 7000;
    51. $data->jsapi_ticket = $ticket;
    52. $this->set_php_file("jsapi_ticket.php", json_encode($data));
    53. }
    54. } else {
    55. $ticket = $data->jsapi_ticket;
    56. }
    57. return $ticket;
    58. }
    59. private function getAccessToken() {
    60. // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
    61. $data = json_decode($this->get_php_file("access_token.php"));
    62. if ($data->expire_time < time()) {
    63. // 如果是企业号用以下URL获取access_token
    64. $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
    65.      // 如果是第三方服务商用以下URL获取access_token
    66. //$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
    67. $res = json_decode($this->httpGet($url));
    68. $access_token = $res->access_token;
    69. if ($access_token) {
    70. $data->expire_time = time() + 7000;
    71. $data->access_token = $access_token;
    72. $this->set_php_file("access_token.php", json_encode($data));
    73. }
    74. } else {
    75. $access_token = $data->access_token;
    76. }
    77. return $access_token;
    78. }
    79. private function httpGet($url) {
    80. $curl = curl_init();
    81. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    82. curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    83. // 为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,必须使用下面2行代码打开ssl安全校验。
    84. // 如果在部署过程中代码在此处验证失败,请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
    85. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    86. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    87. curl_setopt($curl, CURLOPT_URL, $url);
    88. $res = curl_exec($curl);
    89. curl_close($curl);
    90. return $res;
    91. }
    92. private function get_php_file($filename) {
    93. return trim(substr(file_get_contents(SYSTEM_DATA . 'jssdk/' . $filename), 15));
    94. }
    95. private function set_php_file($filename, $content) {
    96. $fp = fopen(SYSTEM_DATA . 'jssdk/' . $filename, "w");
    97. fwrite($fp, "<?php exit();?>" . $content);
    98. fclose($fp);
    99. }
    html页面代码主要用来完成步骤三,也就是具体调用相关接口
    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title></title>
    6. </head>
    7. <body>
    8. <button id="checkJsApi">判断当前客户端是否支持指定JS接口</button><br/>
    9. <button id="choose_image">拍照或从手机相册中选图接口</button><br/>
    10. <button id="preview_image">预览图片接口</button><br/>
    11. <button id="upload_image">上传图片接口</button><br/>
    12. <button id="download_image">下载图片接口</button>
    13. </body>
    14. <script src="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"></script>
    15. <script>
    16. wx.config({
    17. debug: false,// 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    18. appId: '<{$appId}>',// 必填,企业号的唯一标识,此处填写企业号corpid
    19. timestamp: '<{$timestamp}>',// 必填,生成签名的时间戳
    20. nonceStr: '<{$nonceStr}>',// 必填,生成签名的随机串
    21. signature: '<{$signature}>',// 必填,签名,见附录1
    22. jsApiList: [
    23. 'uploadVoice','downloadVoice','chooseImage', 'previewImage'
    24. ]
    25. });
    26. wx.ready(function () {
    27. //这里写页面加载时就调用的相关接口
    28. // 1 判断当前版本是否支持指定 JS 接口,支持批量判断
    29. document.querySelector('#checkJsApi').onclick = function () {
    30. wx.checkJsApi({
    31. jsApiList: [
    32. 'uploadVoice','downloadVoice','chooseImage', 'previewImage'
    33. ],
    34. success: function (res) {
    35. alert(JSON.stringify(res));
    36. }
    37. });
    38. };
    39. // 拍照、本地选图
    40. var images = {
    41. localId: [],
    42. serverId: []
    43. };
    44. document.querySelector('#choose_image').onclick = function () {
    45. wx.chooseImage({
    46. success: function (res) {
    47. images.localId = res.localIds;
    48. alert('已选择 ' + res.localIds.length + ' 张图片');
    49. }
    50. });
    51. };
    52. // 图片预览
    53. document.querySelector('#preview_image').onclick = function () {
    54. wx.previewImage({
    55. current: 'http://101.200.35.86/frame/data/jssdk/1.png',
    56. urls: [
    57. 'http://101.200.35.86/frame/data/jssdk/2.png',
    58. 'http://101.200.35.86/frame/data/jssdk/3.png',
    59. 'http://101.200.35.86/frame/data/jssdk/4.png'
    60. ]
    61. });
    62. };
    63. // 上传图片
    64. document.querySelector('#upload_image').onclick = function () {
    65. if (images.localId.length == 0) {
    66. alert('请先使用拍照或从手机相册中选图接口');
    67. return;
    68. }
    69. var i = 0, length = images.localId.length;
    70. images.serverId = [];
    71. function upload() {
    72. wx.uploadImage({
    73. localId: images.localId[i],
    74. success: function (res) {
    75. i++;
    76. alert('已上传:' + i + '/' + length);
    77. //这里实现具体上传的业务逻辑代码
    78. images.serverId.push(res.serverId);
    79. if (i < length) {
    80. upload();
    81. }
    82. },
    83. fail: function (res) {
    84. alert(JSON.stringify(res));
    85. }
    86. });
    87. }
    88. upload();
    89. };
    90. // 下载图片
    91. document.querySelector('#download_image').onclick = function () {
    92. if (images.serverId.length === 0) {
    93. alert('请先使用上传图片接口');
    94. return;
    95. }
    96. var i = 0, length = images.serverId.length;
    97. images.localId = [];
    98. function download() {
    99. wx.downloadImage({
    100. serverId: images.serverId[i],
    101. success: function (res) {
    102. i++;
    103. alert('已下载:' + i + '/' + length);
    104.            //这里实现具体下载的业务逻辑代码
    105. images.localId.push(res.localId);
    106. if (i < length) {
    107. download();
    108. }
    109. }
    110. });
    111. }
    112. download();
    113. };
    114. });
    115. wx.error(function(res){
    116. // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
    117. });
    118. </script>
    119. </html>
    效果图如下:
     




  • 相关阅读:
    计算机综合面试题总结
    MySQL入门很简单: 13 数据备份和还原
    MySQL入门很简单: 12 MYSQL 用户管理
    MySQL入门很简单: 11 mysql函数
    页面即使加过了移除监听事件,但是到新页面后事件任然存在
    git命令大全
    document.documentElement.scrollTop指定位置失效解决办法
    vue做商品选择如何保持样式
    vue父组件向子组件传对象,不实时更新解决
    vue 遮罩层阻止默认滚动事件
  • 原文地址:https://www.cnblogs.com/phonecom/p/5d7bac017816b442a4ed77a58c2e5cd1.html
Copyright © 2011-2022 走看看