search
HomeBackend DevelopmentPHP TutorialPHP generates QR code for WeChat applet with parameters

PHP generates QR code for WeChat applet with parameters

Jul 14, 2018 am 10:32 AM
javascriptphpQR codeApplets

This article mainly introduces the QR code generated by PHP for WeChat applet with parameters. It has certain reference value. Now I share it with you. Friends in need can refer to it

The WeChat mini program officially opens three interfaces for creating QR codes, one of which is for generating QR codes, and the other is a sunflower-shaped mini program code. I use PHP to generate QR codes here.

First of all, you need to obtain Access_token

This request is also very easy. The WeChat development documentation has a request interface:
You need to obtain the APPID and APPSECRET of your own mini program

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

access_token is only valid for 2 hours, so it is best to cache it to avoid repeated requests

Build request parameters

PHP generates QR code for WeChat applet with parameters

You can build an array, Then convert it into json data and assign it to a variable

$param = json_encode(array("path"=>"pages/index/index?id=123","width"=> 150));

Then POST the data to the WeChat server in exchange for a QR code

Full code

 $_SESSION['expires_in']))
 {

     $json = httpRequest( $access_token );
     $json = json_decode($json,true); 
     // var_dump($json);
     $_SESSION['access_token'] = $json['access_token'];
     $_SESSION['expires_in'] = time()+7200;
     $ACCESS_TOKEN = $json["access_token"]; 
 } 
 else{

     $ACCESS_TOKEN =  $_SESSION["access_token"]; 
 }

//构建请求二维码参数
//path是扫描二维码跳转的小程序路径,可以带参数?id=xxx
//width是二维码宽度
$qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";
$param = json_encode(array("path"=>"pages/index/index?id=123","width"=> 150));

//POST参数
$result = httpRequest( $qcode, $param,"POST");
//生成二维码
file_put_contents("qrcode.png", $result);
$base64_image ="data:image/jpeg;base64,".base64_encode( $result );

//把请求发送到微信服务器换取二维码
  function httpRequest($url, $data='', $method='GET'){
    $curl = curl_init();  
    curl_setopt($curl, CURLOPT_URL, $url);  
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);  
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);  
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);  
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);  
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);  
    if($method=='POST')
    {
        curl_setopt($curl, CURLOPT_POST, 1); 
        if ($data != '')
        {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);  
        }
    }

    curl_setopt($curl, CURLOPT_TIMEOUT, 30);  
    curl_setopt($curl, CURLOPT_HEADER, 0);  
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
    $result = curl_exec($curl);  
    curl_close($curl);  
    return $result;
  } 

?>

Usage method:

1. Create a new qrcode.php
2. Copy the above code into it
3. Modify the APPID and APPSECRET
4. Visit qrcode.php

to generate a small program with parameters 2 QR code

PHP generates QR code for WeChat applet with parameters

#But this interface generates a small program QR code with a LOGO.
We want to generate a simple QR code for a small program without a logo. Is it okay?
There is no official way, but we can use a third-party interface to generate ordinary QR codes.

1. Decode first, decode the QR code of the mini program just generated, and obtain the URL
2. Use ordinary QR code to obtain the URL The QR code generation interface generates ordinary QR codes without LOGO

1. Decoding

In fact, there are many libraries for decoding. I directly use the third-party JSSDK decoding here. It is free and requires application. The interface and appid and appkey

