uniapp 使用微信jssdk 调起 地图,扫码,分享等功能

引入文件:

jweixin-module/lib/index.js

这个可以 随便找个目录 执行 npm install jweixin-module --save 就可以获得,然后从 node_modules 目录下找到 jweixin-module 目录复制到 components 目录下就可以了。或者直接下载

链接: https://pan.baidu.com/s/1gfXn42fHO9Ch6ruOAY8GKw 提取码: gvfw 


核心代码:

com.js

import jweixin from '@/components/jweixin-module/lib/index.js';

const apiUrl = '/api';
const siteUrl = 'http://10.10.34.116:8080';

const shareData = {
	title: "分享标题",
	desc: "分享描述",
	link: "https://10.10.34.116:8080/h5",
	imgUrl: 'https://10.10.34.116:8080/assets/images/share.png'
};

const openPage = function(path){
	if (getCurrentPages().length > 9) {
		uni.reLaunch({
		    url: path
		})
	} else {
		uni.navigateTo({
		    url: path
		});
	}
}

const checkMobile = function(tel){
    var phoneReg = tel.match(/^1[3-9]\d{9}$/);
    if(phoneReg){
        return 1;
    }else{
        return 0;
    }
};

//判断是否在微信中  
const isWechat = function() {
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/micromessenger/i) == 'micromessenger') {
		// console.log('是微信客户端')
		return true;
	} else {
		// console.log('不是微信客户端')
		return false;
	}
};


//获取微信JSSDK授权
const getWxConfig = function(){
	var that = this;
	if (!that.isWechat()) {
		uni.showToast({
			title: '请在微信里操作',
			icon: 'none'
		});
		return;
	}
	uni.request({
		url: that.siteUrl+'/login/index',
		header: {
			'content-type': 'application/x-www-form-urlencoded'
		},
		data: {
			do: 'jssdk',
			url: window.location.href,//当前页面的域名
		},
		method: 'GET',
		success: (res) => {
			console.log('getWxConfig->',res.data);
			jweixin.config({
				debug: false,
				appId: res.data.appId,
				timestamp: res.data.timestamp,
				nonceStr: res.data.nonceStr,
				signature: res.data.signature,
				jsApiList: [
					'scanQRCode',
					'checkJsApi',
					'onMenuShareTimeline',
					'onMenuShareAppMessage',
					'openLocation'
				]
			})
			jweixin.ready(function() {
				// 用户检查接口权限用 比如 想用调起扫码功能 scanQRCode 这部分代码上线的时候需要屏蔽,否则老弹窗
				jweixin.checkJsApi({
					jsApiList: ['scanQRCode'],
					success: function(res) {
						// 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
					}
				});
				//分享给朋友接口  
				jweixin.onMenuShareAppMessage(that.shareData);
				//分享到朋友圈接口  
				jweixin.onMenuShareTimeline(that.shareData);
			});
			jweixin.error(function(res){
				console.log(res,'接口验证失败');
			});
		}
	});
};


export default {  
  apiUrl,
  siteUrl,
  openPage,
  checkMobile,
  formatDate,
  isWechat,
  shareData,
  getWxConfig,
  jweixin
}


使用方法:

引入自定义类 com

import com from '@/common/com.js';

onLoad里 调用

com.getWxConfig();


调起分享 默认把分享封装到com类里了,当然也可以每个页面单独配置 

注意 wx.onMenuShareAppMessage() 调用换成 com.jweixin.onMenuShareAppMessage() 

var shareData = {
	title: "分享标题",
	desc: "分享描述",
	link: "https://10.10.34.116:8080/h5",
	imgUrl: 'https://10.10.34.116:8080/assets/images/share.png'
};
//分享给朋友接口  
com.jweixin.onMenuShareAppMessage(shareData);
//分享到朋友圈接口  
com.jweixin.onMenuShareTimeline(shareData);


调起扫码 wx.scanQRCode:

