current position:Home>Actual combat simulation│WeChat JSSDK realizes functions such as custom sharing, mobile phone picture selection and photography, picture audio processing, geographic location, shake and other functions

Actual combat simulation│WeChat JSSDK realizes functions such as custom sharing, mobile phone picture selection and photography, picture audio processing, geographic location, shake and other functions

2022-08-23 13:53:12Geek Flying Rabbit

微信 JS-SDK

  • 微信 JS-SDK 是微信公众平台 面向网页开发者提供的基于微信内的网页开发工具包
  • 通过使用微信 JS-SDK,Developers can use WeChat efficiently 拍照选图语音位置and other capabilities of the mobile phone system
  • 同时可以直接使用 微信分享扫一扫卡券支付 Wait for the unique capabilities of WeChat,It is to manage all the ecology of WeChatAPI

jssdk功能支持

JS-SDK 使用步骤

  • 绑定域名: 需要在微信公众平台 公众号设置功能设置 里填写 JS接口安全域名
  • 引入 JS 文件: 要使用 JS-SDK 的接口,需要引入 http://res.wx.qq.com/open/js/jweixin-1.6.0.js
  • 注入配置: 所有需要使用 JS-SDK 的页面必须先注入配置信息,否则将无法调用
  • Configure the callback after successful verification:config 信息验证后会执行 ready 方法
  • Configure the callback after validation fails:config信息验证失败会执行 error 函数,如签名过期导致验证失败
wx.config({
    
  debug: true, // 开启调试模式,调用的所有 api 的返回值会在客户端 alert 出来,若要查看传入的参数,可以在 pc 端打开,参数信息会通过 log 打出,仅在 pc 端时才会打印.
  appId: '', // 必填,公众号的唯一标识
  timestamp: , // 必填,生成签名的时间戳
  nonceStr: '', // 必填,生成签名的随机串
  signature: '',// 必填,签名
  jsApiList: [] // 必填,需要使用的 JS 接口列表
});

wx.ready(function(){
    
  // 成功后的回调,所有接口调用都必须在 config 接口获得结果之后
});

wx.error(function(res){
    
  // 失败后的回调
});

JS-SDK 签名生成

  • It can be known from the above,如果想要调用 JS-SDK 的接口,必须是在 wx.config Only after the verification is successful
  • wx.config 里面最重要的就是 JS-SDK Some parameters in the signature
  • 点击可下载 官方SDK示例,SDK 其中包含 phpjavanodejs以及 python 的示例代码,One of them is packaged JS-SDK Signature generation class
  • 我们这里以 php Signature generation class to explain,前端使用 JS-SDK 接口,One of them must be called getSignPackage 方法,生成签名包,Then put the parameters inside the package,传到 wx.config 中即可
  • getSignPackage 中,You can see that it needs to be generated jsapiTicket 标识,And this logo needs to be passed access_token 获取
  • 然后将获取到的 jsapiTicket 标识与 请求url时间戳随机字符串After encrypting to form a signature, it can be returned to the front end together,可以参考 JS-SDK使用权限签名算法
<?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 应该全局存储与更新,以下代码以写入到文件中做示例
        $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 = "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 = "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, 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);
    }
}

JS-SDK Signature Notes

  • Known by WeChat official,jsapiTicketaccess_token A call can be made once 2 小时内使用,也就是 7200 秒,So when we get this value,需要将其 缓存,Cached in the official documentation 7000 秒,To prevent unnecessary problems,So it's official 200
  • About why you want to cache these two values,主要是因为 同一个公众号 The upper limit of calling this value per day is 2000 次,如果不缓存,If the number of visits to your service that day exceeds 2000 次,因为没有缓存,limit will be reached,The service is no longer available
  • The official cache is placed jsapi_ticket.phpaccess_token.php 两个文件中的,Of course you can put inredismongodb 中,But it is not recommended to store in the database,easy to cause a lot I/O 开销
<?php
require_once "jssdk.php";
$jssdk = new JSSDK("yourAppID", "yourAppSecret");
$signPackage = $jssdk->GetSignPackage();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

