search
HomeBackend DevelopmentPHP TutorialPHP WeChat generates a WeChat public account QR code and scans it to enter the public account with parameters

This article mainly introduces the QR code generated by php WeChat to enter the WeChat public account with parameters. It has a certain reference value. Now I share it with you. Friends in need can refer to it

In order to meet the needs of scenarios such as user channel promotion analysis and user account binding, the public platform provides an interface for generating QR codes with parameters. Using this interface, multiple QR codes with different scene values ​​can be obtained. After the user scans them, the public account can receive event push.

There are currently 2 types of QR codes:

1. Temporary QR code has an expiration time, and can be set to a maximum of 30 days after the QR code is generated ( That is, it will expire after 2,592,000 seconds), but it can generate larger quantities. Temporary QR codes are mainly used in business scenarios that do not require permanent storage of QR codes, such as account binding.
2. Permanent QR codes have no expiration time, but the number is small (currently up to 100,000). Permanent QR codes are mainly used in scenarios such as account binding and user source statistics.

When a user scans a QR code with a scene value, the following two events may be pushed:

If the user has not followed the official account, the user can follow the official account. After following, WeChat will Scenario value attention events are pushed to developers.

If the user has followed the official account, the user will automatically enter the session after scanning, and WeChat will also push the scanning event with scene value to the developer.

The process of obtaining a QR code with parameters includes two steps. First, create a QR code ticket, and then use the ticket to the specified URL to exchange for the QR code.

Create QR code ticket

Every time you create a QR code ticket, you need to provide a parameter (scene_id) set by the developer. We will introduce the temporary QR code and the permanent QR code respectively. The process of creating a QR code ticket.

Notice
expire_seconds The validity time of the QR code, in seconds. The maximum value cannot exceed 2592000 (that is, 30 days). If this field is not filled in, the default validity period is 30 seconds.
action_name QR code type, QR_SCENE is a temporary integer parameter value, QR_STR_SCENE is a temporary string parameter value, QR_LIMIT_SCENE is a permanent integer parameter value, QR_LIMIT_STR_SCENE is a permanent string parameter value
action_info QR code details
scene_id Scene value ID, which is a 32-bit non-zero integer when using a temporary QR code. The maximum value when using a permanent QR code is 100000 (currently the parameter only supports 1–100000)
scene_str Scene value ID (ID in string form), string type, length limit is 1 to 64

<?php
namespace app\api\model;
set_time_limit(30);
class WxQrcode{
    //构造方法
    static $qrcode_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?";    
    static $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";    
    static $qrcode_get_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?";    //生成二维码
    public function getEwm($fqid,$type = 1){
        $appid = &#39;你的appid&#39;;        $secret = &#39;你的secret&#39;;        
        $ACCESS_TOKEN = $this->getToken($appid,$secret);        
        $url = $this->getQrcodeurl($ACCESS_TOKEN,$fqid,$type);
        save_log(&#39;测试保存的路径&#39;.$url.&#39;fid&#39;.$fqid);        
        return $this->DownLoadQr($url,time());
    }    
    protected function getQrcodeurl($ACCESS_TOKEN,$fqid,$type = 1){
        $url = self::$qrcode_url.&#39;access_token=&#39;.$ACCESS_TOKEN;        
        if($type == 1){            
        //生成永久二维码
            $qrcode= &#39;{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_str": &#39;.$fqid.&#39;}}}&#39;;
        }else{            
        //生成临时二维码
            $qrcode = &#39;{"expire_seconds": 604800, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": &#39;.$fqid.&#39;}}}&#39;;
        }        $result = $this->http_post_data($url,$qrcode);        
        $oo = json_decode($result[1]);        
        if (empty($oo->ticket)){            
        return false;
        }        
        if(!$oo->ticket){            
        $this->ErrorLogger(&#39;getQrcodeurl falied. Error Info: getQrcodeurl get failed&#39;);            
        exit();
        }        $url = self::$qrcode_get_url.&#39;ticket=&#39;.$oo->ticket.&#39;&#39;;        
        return $url;
    }    
    protected function getToken($appid,$secret){
        $ACCESS_TOKEN = file_get_contents(self::$token_url."appid=$appid&secret=$secret");        
        $ACCESS_TOKEN = json_decode($ACCESS_TOKEN);        
        $ACCESS_TOKEN = $ACCESS_TOKEN->access_token;        
        return $ACCESS_TOKEN;
    }    
    protected function http_post_data($url, $data_string) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(                
        &#39;Content-Type: application/json; charset=utf-8&#39;,                
        &#39;Content-Length: &#39; . strlen($data_string))
        );
        ob_start();
        curl_exec($ch);        i
        f (curl_errno($ch)) {            
        $this->ErrorLogger(&#39;curl falied. Error Info: &#39;.curl_error($ch));
        }        
        $return_content = ob_get_contents();
        ob_end_clean();        
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);        
        return array($return_code, $return_content);
    }    //下载二维码到服务器
    protected function DownLoadQr($url,$filestring){
        if($url == ""){            
        return false;
        }        
        $filename = $filestring.rand(0,99999999999).&#39;.jpg&#39;;
        ob_start();
        readfile($url);        
        $img=ob_get_contents();
        ob_end_clean();        
        $size=strlen($img);        
        $fp2=fopen(&#39;static/qrcode/&#39;.$filename,"a");        
        if(fwrite($fp2,$img) === false){            
        $this->ErrorLogger(&#39;dolwload image falied. Error Info: 无法写入图片&#39;);            
        exit();
        }
        fclose($fp2);        
        return &#39;static/qrcode/&#39;.$filename;
    }    //错误日志
    private function ErrorLogger($errMsg){
        $logger = fopen(&#39;log.txt&#39;, &#39;a+&#39;);
        fwrite($logger, date(&#39;Y-m-d H:i:s&#39;)." Error Info : ".$errMsg."\r\n");
        fclose($logger);
    }

}

The above is the entire content of this article, for more related content, please pay attention to PHP Chinese net.

Related recommendations:

PHP WeChat development of synchronized fans

##php WeChat public account development, obtaining user WeChat personal information

The above is the detailed content of PHP WeChat generates a WeChat public account QR code and scans it to enter the public account 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 does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

How do you retrieve data from a PHP session?How do you retrieve data from a PHP session?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

How can you use sessions to implement a shopping cart?How can you use sessions to implement a shopping cart?May 01, 2025 am 12:10 AM

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

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 Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft