微信网页分享-1.6.0版本

注:开发文档地址:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html

准备工作:

  1.先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。

  2.需要用到wx模块 引入 <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script> 文件

 

代码:

  前端

    第一步需要进行配置  

这里需要请求后端,实现后端生成签名填的参数 和 config验证的参数要一致

<?php

/*******************/
include_once('./common/jssdk.php');
 
$jsapi = new JSSDK(appid,appsecret);
$res = $jsapi->getSignPackage();   //获取js的token

?>

 

  wx.config({
      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
      appId: '', // 必填,公众号的唯一标识
      timestamp: <?php echo $res['timestamp']; ?>, // 必填,生成签名的时间戳
      nonceStr:'<?php echo $res["nonceStr"]; ?>', // 必填,生成签名的随机串
      signature: '<?php echo $res["signature"]; ?>',// 必填,签名
      jsApiList: [
          'updateAppMessageShareData',
          'onMenuShareTimeline',
          'onMenuShareAppMessage'
      ] // 必填,需要使用的JS接口列表
});

  第二步:config验证成功后

wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
        var url = '';
        //分享到朋友圈
        wx.onMenuShareTimeline({
            title: '分享标题',
            desc: '分享描述',
            link:  url, // 分享的url
            imgUrl:  'https://t.0797hr.com/static/top.jpg', // 分享的图标url
            trigger: function (res) {
//           alert(res)   /////注意苹果手机分享的时候要去掉alert事件,不然会出现莫名的弹框
            },
            success: function (res) {
          myresult(res);
            },
            cancel: function (res) {
            },
            fail: function (res) {
            }
        });
        //分享给朋友
        wx.onMenuShareAppMessage({
        title: '分享标题',
            desc: '分享描述',
            link:  url, //分享的url
            imgUrl: 'https://t.0797hr.com/static/top.jpg', // 图标url

            trigger: function (res) {
            },
            success: function (res) {
          //分享成功后执行 myresult(res); }, cancel:
function (res) { alert(2); }, fail: function (res) { alert(3); } }); });

wx.error(function(res){
  alert(res);
  // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
});

 

 

后端:api_ticket有时间,请求次数限制,需要在后端抓取后缓存下来(最容易出现问题是在合成签名) 接口签名验证工具:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign

class JSSDK {
    private $appId;
    private $appSecret;
 
    public function __construct($appId, $appSecret) {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }
 
    public function getSignPackage() {
        $jsapiTicket = $this->getJsApiTicket();
        $url = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        $timestamp = time();
        $nonceStr = $this->createNonceStr();
 
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        
        // $string = "noncestr=$nonceStr&jsapi_ticket=$jsapiTicket&timestamp=$timestamp&url=$url"; 这个顺序是在1.6.0文档找的但是不对
        $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(file_get_contents("./log/jsapi_ticket.json"));
        if ($data->expire_time < time()) {
            $accessToken = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$accessToken&type=jsapi";
            $res = json_decode($this->httpGet($url));

            $ticket = $res->ticket;
            if ($ticket) {
                @$data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $fp = fopen("./log/jsapi_ticket.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }
        return $ticket;
    }
 
    private function getAccessToken() {
        // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
        $data = json_decode(file_get_contents("./log/access_token.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("./log/access_token.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } 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);
        curl_setopt($curl, CURLOPT_URL, $url);
 
        $res = curl_exec($curl);
        curl_close($curl);
 
        return $res;
    }
}

 

 

posted @ 2020-08-13 18:26  时间掉飞机  阅读(1060)  评论(0编辑  收藏  举报