获取微信js sdk授权
php
<?php declare (strict_types = 1); namespace app\api\controller; class WxJsSdk { public $appid; //公众号appi public $appsecret; //公众号密钥 public $merid; //商户号 public $merkey; //商户支付密钥 //读取配置数据 function __construct(){ $this->appid = env('WX.appid'); $this->appsecret = env('WX.appsecret'); $this->merid = env('WX.merid'); $this->merkey = env('WX.merkey'); } //获取wx.config需要的参数 public function getWxConfig(){ $link = input('link'); $access_token = $this->get_token($this->appid,$this->appsecret,1,1); $jsapiTicket = $this->get_ticket($access_token); $nonceStr = $this->nonceStr(16); $timestamp = time(); $string = 'jsapi_ticket='.$jsapiTicket.'&noncestr='.$nonceStr.'×tamp='.$timestamp.'&url='.$link; $signature = sha1 ($string); $WxConfig["appid"] = $this->appid; $WxConfig["noncestr"] = $nonceStr; $WxConfig["timestamp"] = $timestamp; $WxConfig["signature"] = $signature; $WxConfig["debug"] = true; return $WxConfig; } //生成签名的随机串 public function nonceStr($length){ $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJK1NGJBQRSTUVWXYZ';//随即串,62个字符 $strlen = 62; while($length > $strlen){ $str .= $str; $strlen += 62; } $str = str_shuffle($str); return substr($str,0,$length); } //获取access_token public function get_token($appid,$appsecret,$debug=0,$noCacheToken=1){ if(!isset($_COOKIE['token']) || $debug == 1 || $noCacheToken == 1){ $result = $this->http_get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret); $result = json_decode($result,true); $access_token = $result['access_token']; setcookie('token',$access_token,time()+7199); }else{ $access_token = $_COOKIE['token']; } return $access_token; } //获取ticket public function get_ticket($access_token){ $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token='.$access_token; $res = json_decode($this->http_get($url)); $ticket = $res->ticket; return $ticket; } //请求方法 public function http_get($url){ $oCurl = curl_init(); if(stripos($url,"https://")!==FALSE){ curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1 } curl_setopt($oCurl, CURLOPT_URL, $url); curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 ); $sContent = curl_exec($oCurl); $aStatus = curl_getinfo($oCurl); curl_close($oCurl); if(intval($aStatus["http_code"])==200){ return $sContent; }else{ return false; } } } ?>
js
async getWxConfig(item){ const res = await req('WxjsSdk/getWxConfig',{link:window.location.href}); wx.config({ debug: 1, appId: res.appid, timestamp: res.timestamp, nonceStr: res.noncestr, signature: res.signature, jsApiList: ["chooseImage","previewFile"] }); wx.ready(() => { //判断接口方法是否可用 wx.checkJsApi({ jsApiList: ['chooseImage','previewFile'], // 需要检测的JS接口列表,所有JS接口列表见附录2, success: function(res) { console.log(res); } }); //alert('准备好了'); }); }