com.jweixin.scanQRCode({
        // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
	needResult: 1,
	// 可以指定扫二维码还是一维码,默认二者都有
	scanType: ["qrCode", "barCode"],
	success: function(res) {
	   console.log(res);
           if (res.errMsg == 'scanQRCode:ok') {
	      console.log('扫码结果:',res.resultStr);
	   }
	}
});


调起微信地图导航 wx.openLocation

openMap(lng, lat, name, place) {
	
	com.jweixin.openLocation({
	        // 纬度,必须浮点数,范围为90 ~ -90
		latitude: parseFloat(lat),
		// 经度,必须浮点数,范围为180 ~ -180。
		longitude: parseFloat(lng),
		// 位置名
		name: name,
		// 地址详情说明
		address: place ? place: '',
		// 地图缩放级别,整型值,范围从1~28。默认为最大
		scale: 15,
		//国标02
		type: 'gcj02',
		// 在查看位置界面底部显示的超链接,可点击跳转
		infoUrl: ''
	})
},


后台获取微信授权接口:Thinkphp5.x
Jssdk.php 封装好的类 放Tp站点更目录下 applictation/common/library/Jssdk.php 可以放别的位置,注意修改命名空间

<?php
namespace app\common\library;
class Jssdk {
    private $appId;
    private $appSecret;
    private $tempPath = ROOT_PATH . '/../runtime/temp/';

    public function __construct($appId, $appSecret) {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }

    public function getSignPackage($url = '') {
        $jsapiTicket = $this->getJsApiTicket();
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = $url ? $url : "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        $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;
    }
    // jsapi_ticket
    private function getJsApiTicket() {
        // 先判断./jsapi_ticket_xgNcGqAcP5oEzXUgx.json文件是否存在,不存在先创建
        if(is_file($this->tempPath."/jsapi_ticket_xgNcGqAcP5oEzXUgx.json")){
            $data = json_decode(file_get_contents($this->tempPath."/jsapi_ticket_xgNcGqAcP5oEzXUgx.json"));
            if ($data->expire_time < time()) {
                $accessToken = $this->getAccessToken();
                $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;
                    $fp = fopen($this->tempPath."/jsapi_ticket_xgNcGqAcP5oEzXUgx.json", "w");
                    fwrite($fp, json_encode($data));
                    fclose($fp);
                }
            } else {
                $ticket = $data->jsapi_ticket;
            }
        }else{
            $accessToken = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpGet($url));
            $ticket = $res->ticket;
            $data=(object)[];
            if ($ticket) {
                $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $fp = fopen($this->tempPath."/jsapi_ticket_xgNcGqAcP5oEzXUgx.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        }
        return $ticket;
    }
    // access_token
    private function getAccessToken() {
        // 先判断./access_token_xgNcGqAcP5oEzXUgx.json文件是否存在,不存在先创建
        if(is_file($this->tempPath."/access_token_xgNcGqAcP5oEzXUgx.json")){
            $data = json_decode(file_get_contents($this->tempPath."/access_token_xgNcGqAcP5oEzXUgx.json"));
            if ($data->expire_time < time()) {
                $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;
                    $fp = fopen($this->tempPath."/access_token_xgNcGqAcP5oEzXUgx.json", "w");
                    fwrite($fp, json_encode($data));
                    fclose($fp);
                }
            } else {
                $access_token = $data->access_token;
            }
        }else{
            $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;
            $data=(object)[];
            if ($access_token) {
                $data->expire_time = time() + 7000;
                $data->access_token = $access_token;
                $fp = fopen($this->tempPath."/access_token_xgNcGqAcP5oEzXUgx.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        }
        return $access_token;
    }

    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }
}


在controller里调用

引入类 use app\common\library\Jssdk;

调用:

$jssdk = new Jssdk("已认证服务号appId", "secret密钥");//登陆公众账号后台获取
$signPackage = $jssdk->getSignPackage($wxurl);
echo(json_encode($signPackage));
exit();