Thinkphp5.1调用微信扫一扫实例,学会再也不怕客户在微信提的奇葩要求了

哎!苦于客户一直要求,官方文档看起来又蛋疼,磨了一个下午整理出一套试用Thinkphp5.1 调用微信扫一扫示例

别小瞧这些代码哦,它们能帮你实现几乎所有的微信功能_

示例地址:http://spt.zmtek.net/Wxshop/Wxtest/options (手机微信打开)

1 先在Thinkphp – Vendor 目录下面创建WxJDK文件夹,然后在创建文件JSSDK.php.

<?php

namespace WxJDK;

class JSSDK

{

    //公众号appid ,公众号开发配置处可查看

    public    $appId;

//公众号appi , 公众号开发配置处可查看

    private $appSecret;

/**

    * @name        初始化参数

    * @author        cq <just_leaf@foxmail.com>

    * @copyright    zydbbt 2018-10-27

*/

    public function __construct($appId ,$appSecret ){

        $this    -> appId            = $appId;

$this    -> appSecret        = $appSecret;

}

    /**

    * @name        获取accessToken

    * @author        cq <just_leaf@foxmail.com>

    * @copyright    zydbbt 2018-10-27

*/

    public function getAcc(){

        return $this -> getAccessToken();

}

    /**

    * @name        获取config接口注入权限验证配置

    * @author        cq <just_leaf@foxmail.com>

    * @copyright    zydbbt 2018-10-27

*/

    public function getWxConfig(){

        # - 获取 jsapi_ticket

        $jsapiTicket = $this -> getJsApiTicket();

# - 获取调用页面的url

        $protocol = (!empty($_SERVER['HTTPS'])&& $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443)? "https://" : "http://";

$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

# - 时间戳

        $timestamp = time();

# - 获取随机字符串

        $nonceStr = $this -> createNonceStr();

# - 这里参数的顺序要按照 key 值 ASCII 码升序排序

# - 亦可把参数以数组存值,ksort() - 以升序对关联数组进行排序

        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

# - sha1获取签名

        $signature = sha1($string);

# - 页面所需注入参数

        $WxConfig = array(

"appId"    => $this -> appId,

"nonceStr"  => $nonceStr,

"timestamp" => $timestamp,

"url"      => $url,

"signature" => $signature,

"rawString" => $string

        );

# - 返回

        return $WxConfig;

}

    /**

    * @name        获取JsApiTicket

    * @author        cq <just_leaf@foxmail.com>

    * @copyright    zydbbt 2018-10-27

*/

    private function getJsApiTicket(){

        # - 判断缓存

        $ticket = session('ticket');

if(!$ticket){

            # - 获取

            $accessToken = $this->getAccessToken();

# - 获取Ticket

# - 如果是企业号用以下 URL 获取 ticket

            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";

# - get请求,转换数组

            $result = json_decode($this->httpGet($url),true);

$ticket = $result['ticket'];

# - 全局缓存

            if ($ticket){

                # - 官方返回

# - {

# -        "errcode":0,

# -        "errmsg":"ok",

# -        "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",

# -    "expires_in":7200

# - }

//                session('ticket',$ticket,$result['expires_in']);

                session('ticket',$ticket);

}

}

        # - 返回

        return $ticket;

}

    /**

    * @name        获取AccessToken

    * @author        cq <just_leaf@foxmail.com>

    * @copyright    zydbbt 2018-10-27

*/

    private function getAccessToken(){

        # - 判断缓存

        $access_token = session('accesToken');

if(!$access_token){

            # - 如果是企业号用以下URL获取access_token

            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";

# - get请求,转换数组

            $result = json_decode($this->httpGet($url),true);

$access_token = $result['access_token'];

# - 全局缓存

            if ($access_token){

//                session('accesToken',$result['access_token'],$result['expires_in']);

                session('accesToken',$result['access_token']);

}

}

        # - 返回

        return $access_token;

}

    /**

    * @name        GET请求

    * @author        cq <just_leaf@foxmail.com>

    * @copyright    zydbbt 2018-10-27

*/

    private function httpGet($url){

        # - 初始化

        $curl = curl_init();

# - 为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,必须使用下面2行代码打开ssl安全校验。

# - 如果在部署过程中代码在此处验证失败,请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。

        curl_setopt($curl,CURLOPT_URL,$url);

curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);

curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);

curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);

curl_setopt($curl,CURLOPT_TIMEOUT,500);

# - 请求

        $res = curl_exec($curl);

//        $res = json_decode($res, true);

# - 关闭

        curl_close($curl);

