老莫的笔记本  
  
查看: 608|回复: 0

laravel 接 微信签名-

[复制链接]

662

主题

878

帖子

5133

积分

超级版主

Rank: 8Rank: 8

积分
5133
发表于 2021-9-7 16:05:06 | 显示全部楼层 |阅读模式
需求: 在微信公众号的网页里面 点击一下 调起导航 ,从而调起第三方APP  腾讯或者百度的高德地图。
框架: laravel + easywechat + 微信公众号 网页开发模式

明确:
1.  网页并不能在 微信中 直接打开第三方APP ,而是进入微信的地图页,由微信自己去调用 手机里的APP 。
2. 微信跳转 是需要微信签名的, 微信签名的获取,是一个前后台交互的过程。 前台负责传值[主要就是 openid 和 URL ],后端负责 处理,获取签名 然后再返回给前端. 前端形成配置项后使用。
3.URL 一定得是前端的URL,也就是你在哪个页面 使用微信的部分功能,就把当前页面的URL传递给后端 。

  1.     /**
  2.      * 微信签名获取
  3.      */
  4.     public function getSignature( Request $request )
  5.     {
  6.         // 先判断cache
  7.         $jsapiTicket =$this->getTicket() ;
  8.         
  9.         $nonceStr = $this->createNonceStr();
  10.         
  11.         $timestamp = time();
  12.         
  13.         // var test = window.location.href; 这样就可以获取当前页面url,最近我写个微信功能也这样取的。[我的想法是前端的URL当前页,传给后台]
  14.         // 签名用的url必须是调用JS接口页面的完整URL”
  15.         // 注意 URL 一定要动态获取,不能 hardcode.
  16.         $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
  17.         // $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  18.         $url = $request->input('url');
  19.         
  20.         // 这里参数的顺序要按照 key 值 ASCII 码升序排序
  21.         $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url";
  22.         
  23.         $signature = sha1($string);

  24.         $config = $this->sendConfig();
  25.         
  26.         // dd($config['app_id']);

  27.         $signPackage = array(
  28.           "appId"     => $config['app_id'],
  29.           "nonceStr"  => $nonceStr,
  30.           "timestamp" => $timestamp,
  31.           "url"       => $url,
  32.           "signature" => $signature,
  33.           "rawString" => $string
  34.         );
  35.         return [
  36.             'code'=>0,
  37.             'message'=> '获取微信配置成功',
  38.             'data'=>$signPackage
  39.         ];
  40.         // return $signPackage;

  41.     }

  42.     public function getTicket()
  43.     {
  44.         if(Cache::has('ticket')){

  45.             return Cache::get('ticket');

  46.         }else{
  47.             
  48.             $config = $this->sendConfig();

  49.             $app = Factory::officialAccount($config);
  50.    
  51.             $accessToken = $app->access_token;
  52.    
  53.             $token = $accessToken->getToken(true); // 强制重新从微信服务器获取 token

  54.             $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='. $token['access_token'].'&type=jsapi';
  55.             
  56.                  //初始化
  57.             $ticketArr = $this->curl_get($url);
  58.             
  59.             $ticket = $ticketArr['ticket'];

  60.             Cache::put('ticket', $ticket ,now()->addMinutes(60));
  61.         
  62.             return $ticket;

  63.         }
  64.       
  65.     }


  66.     public function curl_get($url)
  67.     {
  68.        $headerArray =array("Content-type:application/json;","Accept:application/json");
  69.         $ch = curl_init();
  70.         curl_setopt($ch, CURLOPT_URL, $url);
  71.         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  72.         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  73.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  74.         curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
  75.         $output = curl_exec($ch);
  76.         curl_close($ch);
  77.         $output = json_decode($output,true);
  78.         return $output;
  79.     }
  80.    
  81.     /**
  82.      *  生成随机数  
  83.     */
  84.    
  85.     public function createNonceStr($length = 16) {
  86.         $returnStr='';

  87.         $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

  88.         for($i = 0; $i < $length; $i ++) {
  89.             
  90.             $returnStr .= $pattern {mt_rand ( 0, 61 )};

  91.         }
  92.         return $returnStr;
  93.     }
复制代码
上面是后端PHP的。

下面是前端的内容
这里只放几个react 的 reducx 几个片段 ,大致就是发送当前的URL给PHP 之后 拿到返回数据 然后配置, 以及配置完之后在任意位置使用

  1. export const actionGetWechatConf = (JsonDate) => ({
  2.     type: GetWechatConf,
  3.     value: JsonDate
  4. })
  5. export const funGetWechatConf = (value) => {


  6.     let url = webServer + '/api/sd/get/wxc';
  7.    
  8.     return (dispatch) => {

  9.         axios.get(url, {
  10.             params: value,
  11.             headers: {
  12.                 'token': localStorage.getItem('token')
  13.             }
  14.         }).then((res) => {
  15.             let data = res.data;  // 注意了 这里不能少一层
  16.             checkRes(res.data);
  17.             // 派发action
  18.             dispatch(actionGetWechatConf(data));
  19.         })
  20.     }
  21. }
复制代码
  1.             Wx.config({
  2.                 debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
  3.                 appId: allStore.weChatConf.appId, // 必填,公众号的唯一标识
  4.                 timestamp: allStore.weChatConf.timestamp, // 必填,生成签名的时间戳
  5.                 nonceStr: allStore.weChatConf.nonceStr, // 必填,生成签名的随机串
  6.                 signature: allStore.weChatConf.signature,// 必填,签名,见附录1
  7.                 jsApiList: [
  8.                 'openLocation',
  9.                 'onMenuShareTimeline'
  10.                 ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
  11.             })
复制代码

  1.     // 点击打开微信位置功能
  2.     gowechatAddress()
  3.     {
  4.         // if( !this.state.weChatConf){
  5.         //     alert('系统提示', '地图初始化中请稍后点击', [
  6.         //         { text: '我知道了', onPress: () => console.log('cancel'), style: 'default' },
  7.         //     ]);
  8.         //     return false;
  9.         // }
  10.         if(this.state.orderInfoData)
  11.         {
  12.             let s = this.state.orderInfoData;
  13.             console.log(s.user_lat )
  14.             console.log(s.user_lon )
  15.             console.log(s.user_address )
  16.             Wx.openLocation({
  17.                 latitude: s.user_lat, // 纬度,浮点数,范围为90 ~ -90
  18.                 longitude: s.user_lon, // 经度,浮点数,范围为180 ~ -180。
  19.                 name: s.user_address, // 位置名
  20.                 address: '客户所在位置', // 地址详情说明
  21.                 scale: 10, // 地图缩放级别,整形值,范围从1~28。默认为最大
  22.             });
  23.         }
  24.         


  25.     }
复制代码





参考地址: 当时看了很多,谈不上有没有作用。 大部分都是参考下面的逻辑

        // http://www.jjyc.org/h/182281.html  获取签名配置
    // https://blog.csdn.net/qq_40654664/article/details/90291509 获取签名配置
    // https://blog.csdn.net/weixin_343 ... 7Edefault-1.control
    // https://blog.csdn.net/roamingcode/article/details/81773618  触类旁通
    // https://qydev.weixin.qq.com/wiki ... K%E6%8E%A5%E5%8F%A3  微信接口文档
    // https://blog.csdn.net/dadsfasfadf/article/details/109443378   react实现微信分享
        // https://www.cnblogs.com/pxjbk/p/11823559.html  PHP微信SDK经典运算
               




回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表