首页 > 编程语言 >php 生成小程序二维码

php 生成小程序二维码

时间:2024-02-28 16:12:04浏览次数:19  
标签:code data token 生成 access 二维码 result php true

    public function generate($code, $isShow)
    {
        // 构建二维码参数
        $scene  = 'C=' . $code.'&path=green';
        $params = [
            "scene" => $scene,
            'page'  => 'pages/login/registerSales', // 小程序页面路径
            'width' => 200, // 二维码宽度
        ];
        // 调用微信接口获取 access_token
        $wechatService = new WechatApiService();
        $access_token  = $wechatService->getAccessToken(true);
        if (empty($access_token)) {
            $access_token = $wechatService->getAccessToken(true);
        }
        $accessToken = $access_token;
        // 调用微信接口生成小程序二维码
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$accessToken}";
        $ch  = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $imageData = curl_exec($ch);
        curl_close($ch);

        if($isShow){
            header("Content-Type: image/jpeg;text/html; charset=utf-8");
            echo $imageData;
            exit;
        }

        $path = 'uploadfile/admin/green_invite_qrcode/';
        if(!file_exists($path)){
            mkdir($path, 0777, true);
        }
        // 保存二维码图片
        $filename  = 'invite_qrcode_' . $code . '.png';
        $file_path = public_path($path) . $filename;
        file_put_contents($file_path, $imageData);
        return $path . $filename;
    }
<?php
/**
 * 获取微信相关接口
 */
namespace App\Services\Wechat;

use App\Tools\Common;
use App\Tools\HttpCurl;
use App\Tools\RedisCommon;

class WechatApiService extends \App\Services\BaseService
{
    public function getOpenidByCode($code)
    {
        $url = "https://api.weixin.qq.com/sns/jscode2session";
        $data = [
            'appid' => Common::getConfigValByEnv('wechat.APP_ID'),
            'secret' => Common::getConfigValByEnv('wechat.APP_SECRET'),
            'js_code' => $code,
            'grant_type' => 'authorization_code',
        ];

        /**
         * 正确时返回
         *{"session_key": "6I7echmzado/KAk0tw9t1g==",
         *"openid": "oy3tU41PkUKSzXgMQB_K515qMS_A"}
         * 失败时返回:{"errcode": 40163,"errmsg": "code been used, rid: 6448dd1c-6b6cb729-1abe846a"}
         */
        $result = HttpCurl::sendGet($url, $data);
        unset($data['secret']);
        Common::logInfo('','查询微信openid返回', ['params'=>$data,'result'=>$result]);
        $result = json_decode($result,true);

        if(Common::getConfigValByEnv('wechat.wx_api_debug') === true && empty($result['openid'])){
            $result['openid'] = 'abcfdfsd5454';
        }
        return $result;
    }

    /**
     * 通过小程序code获取用户手机号
     * {
    "errcode":0,
    "errmsg":"ok",
    "phone_info": {
    "phoneNumber":"xxxxxx",
    "purePhoneNumber": "xxxxxx",
    "countryCode": 86,
    "watermark": {
    "timestamp": 1637744274,
    "appid": "xxxx"
    }
    }
    }
     * @param $code
     * @return void
     */
    public function getPhoneNumber($code)
    {
        $result = $this->getWxPhoneNumber($code);
        if($result['errcode'] != '0' && $result['errcode'] == '40001'){
            $result = $this->getWxPhoneNumber($code, true);
        }
        if($result['errcode'] != '0'){
            return self::showMsg(self::CODE_FAIL, self::MSG_FAIL, $result);
        }

        return self::showMsg(self::CODE_SUCCESS, self::MSG_SUCCESS, $result['phone_info']);
    }

    private function getWxPhoneNumber($code, $refreshToken=false)
    {
        if(env('APP_ENV') == 'local'){
            $url = 'https://consultant.noakcent.com/wp/wechat/get_access_token';
            $result = HttpCurl::sendPost($url, ['tk'=>'!@#$%^789_'.date('md')]);
            $acObj = json_decode($result, true);
            $token = $acObj['data'];
        }else{
            $token = $this->getAccessToken($refreshToken);
        }

        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$token;
        $data = ['code'=>$code];
        $result = HttpCurl::sendJsonPost($url, $data);

        Common::logInfo('','查询微信getPhoneNumber返回', ['url'=>$url,'params'=>$data,'result'=>$result]);
        $result = json_decode($result,true);
        return $result;
    }

