使用微信jssdk接口调用语音,图片,分享等功能

1.在js接口安全域名中明设置你的业务域名

2.获取access_token以及jsticket

public function getvAssaceTokena(){
      $appId = config('post_house.wx_appid');
      $secret = config('post_house.wx_appsecret');
      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$secret}";
      return json_decode( https_request($url) )->access_token;
    } 

    public function getvTicketa($token){
      $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$token."&type=jsapi";
      return json_decode(https_request($url))->ticket;
    }

3.生成随机数

public function createNonceStra($length = 16) {
      $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      $str = "";
      for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
      }
      return $str;
    }

4.生成签名 

public function sdksign($url){
		$time =time();
        if(Cache::get('post_token')){
            $token = Cache::get('post_token');
        }else{
            $token = $this->getvAssaceTokena();
            Cache::set('post_token',$token,7100);
        }
         if(Cache::get('post_ticket')){
            $ticket = Cache::get('post1_ticket');
        }else{
             $ticket = $this->getvTicketa($token);
            Cache::set('post_ticket',$ticket,7100);
        }
        $nonceStr = $this->createNonceStra();
        // Cache::clear(); 
        $url = $url;
        $str = "jsapi_ticket={$ticket}&noncestr={$nonceStr}&timestamp={$time}&url={$url}";
        $signature = sha1($str);
        $appid = config('post_house.wx_appid');
        return array('nonceStr' =>$nonceStr ,'timestamp'=>$time,'signature' =>$signature,'appid'=>$appid );
	}

5.前端页面引入微信js

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

6.将需要引入的功写在wx.config里

$(function(){
				wx.config({
			    debug: false,
			    appId: '{$appId}',
			    timestamp: '{$timestamp}',
			    nonceStr: '{$nonceStr}',
			    signature: '{$signature}',
			    jsApiList: [
			      // 所有要调用的 API 都要加到这个列表中
			      'startRecord',
			      'stopRecord',
			      'onVoiceRecordEnd',
			      'playVoice',
			      'pauseVoice',
			      'stopVoice',
			      'onVoicePlayEnd',
			      'uploadVoice',
			      'chooseImage',
			      'uploadImage',
			      'downloadImage',
			      'uploadVoice',
			      'onMenuShareAppMessage'
			    ]
			});

我使用了微信语音接口及有图片上传接口  并且将语音文件以及图片上传到微信服务器因为微信服务器有限制仅保存三天,所以需要将文件西再到自己的服务器上

(function(){
					$("input[type='button']").click(function(e){
						wx.chooseImage({
					      count: 1, // 默认9
					      sizeType: ['original','compressed'], // 可以指定是原图还是压缩图,默认二者都有
					      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
					      success: function (res) {
					        var localIds = res.localIds; 
					        $('#localIds').attr('value',localIds)
					        uploadImageurl();
					      }
					    });
					});

					var uploadImageurl = function(){
					    var localIds = $('#localIds').val();
						wx.uploadImage({
					      localId: localIds, // 需要上传的图片的本地ID,由chooseImage接口获得
					      isShowProgressTips: 1, // 默认为1,显示进度提示
					      success: function (res) {
						      serverId = res.serverId; // 返回图片的服务器端ID
						       $('#serverId').attr('value',serverId)
						       qiniu();
					      	}
					    });
					}	

					var qiniu = function(){
						$.ajax({
							'url':"{:url('qiniu')}",
							'data':{serverId},
				            'type':'post',
				            'dataType':'json',
				            success:function(res){
				            	var url = res.substr(7,61)
				            	var img_url = res.substr(30,64)
				            	
				            	$('#img_url').attr('value',img_url);
				            	$('.addPic .add_btn').css('display','none');
				            	$('.addPic .int_img').attr("src",url);
				            	console.log(res)
				            }
						})
					}
 
				})();

下载方式

public function qiniu(){
		$serverId = $_POST['serverId'];
		$new_url = "/public/uploads/posthouse_img/".date('YmdHis').rand(100,999).".jpg";
			
		if(Cache::get('post1_token')){
            $token = Cache::get('post1_token');
        }else{
            $token = $this->getvAssaceTokena();
            Cache::set('post1_token',$token,7200);
        }
        $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$token."&media_id=".$serverId;
        $a = file_get_contents($url);
        // $new_url = "/public/uploads/posthouse_img/posthouse_".date('YmdHis').rand().".jpg";
        $fileurl =ROOT_PATH .$new_url;
        $resource = fopen($fileurl , 'w+');
        fwrite($resource, $a);
        fclose($resource);
        echo json_encode($new_url);exit;
	}

使用上传后返回的服务端id请求接口将文件写入自己到服务器上

语音接口与图像接口下载方式相似  需要注意的是 微信下载的语音个事是amr格式的 在页面audio标签无法使用 所以需要将amr格式的转化成MP3格式的音频  需要在服务器配置一个插件ffmpeg

参考文档: 
ffmpeg安装指南:https://trac.ffmpeg.org/wiki/CompilationGuide 

ffmpeg git地址:https://github.com/FFmpeg/FFmpeg

public function qiniu_voice(){	
		$serverId = $_POST['voice_serverId'];
		$voice_url = "/public/uploads/posthouse_voice/".date('YmdHis').rand(100,999);	
		if(Cache::get('post1_token')){
            $token = Cache::get('post1_token');
        }else{
            $token = $this->getvAssaceTokena();
            Cache::set('post1_token',$token,7200);
        }	
        $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$token."&media_id=".$serverId;
        $a = file_get_contents($url);
        // $new_url = "/public/uploads/posthouse_img/posthouse_".date('YmdHis').rand().".jpg";
        $fileurl =ROOT_PATH .$voice_url;
        $resource = fopen($fileurl , 'w+');
        fwrite($resource,$a);
        fclose($resource);
        $amr = '/data/wwwroot/qqcardcs.10088.cn'.$voice_url;
        $mp3 = $amr.'.mp3';
		$error = null;  
		 if(file_exists($mp3) == true){  
		     // exit('无需转换');  
		 }else{  
		     $command = "/usr/local/bin/ffmpeg -i $amr $mp3";
		     $a = exec($command,$error);
		     unlink($amr);
		 } 
        echo json_encode($mp3);exit;
	}

猜你喜欢

转载自blog.csdn.net/myzhou2017/article/details/81167831
今日推荐