<h2 id="生成无LOGO二维码">生成无LOGO二维码</h2>
nbsp;html>

  
    <title>PHP生成微信小程序二维码</title>
    <meta>
    <meta>
    <script></script>
    <script></script>
    <script></script>
  
  
    <!--显示二维码-->
    <p></p>
    <p>
        <input>
        <br>
        <img  src="/static/imghwm/default1.png" data-src="" class="lazy" alt="PHP generates QR code for WeChat applet with parameters" >
    </p>
    <a>点击生成无LOGO二维码</a>
    <script>

    var get_timestamp = function(){
        var timestamp =0;
        timestamp = Date.parse(new Date());// 获取当前时间戳(以s为单位)
        timestamp = timestamp / 1000;
        return timestamp;
    };

    //config,申请解码接口:http://www.wwei.cn/,免费
    var api_id = &#39;xxxxxxx&#39;;//改为您自己的
    var api_key = &#39;xxxxxxxxx&#39;;//改为您自己的
    var timestamp = get_timestamp();
    var client = hprose.Client.create(&#39;http://hprose.wwei.cn/qrcode.html&#39;, [&#39;qrencode&#39;,&#39;qrdecode&#39;]);

    //解码
    $("#qrdecode").click(function(){
            var timestamp = get_timestamp();
            var imgurl = &#39;&#39;;//远程图片
            var imgdata =&#39;<?php echo $base64_image;?>&#39;;//本地图片,直接调用生成的官方小程序二维码,用于解码
            var signature = md5(api_key + timestamp + imgurl + imgdata);
            client.ready(function(qrcode) {
                qrcode.qrdecode(api_id,signature,timestamp,imgurl,imgdata)
                .then(function(result) {
                    if(result.status !=1){
                        alert(result.msg);
                        return ;
                    }

                    //生成无LOGO二维码api接口
                    var qrcodeapi = "http://qr.liantu.com/api.php?text=";
                    //拼接接口+解码url并输出为图片
                    $("#show_test").html(&#39;<img  src="/static/imghwm/default1.png"  data-src="&#39;+qrcodeapi+result.data.raw_text+&#39;"  class="lazy"  / alt="PHP generates QR code for WeChat applet with parameters" >&#39;);
                },function(e) {
                    console.error(e);
                });
            },
            function(e) {
                console.error(e);
            });
    });
    </script>
  

The above is decoding implemented through js. The decoding still calls an image address of the QR code generated by php

<?php  echo $base64_image;?>

The above is calling a local image, so This decoding program needs to be used in conjunction with the PHP code that generates the QR code for the mini program.

After decoding, a QR code without LOGO needs to be generated. For this, I only need to call an interface.
Interface: http://qr.liantu.com/api.php?...

Then splicing the decoded url can generate a QR code.

PHP generates QR code for WeChat applet with parameters

Then the combination of generating small program code and generating code without LOGO QR code is:

 $_SESSION['expires_in']))
 {

     $json = httpRequest( $access_token );
     $json = json_decode($json,true); 
     // var_dump($json);
     $_SESSION['access_token'] = $json['access_token'];
     $_SESSION['expires_in'] = time()+7200;
     $ACCESS_TOKEN = $json["access_token"]; 
 } 
 else{

     $ACCESS_TOKEN =  $_SESSION["access_token"]; 
 }

//构建请求二维码参数
//path是扫描二维码跳转的小程序路径,可以带参数?id=xxx
//width是二维码宽度
$qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";
$param = json_encode(array("path"=>"pages/index/index?id=123","width"=> 150));

//POST参数
$result = httpRequest( $qcode, $param,"POST");
//生成二维码
file_put_contents("qrcode.png", $result);
$base64_image ="data:image/jpeg;base64,".base64_encode( $result );

//把请求发送到微信服务器换取二维码
  function httpRequest($url, $data='', $method='GET'){
    $curl = curl_init();  
    curl_setopt($curl, CURLOPT_URL, $url);  
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);  
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);  
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);  
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);  
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);  
    if($method=='POST')
    {
        curl_setopt($curl, CURLOPT_POST, 1); 
        if ($data != '')
        {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);  
        }
    }

    curl_setopt($curl, CURLOPT_TIMEOUT, 30);  
    curl_setopt($curl, CURLOPT_HEADER, 0);  
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
    $result = curl_exec($curl);  
    curl_close($curl);  
    return $result;
  } 

?>

生成小程序官方二维码

PHP generates QR code for WeChat applet with parameters

生成无LOGO二维码

nbsp;html>        PHP生成微信小程序二维码               <script></script>     <script></script>     <script></script>           

    

                 
        PHP generates QR code for WeChat applet with parameters     

    点击生成无LOGO二维码     <script> var get_timestamp = function(){ var timestamp =0; timestamp = Date.parse(new Date());// 获取当前时间戳(以s为单位) timestamp = timestamp / 1000; return timestamp; }; //config,申请解码接口:http://www.wwei.cn/,免费 var api_id = &#39;xxx&#39;;//改为您自己的 var api_key = &#39;xxx&#39;;//改为您自己的 (实际使用,建议在后台完成 signature 签名,以防暴露 api_key ,或定期更改) var timestamp = get_timestamp(); var client = hprose.Client.create(&#39;http://hprose.wwei.cn/qrcode.html&#39;, [&#39;qrencode&#39;,&#39;qrdecode&#39;]); //解码 $("#qrdecode").click(function(){ var timestamp = get_timestamp(); var imgurl = &#39;&#39;;//远程图片 var imgdata =&#39;<?php echo $base64_image;?>&#39;;//本地图片,直接调用生成的官方小程序二维码,用于解码 var signature = md5(api_key + timestamp + imgurl + imgdata); client.ready(function(qrcode) { qrcode.qrdecode(api_id,signature,timestamp,imgurl,imgdata) .then(function(result) { if(result.status !=1){ alert(result.msg); return ; } //生成无LOGO二维码api接口 var qrcodeapi = "http://qr.liantu.com/api.php?text="; //拼接接口+解码url并输出为图片 $("#show_test").html(&#39;<img src="/static/imghwm/default1.png" data-src="&#39;+qrcodeapi+result.data.raw_text+&#39;" class="lazy" / alt="PHP generates QR code for WeChat applet with parameters" >&#39;); },function(e) { console.error(e); }); }, function(e) { console.error(e); }); }); </script>   

But two js libraries are needed for decoding

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

php Daniel shared: PHP code writing specifications, a comprehensive summary

The above is the detailed content of PHP generates QR code for WeChat applet with parameters. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version