微信分享自定义分享链接图文

1、 绑定域名 先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”(就是发布用的那个域名)

2、获取access_token和生成签名

 1 <?php
 2 class WXShare {
 3     private $appId;
 4     private $appSecret;
 5 
 6     public function __construct($appId, $appSecret) {
 7         $this->appId = $appId;
 8         $this->appSecret = $appSecret;
 9     }
10 
11     public function getSignPackage() {
12         $jsapiTicket = $this->getJsApiTicket();
13 
14         // 注意 URL 一定要动态获取,不能 hardcode.
15         $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
16         $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
17         //二次分享会带form=,会导致签名错误,所以需要单独处理
18         $pos = strpos($url,'form=');
19         if($pos !== false){
20             $url = substr($url,0,$pos-1);
21         }
22 
23 
24         $timestamp = time();
25         $nonceStr = $this->createNonceStr();
26 
27         // 这里参数的顺序要按照 key 值 ASCII 码升序排序
28         $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
29 
30         $signature = sha1($string);
31 
32         $signPackage = array(
33             "appId"     => $this->appId,
34             "nonceStr"  => $nonceStr,
35             "timestamp" => $timestamp,
36             "url"       => $url,
37             "signature" => $signature,
38             "rawString" => $string
39         );
40         return $signPackage;
41     }
42 
43     private function createNonceStr($length = 16) {
44         $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
45         $str = "";
46         for ($i = 0; $i < $length; $i++) {
47             $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
48         }
49         return $str;
50     }
51 
52     private function getJsApiTicket() {
53         //将数据存储在redis,防止达到上限
54         $redis = PublicOperationRedis::getInstance();
55         if($redis->get($this->appId.":ticket")){
56             return $redis->get($this->appId.":ticket");
57         }
58         $accessToken = $this->getAccessToken();
59         $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
60         $res = json_decode($this->httpGet($url));
61         $ticket = $res->ticket;
62         if($ticket){
63             $redis->set($this->appId.":ticket",$ticket,7200);
64         }
65         return $ticket;
66     }
67 
68     private function getAccessToken() {
69         $redis = PublicOperationRedis::getInstance();
70         if($redis->get($this->appId)){
71             return $redis->get($this->appId);
72         }
73         $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
74         $res = json_decode($this->httpGet($url));
75         $access_token = $res->access_token;
76         if($access_token){
77             $redis->set($this->appId,$access_token,7200);
78         }
79         return $access_token;
80     }
81 
82     private function httpGet($url) {
83         $curl = curl_init();
84         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
85         curl_setopt($curl, CURLOPT_TIMEOUT, 500);
86         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
87         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
88         curl_setopt($curl, CURLOPT_URL, $url);
89 
90         $res = curl_exec($curl);
91         curl_close($curl);
92 
93         return $res;
94     }
95 }

 

3、编写js代码

  

<script type="text/javascript" src='https://res.wx.qq.com/open/js/jweixin-1.0.0.js'></script>
  <script type="text/javascript">
  wx.config({
    debug: false,
    appId: '{$signPackage["appId"]}',
    timestamp: '{$signPackage["timestamp"]}',
    nonceStr: '{$signPackage["nonceStr"]}',
    signature: '{$signPackage["signature"]}',
    jsApiList: [
        'checkJsApi',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
        'onMenuShareQZone'
    ]
  });
  </script>

 

wx.ready(function () {
        //分享到朋友圈
        wx.onMenuShareTimeline({
            title: "title",
            link:'url',
            imgUrl: 'pic', // 分享图标
            success: function () {
                // 分享成功执行此回调函数
               // alert('分享成功');
            },
            cancel: function () {
                //alert('分享失败');
            }
        });

        //分享给朋友
        wx.onMenuShareAppMessage({
            title: "title",
            link:'utl',
            desc: "desc",
            imgUrl: "pic", // 分享图标
            trigger: function (res) {
                // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回
            },
            success: function (res) {
                // 分享成功执行此回调函数
                //alert('已分享');
            },
            cancel: function (res) {
                alert('已取消');
            },
            fail: function (res) {
                //alert(JSON.stringify(res));
            }
        });
    });

 

以上为微信分享图文链接操作方式

posted on 2017-10-31 09:39  铁猛  阅读(2425)  评论(1编辑  收藏  举报

导航