</body>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
    /* * 注意: * 1. 所有的JS接口只能在公众号绑定的域名下调用,公众号开发者需要先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”. * 2. 如果发现在 Android 不能分享自定义内容,请到官网下载最新的包覆盖安装,Android 自定义分享接口需升级至 6.0.2.58 版本及以上. * 3. 常见问题及完整 JS-SDK 文档地址:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html * * 开发中遇到问题详见文档“附录5-常见错误及解决办法”解决,如仍未能解决可通过以下渠道反馈: * 邮箱地址:[email protected] * 邮件主题:【微信JS-SDK反馈】具体问题 * 邮件内容说明:用简明的语言描述问题所在,并交代清楚遇到该问题的场景,可附上截屏图片,微信团队会尽快处理你的反馈. */
    wx.config({
    
        debug: true,
        appId: '<?php echo $signPackage["appId"];?>',
        timestamp: <?php echo $signPackage["timestamp"];?>,
        nonceStr: '<?php echo $signPackage["nonceStr"];?>',
        signature: '<?php echo $signPackage["signature"];?>',
        jsApiList: [
            // 所有要调用的 API 都要加到这个列表中
        ]
    });
    wx.ready(function () {
    
        // 在这里调用 API
    });
</script>
</html>

自定义微信分享

  • 想要调用 JS-SDK 中的接口,必须先在 wx.configjsApiList add what you need to use API,不然无法使用
  • Often done in projects H5,for better sharing,Customization is required in WeChat分享的icon分享的标题shared profile跳转链接
  • Because the general shared information is initialized when the project is loaded,所以需要放到 ready 中进行初始化
  • 当然,If your shared information is changed,It is also possible to call the sharing interface through the click event

微信分享

wx.config({
    
    debug: true,
    appId: '<?php echo $signPackage["appId"];?>',
    timestamp: <?php echo $signPackage["timestamp"];?>,
    nonceStr: '<?php echo $signPackage["nonceStr"];?>',
    signature: '<?php echo $signPackage["signature"];?>',
    jsApiList: [
        'checkJsApi',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
    ]
});

wx.ready(function () {
    
    // 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口
    wx.onMenuShareTimeline({
    
	  title: '', // 分享标题
	  link: '', // 分享链接,该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
	  imgUrl: '', // 分享图标
	  success: function () {
    
		  	// 用户点击了分享后执行的回调函数
	  }
	}),
	
	// 获取“分享给朋友”按钮点击状态及自定义分享内容接口
	wx.onMenuShareAppMessage({
    
	  title: '', // 分享标题
	  desc: '', // 分享描述
	  link: '', // 分享链接,该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致
	  imgUrl: '', // 分享图标
	  type: '', // 分享类型,music、video或link,不填默认为link
	  dataUrl: '', // 如果 type 是music或video,则要提供数据链接,默认为空
	  success: function () {
    
	    	// 用户点击了分享后执行的回调函数
	  }
	});
	
	wx.onMenuShareWeibo({
    
	  title: '', // 分享标题
	  desc: '', // 分享描述
	  link: '', // 分享链接
	  imgUrl: '', // 分享图标
	  success: function () {
    
	  	// 用户确认分享后执行的回调函数
	  },
	  cancel: function () {
    
	  	// 用户取消分享后执行的回调函数
	  }
	});
});

Photo selection function

  • 有时候需要通过 JS-SDK Call the phone camera to take pictures,然后处理图片
  • It should be noted that the upload image interface,上传图片有效期 3 天,可用微信多媒体接口下载图片到自己的服务器
wx.config({
    
    debug: true,
    appId: '<?php echo $signPackage["appId"];?>',
    timestamp: <?php echo $signPackage["timestamp"];?>,
    nonceStr: '<?php echo $signPackage["nonceStr"];?>',
    signature: '<?php echo $signPackage["signature"];?>',
    jsApiList: [
        'checkJsApi',
        'chooseImage',
        'previewImage',
        'downloadImage',
        'getLocalImgData',
    ]
});

// 拍照或从手机相册中选图接口
wx.chooseImage({
    
  count: 1, // 默认9
  sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
  sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
  success: function (res) {
    
  var localIds = res.localIds; // 返回选定照片的本地 ID 列表,localId可以作为 img 标签的 src 属性显示图片
  }
});

// 预览图片接口
wx.previewImage({
    
  current: '', // 当前显示图片的 http 链接
  urls: [] // 需要预览的图片 http 链接列表
});

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

// 下载图片接口
wx.downloadImage({
    
  serverId: '', // 需要下载的图片的服务器端ID,由 uploadImage 接口获得
  isShowProgressTips: 1, // 默认为1,显示进度提示
  success: function (res) {
    
    var localId = res.localId; // 返回图片下载后的本地ID
  }
});

