ThinkPHP5怎么集成JS-SDK实现微信自定义分享功能

后端开发   发布日期:2023年08月18日   浏览次数:767

今天小编给大家分享一下ThinkPHP5怎么集成JS-SDK实现微信自定义分享功能的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

Jssdk类库

1、文件名及位置

名字:Jssdk.php
位置:extendutilJssdk.php

2、代码

  1. <?php
  2. namespace util;
  3. class Jssdk {
  4. protected $appid = 'xxxx';
  5. protected $secret = 'xxxx';
  6. /**
  7. * 获取access_token方法
  8. */
  9. public function getAccessToken(){
  10. //定义文件名称
  11. $name = 'token_' . md5($this->appid . $this->secret);
  12. //定义存储文件路径
  13. // $filename = __DIR__ . '/cache/' . $name . '.php';
  14. $filename = '../runtime/temp/' . $name . '.php';
  15. //判断文件是否存在,如果存在,就取出文件中的数据值,如果不存在,就向微信端请求
  16. if (is_file($filename) && filemtime($filename) + 7100 > time()){
  17. $result = include $filename;
  18. //定义需要返回的内容$data
  19. $data = $result['access_token'];
  20. }else{
  21. // https请求方式: GET
  22. // https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
  23. // 调用curl方法完成请求
  24. $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appid.'&secret=' . $this->secret;
  25. $result = $this->curl($url);
  26. //将返回得到的json数据转成php数组
  27. $result = json_decode($result,true);
  28. //将内容写入文件中
  29. file_put_contents($filename,"<?php
  30. return " . var_export($result,true) . ";
  31. ?>");
  32. //定义需要返回的内容
  33. $data = $result['access_token'];
  34. }
  35. //将得到的access_token的值返回
  36. return $data;
  37. }
  38. /**
  39. *
  40. * 获取临时票据方法
  41. *
  42. * @return mixed
  43. */
  44. public function getJsapiTicket(){
  45. //存入文件中,定义文件的名称和路径
  46. $name = 'ticket_' . md5($this->appid . $this->secret);
  47. //定义存储文件路径
  48. //$filename = __DIR__ . '/cache/' . $name . '.php';
  49. $filename = '../runtime/temp/' . $name . '.php';
  50. //判断是否存在临时票据的文件,如果存在,就直接取值,如果不存在,就发送请求获取并保存
  51. if (is_file($filename) && filemtime($filename) + 7100 > time()){
  52. $result = include $filename;
  53. }else{
  54. //定义请求地址
  55. $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$this
  56. ->getAccessToken().'&type=jsapi';
  57. //使用curl方法发送请求,获取临时票据
  58. $result = $this->curl($url);
  59. //转换成php数组
  60. $result = json_decode($result,true);
  61. //将获取到的值存入文件中
  62. file_put_contents($filename,"<?php
  63. return " . var_export($result,true) . ";
  64. ?>");
  65. }
  66. //定义返回的数据
  67. $data = $result['ticket'];
  68. //将得到的临时票据结果返回
  69. return $data;
  70. }
  71. /**
  72. * 获取签名方法
  73. */
  74. public function sign(){
  75. //需要定义4个参数,分别包括随机数,临时票据,时间戳和当前url地址
  76. $nonceStr = $this->makeStr();
  77. $ticket = $this->getJsapiTicket();
  78. $time = time();
  79. //组合url
  80. //$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
  81. $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
  82. //将4个参数放入一个数组中
  83. $arr = [
  84. 'noncestr=' . $nonceStr,
  85. 'jsapi_ticket=' . $ticket,
  86. 'timestamp=' . $time,
  87. 'url=' . $url
  88. ];
  89. //对数组进行字段化排序
  90. sort($arr,SORT_STRING);
  91. //对数组进行组合成字符串
  92. $string = implode('&',$arr);
  93. //将字符串加密生成签名
  94. $sign = sha1($string);
  95. //由于调用签名方法的时候不只需要签名,还需要生成签名的时候的随机数,时间戳,所以我们应该返回由这些内容组成的一个数组
  96. $reArr = [
  97. 'appId' => $this->appid,
  98. 'timestamp' => $time,
  99. 'nonceStr' => $nonceStr,
  100. 'signature' => $sign,
  101. 'url' => $url
  102. ];
  103. //将数组返回
  104. return $reArr;
  105. }
  106. /**
  107. *
  108. * 生成随机数
  109. *
  110. * @return string
  111. */
  112. protected function makeStr(){
  113. //定义字符串组成的种子
  114. $seed = 'www512wayanbao1qasxianrendong5tgblaochaguan8ik9500net';
  115. //通过循环来组成一个16位的随机字符串
  116. //定义一个空字符串 用来接收组合成的字符串内容
  117. $str = '';
  118. for ($i = 0;$i < 16; $i++){
  119. //定义一个随机数
  120. $num = rand(0,strlen($seed) - 1);
  121. //循环连接随机生成的字符串
  122. $str .= $seed[$num];
  123. }
  124. //将随机数返回
  125. return $str;
  126. }
  127. /**
  128. *
  129. * 服务器之间请求的curl方法
  130. *
  131. * @param $url 请求地址
  132. * @param array $field post参数
  133. * @return string
  134. */
  135. public function curl($url,$field = []){
  136. //初始化curl
  137. $ch = curl_init();
  138. //设置请求的地址
  139. curl_setopt($ch,CURLOPT_URL,$url);
  140. //设置接收返回的数据,不直接展示在页面
  141. curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  142. //设置禁止证书校验
  143. curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
  144. curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
  145. //判断是否为post请求方式,如果传递了第二个参数,就代表是post请求,如果么有传递,第二个参数为空,就是get请求
  146. if (!empty($field)){
  147. //设置请求超时时间
  148. curl_setopt($ch,CURLOPT_TIMEOUT,30);
  149. //设置开启post
  150. curl_setopt($ch,CURLOPT_POST,1);
  151. //传递post数据
  152. curl_setopt($ch,CURLOPT_POSTFIELDS,$field);
  153. }
  154. //定义一个空字符串,用来接收请求的结果
  155. $data = '';
  156. if (curl_exec($ch)){
  157. $data = curl_multi_getcontent($ch);
  158. }
  159. //关闭curl
  160. curl_close($ch);
  161. //将得到的结果返回
  162. return $data;
  163. }
  164. }
  165. //测试获取access_token值的方法
  166. //$obj = new Wx();
  167. //$data = $obj->getAccessToken();
  168. //echo $data;
  169. //测试获取jsapiticket方法
  170. //$obj = new Wx();
  171. //$data = $obj->getJsapiTicket();
  172. //echo $data;
  173. //测试生成签名方法
  174. //$obj = new Wx();
  175. //$data = $obj->sign();
  176. //echo '<pre>';
  177. //print_r($data);
  178. ?>

后台控制器处理

  1. <?php
  2. namespace appindexcontroller;
  3. use thinkController;
  4. use thinkDb;
  5. use appadminmodelMenu;
  6. use utilJssdk;
  7. class Index extends Controller {
  8. public function demo(){
  9. $id = input('id',0);//ID
  10. $catid = input('catid',0);//分类ID
  11. $modelInfo = getModInfoById($catid);
  12. $info = Db::name($modelInfo['tablename'])->where('id',$id)->find();
  13. $catinfo = getCatInfoById($catid);
  14. $p_catname = getCatInfoById($catinfo['parentid'],'catname');
  15. $obj = new Jssdk();
  16. $data = $obj->sign();
  17. $this->assign('infos',$info);
  18. $this->assign('catids',$catid);
  19. $this->assign('catnames',$catinfo['catname']);
  20. $this->assign('p_catnames',$p_catname);
  21. $this->assign('data',$data);
  22. return view('../application/index/view/default/index/' . $modelInfo['show_template']);
  23. }
  24. }
  25. ?>

微信事件响应

  1. <script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
  2. <script type="text/javascript">
  3. // 通过config接口注入权限验证配置
  4. wx.config({
  5. debug: false,
  6. appId: '{$data.appId}',
  7. timestamp: '{$data.timestamp}',
  8. nonceStr: '{$data.nonceStr}',
  9. signature: '{$data.signature}',
  10. jsApiList: [
  11. 'onMenuShareTimeline',
  12. 'onMenuShareAppMessage'
  13. ]
  14. });
  15. // 通过ready接口处理成功验证
  16. wx.ready(function(){
  17. // 分享到朋友圈
  18. wx.onMenuShareTimeline({
  19. title: '{$info.title}',
  20. link: '{$data.url}',
  21. imgUrl: 'http://m.psnav.com/uploads/image/{$info.thumb}',
  22. success: function () {
  23. // 用户点击了分享后执行的回调函数
  24. }
  25. });
  26. // 分享给朋友
  27. wx.onMenuShareAppMessage({
  28. title: '{$info.title}',
  29. desc: '{$info.description}',
  30. link: '{$data.url}',
  31. imgUrl: 'http://m.psnav.com/uploads/image/{$info.thumb}',
  32. type: 'link', // 分享类型,music、video或link,不填默认为link
  33. dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
  34. success: function () {
  35. // 用户点击了分享后执行的回调函数
  36. }
  37. });
  38. });
  39. </script>

全部分享接口

  1. <script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
  2. <script type="text/javascript">
  3. // 通过config接口注入权限验证配置
  4. wx.config({
  5. debug: true,
  6. appId: '{$data.appId}',
  7. timestamp: '{$data.timestamp}',
  8. nonceStr: '{$data.nonceStr}',
  9. signature: '{$data.signature}',
  10. jsApiList: [
  11. 'onMenuShareTimeline',
  12. 'onMenuShareAppMessage',
  13. 'onMenuShareQQ',
  14. 'onMenuShareWeibo',
  15. 'onMenuShareQZone'
  16. ]
  17. });
  18. // 通过ready接口处理成功验证
  19. wx.ready(function(){
  20. // 分享到朋友圈
  21. wx.onMenuShareTimeline({
  22. title: '{$info.title}',
  23. link: '{$data.url}',
  24. imgUrl: 'http://m.psnav.com/uploads/image/{$info.thumb}',
  25. success: function () {
  26. // 用户点击了分享后执行的回调函数
  27. }
  28. });
  29. // 分享给朋友
  30. wx.onMenuShareAppMessage({
  31. title: '{$info.title}',
  32. desc: '{$info.description}',
  33. link: '{$data.url}',
  34. imgUrl: 'http://m.psnav.com/uploads/image/{$info.thumb}',
  35. type: 'link', // 分享类型,music、video或link,不填默认为link
  36. dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
  37. success: function () {
  38. // 用户点击了分享后执行的回调函数
  39. }
  40. });
  41. // 分享到QQ
  42. wx.onMenuShareQQ({
  43. title: '{$info.title}',
  44. desc: '{$info.description}',
  45. link: '{$data.url}',
  46. imgUrl: 'http://m.psnav.com/uploads/image/{$info.thumb}',
  47. success: function () {
  48. // 用户确认分享后执行的回调函数
  49. },
  50. cancel: function () {
  51. // 用户取消分享后执行的回调函数
  52. }
  53. });
  54. // 分享到腾讯微博
  55. wx.onMenuShareWeibo({
  56. title: '{$info.title}',
  57. desc: '{$info.description}',
  58. link: '{$data.url}',
  59. imgUrl: 'http://m.psnav.com/uploads/image/{$info.thumb}',
  60. success: function () {
  61. // 用户确认分享后执行的回调函数
  62. },
  63. cancel: function () {
  64. // 用户取消分享后执行的回调函数
  65. }
  66. });
  67. // 分享到QQ空间
  68. wx.onMenuShareQZone({
  69. title: '{$info.title}',
  70. desc: '{$info.description}',
  71. link: '{$data.url}',
  72. imgUrl: 'http://m.psnav.com/uploads/image/{$info.thumb}',
  73. success: function () {
  74. // 用户确认分享后执行的回调函数
  75. },
  76. cancel: function () {
  77. // 用户取消分享后执行的回调函数
  78. }
  79. });
  80. });
  81. </script>

以上就是ThinkPHP5怎么集成JS-SDK实现微信自定义分享功能的详细内容,更多关于ThinkPHP5怎么集成JS-SDK实现微信自定义分享功能的资料请关注九品源码其它相关文章!