    /**
     * 获取微信access_token值
     * @return void
     */
    public  function getAccessToken($refresh=false)
    {
        $key = 'nobel.wechat.access_token';
        $accessToken = RedisCommon::get($key);
        if(!$accessToken || $refresh === true){
            $url = "https://api.weixin.qq.com/cgi-bin/token";
            $data = [
                'appid' => Common::getConfigValByEnv('wechat.APP_ID'),
                'secret' => Common::getConfigValByEnv('wechat.APP_SECRET'),
                'grant_type' => 'client_credential',
            ];
            $result = HttpCurl::sendGet($url, $data);
            unset($data['secret']);
            Common::logInfo('','查询微信access_token返回', ['params'=>$data,'result'=>$result]);
            $result = json_decode($result,true);
            if(!empty($result['access_token'])){
                $accessToken = $result['access_token'];
                RedisCommon::set($key, $accessToken, 7190);
            }
        }

//        if(Common::getConfigValByEnv('wechat.wx_api_debug') === true && empty($result['openid'])){
//            $result['openid'] = 'test';
//        }
        Common::logInfo('','微信access_token:', ['wx-accesstoken'=>$accessToken]);
        return $accessToken;
    }

}

 

标签:code,data,token,生成,access,二维码,result,php,true
From: https://www.cnblogs.com/andydao/p/18040733

相关文章

  • php生成树状层级子孙树
    关于简单的方式获取树状层级子孙树的方案我已经写过了,在这里,当时是用简单的递归实现的,但是现在回头想想,如果层级很多,数据也很多,用递归感觉还是会不稳妥,这就有必要想办法转换为迭代来实现了。以下是迭代的代码实现<?php$data=[['id'=>1,'name'=>'中国','pid'=>0......
  • js调用斑马打印机打印二维码
    斑马打印机打印二维码项目(Web项目)功能中存在生成并打印二维码的功能,需要借助打印机打印出二维码。由于业务需求二维码需要打印在不干胶的材料上并可以进行粘贴,所以借助斑马打印机通过热敏不干胶纸进行打印。需要结合所使用的的斑马打印机的型号,去官网下载相关的浏览器打印插件。(......
  • Qt 随机数生成器:QRandomGenerator
    一、描述QRandomGenerator可用于从高质量随机数生成器生成随机值。与C++随机引擎一样,QRandomGenerator可以通过构造函数使用用户提供的值作为种子。播种时,此类生成的数字序列是确定性的。也就是说,给定相同的种子数据,QRandomGenerator会生成相同的数字序列。给定不同的种......
  • Qt 生成随机数 qrand、QRandomGenerator
    //老方法//利用qrand和qsrand生成随机数//位于QtGlobal中//例,生成一个0和10之间的随机数1qsrand(QTime::currentTime().msec());//设置种子,该种子作为qrand生成随机数的起始值,RAND_MAX为32767,即随机数在种子值到32767之间2qrand()%10;//新方法//利用QRandomGenerator类......
  • c# winform项目生成的配置文件如何复制到输出目录
    版本:vs2022右键项目文件-》属性复制到输出目录改成1启动项目后可以在Debug\Config目录下看到jsconfig1.json ......
  • 学习python自动化——pytest+allure+jenkins持续集成平台生成allure报告
    一、安装allure命令行工具具体安装过程查看:学习python自动化——pytest单元测试框架的2.4.4、生成allure的测试文件二、allure与pytest的集成在allure安装完成之后,需要与pytest集成,能够在pytest运行完成之后,生成allure的文件。1、安装pytest的allure支撑插件pipinstal......
  • idea使用MybatisX插件根据表自动生成代码
    1.情景展示在实际开发过程中,根据数据库的表生成对应的增删改查代码,最为常见。除了使用公司封装的代码自动生成外,有没有通用的呢?2.具体分析在idea当中,我们可以使用MybatisX插件生成:表对应的实体类、dao层所使用的的mapper.java文件、mybatis对应的xml文件、service层所需的......
  • [安洵杯 2019]easy_serialize_php
    [安洵杯2019]easy_serialize_php<?php$function=@$_GET['f'];functionfilter($img){$filter_arr=array('php','flag','php5','php4','fl1g');$filter='/'.implode('|�......
  • CTFHUB-web-信息泄露-PHPINFO
    开启题目访问只有这一个页面,看一下flag在没在页面里信息发现:https://www.cnblogs.com/Cl0ud/p/15999347.html系统版本信息配置文件位置allow_url_fopen&allow_url_include文件包含必看选项之一,如果allow_url_fopen和allow_url_include都为On的时候,则文件包含函数......
  • 二维码的背后故事:为用户带来的便捷与安全
    一、二维码的起源二维码是一种将信息编码成二维图案的技术。它的起源可以追溯到上世纪90年代初,当时条形码已经被广泛应用于商业领域。然而,条形码的局限性和不足促使人们寻找一种更高效、更灵活的信息编码方式,于是二维码应运而生。二维码生成器|一个覆盖广泛主题工具的高效......