jssdk.js 微信接口api调用

曹え 5811 发布于:2019-06-05 12:09:21

jssdk.php

<?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&timestamp=$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 应该全局存储与更新,以下代码以写入到文件中做示例

      $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;
      return $ticket;

  }

  private function getAccessToken() {
    // access_token 应该全局存储与更新,以下代码以写入到文件中做示例

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

       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;
  }

  private function get_php_file($filename) {
    return trim(substr(file_get_contents($filename), 15));
  }
  private function set_php_file($filename, $content) {
    $fp = fopen($filename, "w");
    fwrite($fp, "<?php exit();?>" . $content);
    fclose($fp);
  }
}


php 引入

<?php
require_once "jssdk.php";
    $appId = "wx2958c8f7d634455233";
    $appSecret = "767ab2f816642e9655e34d2735e978e70c";
$jssdk = new JSSDK($appId, $appSecret);
$signPackage = $jssdk->GetSignPackage();
//echo json_encode($signPackage);
?>
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
    <meta name="renderer" content="webkit" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
    <meta name="format-detection" content="telephone=no" />
    <title></title>
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    <script src="js/jquery.js"></script>
<style>
button,body { display: block; padding: 10px; margin: 10px 0;
    -webkit-touch-callout: none;
            -webkit-user-select: none;
            -khtml-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
        
}
</style>
</head>

<body>
     
    <h3 id="menu-voice">音频接口</h3>
      开始录音接口
      <button class="btn btn_primary" id="startRecord">startRecord</button>
      停止录音接口
      <button class="btn btn_primary" id="stopRecord">stopRecord</button>
      播放语音接口
      <button class="btn btn_primary" id="playVoice">playVoice</button>
      暂停播放接口
      <button class="btn btn_primary" id="pauseVoice">pauseVoice</button>
      停止播放接口
      <button class="btn btn_primary" id="stopVoice">stopVoice</button>
      上传语音接口
      <button class="btn btn_primary" id="uploadVoice">uploadVoice</button>
      下载语音接口
      <button class="btn btn_primary" id="downloadVoice">downloadVoice</button>
 
      <h3 id="menu-smart">智能接口</h3>
      识别音频并返回识别结果接口
      <button class="btn btn_primary" id="translateVoice">translateVoice</button>
<!-- 微信分享 -->
<button id="messageBtn">语音输入手机号</button>


<script type="text/javascript" src='http://res.wx.qq.com/open/js/jweixin-1.4.0.js'></script>
  <script type="text/javascript">



  wx.config({
    debug: false,
    appId: "<?php echo $signPackage['appId']; ?>",
    timestamp: "<?php echo $signPackage['timestamp']; ?>",
    nonceStr: "<?php echo $signPackage['nonceStr']; ?>",
    signature: "<?php echo $signPackage['signature']; ?>",
    jsApiList: [
      // 所有要调用的 API 都要加到这个列表中
'checkJsApi',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
        'hideMenuItems',
        'showMenuItems',
        'hideAllNonBaseMenuItem',
        'showAllNonBaseMenuItem',
        'translateVoice',
        'startRecord',
        'stopRecord',
        'onRecordEnd',
        'playVoice',
        'pauseVoice',
        'stopVoice',
        'uploadVoice',
        'downloadVoice',
        'chooseImage',
        'previewImage',
        'uploadImage',
        'downloadImage',
        'getNetworkType',
        'openLocation',
        'getLocation',
        'hideOptionMenu',
        'showOptionMenu',
        'closeWindow',
        'scanQRCode',
        'chooseWXPay',
        'openProductSpecificView',
        'addCard',
        'chooseCard',
        'openCard'
    ]
  });
 