# - 返回

        return $res;

}

    /**

    * @name        POST请求

    * @author        cq <just_leaf@foxmail.com>

    * @copyright    zydbbt 2018-10-27

*/

    private function httpPost($url,$query_data){

        # - 初始化

        $curl = curl_init();

# - 为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,必须使用下面2行代码打开ssl安全校验。

# - 如果在部署过程中代码在此处验证失败,请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。

        curl_setopt($curl,CURLOPT_URL,$url);

curl_setopt($curl,CURLOPT_POSTFIELDS,$query_data);

curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);

curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);

curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);

curl_setopt($curl,CURLOPT_TIMEOUT,500);

# - 请求

        $res = curl_exec($curl);

//        $res = json_decode($res, true);

# - 关闭

        curl_close($curl);

# - 返回

        return $res;

}

    /**

    * @name        产生随机字符串

    * @author        cq <just_leaf@foxmail.com>

    * @copyright    zydbbt 2018-10-27

*/

    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;

}

    public function getCommodityInfo($sub){

//聚合数据接口

# - 如果是企业号用以下URL获取access_token

        $url = "http://feedback.api.juhe.cn/ISBN?key=c74a5cde7c1e58709624454f18447a54&sub=".$sub;

# - get请求,转换数组

        $result = json_decode($this->httpGet($url),true);

halt($result);

}

}

2 把网站的Ip 授权,不然无法获取access_token值,那么jspai_ticket也将无法获取

使用方法看下列代码:

php:action如下

namespace app\index\controller;

use app\common\controller\Base;

use think\Loader;

class Smsb extends Base

{

    public function index()

{

        # 公众号获取

        $appid = config('wechat')['wechat_options']['appid'];

# 公众号获取

        $appSecret = config('wechat')['wechat_options']['appsecret'];

# 实例化

        $wx = new \WxJDK\JSSDK($appid,$appSecret);

# 获取参数

        $info = $wx-> getWxConfig();

$info['url']=str_replace('http://','',$info['url']);

# 传参页面

        $this -> assign('wxConfig',$info);

return $this->fetch('');

}

  public function WeChat()

{

        return ['appId'=>config('WeChat')['appId'],'timestamp'=>time(),'noncestr'=>'123456','signature'=>''];

}

    public function sp(){

        # 公众号获取

        $appid = config('wechat')['wechat_options']['appid'];

# 公众号获取

        $appSecret = config('wechat')['wechat_options']['appsecret'];

$wx = new \WxJDK\JSSDK($appid,$appSecret);

$wx->getCommodityInfo(input('ISBN'));

return $this->fetch('index');

}

    public function hello($name = 'ThinkPHP5')

{

        return 'hello,' . $name;

}

}



html:页面如下

<!DOCTYPE html>

<html>

  <head>

      <meta charset="utf-8" />

      <title></title>

      <script src="/static/js/jquery-1.8.3.min.js" type="text/javascript" charset="utf-8"></script>

      <script src="/static/js/jweixin-1.4.0.js" type="text/javascript" charset="utf-8"></script>

  </head>

  <body>

      <a class="weui-btn weui-btn_primary submit-btn" id="wxcode" type="button">扫一扫</a>

  <div id="content"></div>

  </body>

</html>

<script>

  wx.config({

      // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。

      debug: false,

// 必填,公众号的唯一标识

      appId: "{$wxConfig.appId}",

// 必填,生成签名的时间戳

      timestamp:"{$wxConfig.timestamp}",

// 必填,生成签名的随机串

      nonceStr:"{$wxConfig.nonceStr}",

// 必填,签名,见附录1

      signature:"{$wxConfig.signature}",

// 必填,需要使用的JS接口列表,所有JS接口列表见附录2

      jsApiList : [ 'scanQRCode' ]

  });

wx.error(function(res){

            alert("----------出错了-----------:" + res.errMsg);//这个地方的好处就是wx.config配置错误,会弹出窗口哪里错误,然后根据微信文档查询即可。

  });

wx.ready(function(){

      wx.checkJsApi({

        jsApiList : ['scanQRCode'],

success : function(res){

}

      });

//点击按钮扫描二维码

      $('#wxcode').click(function(){

//              alert(1);

        wx.scanQRCode({

            needResult: 1,// 默认为0,扫描结果由微信处理,1则直接返回扫描结果,

            scanType: ["qrCode","barCode"],// 可以指定扫二维码还是一维码,默认二者都有

            success: function (res){

              var result = res.resultStr;// 当needResult 为 1 时,扫码返回的结果

              result=result.replace('EAN_13,','');

var url= '{:url("smsb/sp")}';

url = url+'?ISBN='+result;

//            $('#content').html(url);

              window.location = url;

}

        });

})

});

</script>

转自https://www.cnblogs.com/leaf-cq/p/8877270.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值