Record audio processing

  • 可以使用 JS-SDK 实现录音上传录音播放语音等功能,Can greatly increase user engagement in your project
  • For example, you can record a user's voice,It then automatically replies via a voice-recognition bot,再通过 播放语音功能 Play back the content of the reply,It simply formed a small game of you asking and answering
wx.config({
    
    debug: true,
    appId: '<?php echo $signPackage["appId"];?>',
    timestamp: <?php echo $signPackage["timestamp"];?>,
    nonceStr: '<?php echo $signPackage["nonceStr"];?>',
    signature: '<?php echo $signPackage["signature"];?>',
    jsApiList: [
        'checkJsApi',
        'startRecord',
        'stopRecord',
        'onVoiceRecordEnd',
        'playVoice',
        'pauseVoice',
        'stopVoice',
        'onVoicePlayEnd',
        'uploadVoice',
        'downloadVoice'
    ]
});

// 开始录音接口,Can be placed on the click event to trigger
wx.startRecord();

// 停止录音接口
wx.stopRecord({
    
  success: function (res) {
    
    var localId = res.localId;
  }
});

// 监听录音自动停止接口
wx.onVoiceRecordEnd({
    
	// 录音时间超过一分钟没有停止的时候会执行 complete 回调
  complete: function (res) {
    
	  var localId = res.localId;
	}
});

// 播放语音接口
wx.playVoice({
    
  localId: '' // 需要播放的音频的本地ID,由 stopRecord 接口获得
});

// 暂停播放接口
wx.pauseVoice({
    
  localId: '' // 需要暂停的音频的本地ID,由 stopRecord 接口获得
});

// 上传语音接口
wx.uploadVoice({
    
  localId: '', // 需要上传的音频的本地ID,由 stopRecord 接口获得
  isShowProgressTips: 1, // 默认为1,显示进度提示
  success: function (res) {
    
    var serverId = res.serverId; // 返回音频的服务器端ID
  }
});

获取地理位置

  • 可以通过 JS-SDK Get the latitude and longitude of the current user's location,In this way, users can recommend some surrounding consumption or something
  • Location information is also available,给用户推荐Some peripheral services such as personalized entertainment are very convenient

位置服务

// 使用微信内置地图查看位置接口
wx.openLocation({
    
  latitude: 0, // 纬度,浮点数,范围为90 ~ -90
  longitude: 0, // 经度,浮点数,范围为180 ~ -180.
  name: '', // 位置名
  address: '', // 地址详情说明
  scale: 1, // 地图缩放级别,整型值,范围从1~28.默认为最大
  infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转
});

// 获取地理位置接口
wx.getLocation({
    
  type: 'wgs84', // 默认为wgs84的 gps 坐标,如果要返回直接给 openLocation 用的火星坐标,可传入'gcj02'
  success: function (res) {
    
    var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
    var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180.
    var speed = res.speed; // 速度,以米/每秒计
    var accuracy = res.accuracy; // 位置精度
  }
});

微信摇一摇

  • If you want to develop some functions through WeChat Shake it yourself,可以使用 JS-SDK Shake function in
// Turn on Find Around ibeacon 设备接口
wx.startSearchBeacons({
    
  ticket:"",  //Shake the business around ticket , The system automatically adds it after the page link that is shaken out
  complete:function(argv){
    
    //Enables the callback function after the search is completed
  }
});

// Turn off Find Around ibeacon 设备接口
wx.stopSearchBeacons({
    
  complete:function(res){
    
    //Close the callback function after the search is completed
  }
});

// Monitor the surrounding ibeacon 设备接口
wx.onSearchBeacons({
    
  complete:function(argv){
    
    //回调函数,The list of related devices in the surrounding area registered by the merchant can be obtained in the form of an array
  }
});

微信扫一扫

  • If you want to call the WeChat scan function,可以使用 scanQRCode 接口
  • success 回调方法中,Get scan results,Then you can carry out secondary development by yourself through the scan results,是非常的方便的
// 调起微信扫一扫接口
wx.scanQRCode({
    
  needResult: 0, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
  scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
  success: function (res) {
    
    var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
  }
});

copyright notice
author[Geek Flying Rabbit],Please bring the original link to reprint, thank you.
https://en.hqmana.com/2022/235/202208231200360672.html

Random recommended