//完成wx.config,执行这里
         wx.ready(function () {

            wx.checkJsApi({
                jsApiList: ['chooseImage','updateTimelineShareData','updateAppMessageShareData'], // 需要检测的JS接口列表,所有JS接口列表见附录2,
                success: function(res) {
                // 以键值对的形式返回,可用的api值true,不可用为false
                console.log(res);
                // 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                }
            });

             //分享到朋友圈
             wx.onMenuShareTimeline({
                 title: '发条微信就能记账,太好用了!简单记账,轻松理财 —— 微账本!', // 分享标题
                 link:"http://zhangben.cn/index.php?a=gits",
                 imgUrl: "http://zhangben.cn/img/getheadimg.jpg", // 分享图标
                 success: function () {
                    
                 }
             });

             //分享给朋友
             wx.onMenuShareAppMessage({
                 title: '微账本', // 分享标题
                 desc: '赶快试试这个,发条微信就能记账,太好用了!',
                 link:"http://zhangben.cn/index.php?a=gits",
                 imgUrl: "http://zhangben.cn/img/getheadimg.jpg", // 分享图标
                 success: function (res) {
                     
                 }
             });
 
  // 4 音频接口
  
    // 3 智能接口
  var voice = {
    localId: '',
    serverId: ''
  };
  // 3.1 识别音频并返回识别结果
  document.querySelector('#translateVoice').onclick = function () {
    if (voice.localId == '') {
      alert('请先使用 startRecord 接口录制一段声音');
      return;
    }
    wx.translateVoice({
      localId: voice.localId,
      complete: function (res) {
        if (res.hasOwnProperty('translateResult')) {
          alert('识别结果:' + res.translateResult);
        } else {
          alert('无法识别');
        }
      }
    });
  };
  
  // 4.2 开始录音
  document.querySelector('#startRecord').onclick = function () {
    wx.startRecord({
      cancel: function () {
        alert('用户拒绝授权录音');
      }
    });
  };
 
  // 4.3 停止录音
  document.querySelector('#stopRecord').onclick = function () {
    wx.stopRecord({
      success: function (res) {
        voice.localId = res.localId;
      },
      fail: function (res) {
        alert(JSON.stringify(res));
      }
    });
  };
 
  // 4.4 监听录音自动停止
  wx.onVoiceRecordEnd({
    complete: function (res) {
      voice.localId = res.localId;
      alert('录音时间已超过一分钟');
    }
  });
 

 wx.onVoiceRecordEnd({
// 录音时间超过一分钟没有停止的时候会执行 complete 回调
complete: function (res) {
var localId = res.localId;
wx.translateVoice({
localId: localId, // 需要识别的音频的本地Id,由录音相关接口获得
isShowProgressTips: 1, // 默认为1,显示进度提示
success: function (res) {
alert(res.translateResult); // 语音识别的结果
}
});
}
});

var btnElem=document.getElementById("messageBtn");//获取ID
var posStart = 0;//初始化起点坐标
var posEnd = 0;//初始化终点坐标
var posMove = 0;//初始化滑动坐标
console.log(screen);
function initEvent() {
btnElem.addEventListener("touchstart", function(event) {
event.preventDefault();//阻止浏览器默认行为
posStart = 0;
posStart = event.touches[0].pageY;//获取起点坐标
btnElem.value = '松开 结束';
console.log("start");
console.log(posStart+'---------开始坐标');
 wx.startRecord({
 cancel: function () {
alert('用户拒绝授权录音');
 }
});
});
btnElem.addEventListener("touchmove", function(event) {
event.preventDefault();//阻止浏览器默认行为
posMove = 0;
posMove = event.targetTouches[0].pageY;//获取滑动实时坐标
if(posStart - posMove < 500){
btnElem.value = '松开 结束';
}else{
btnElem.value = '松开手指,取消发送';
save();
}
/*console.log(posStart+'---------');
console.log(posMove+'+++++++++');*/
});
btnElem.addEventListener("touchend", function(event) {
event.preventDefault();
posEnd = 0;
posEnd = event.changedTouches[0].pageY;//获取终点坐标
btnElem.value = '按住 说话';
console.log("End");
console.log(posEnd+'---------结束坐标');
if(posStart - posEnd < 500 ){
console.log("发送成功");
save();
}else{
console.log("取消发送");
console.log("Cancel");
};
});
};
initEvent();
function save(){
//ajax
console.log('Success');
wx.stopRecord({
 success: function (res) {
voice.localId = res.localId;
wx.translateVoice({
 localId: voice.localId,
 complete: function (res) {
if (res.hasOwnProperty('translateResult')) {
 alert('识别结果:' + res.translateResult);
} else {
 alert('无法识别');
}
 }
});
 },
 fail: function (res) {
alert(JSON.stringify(res));
 }
});
}

 
         });
  
 
  </script>


</body>

</html>


觉得有用请点个赞吧!
0 571