


WeChat obtains multiple global access_token conflicts, resulting in invalidity? (Solution)
Token expires in 7200 seconds by default. If a second place also requests the same token, the first token will expire within 5 minutes. In other words, if the time is too short during my second request, it will cause a conflict.
I just learned WeChat development and my code writing is not perfect. I only passed the judgment of whether the lifetime is greater than 7200. I saw someone saying that it can judge the reading every minute. I wonder if you have any optimization suggestions for my code? Thank you
<code>function getWxAccessToken(){ if ( $_SESSION['access_token'] && $_SESSION['expire_time'] > time() ) { //未过期 return $_SESSION['access_token']; }else { $appid = "wx3bbf9ae731a6eb07"; $appsecret = "2b14a75fa48825ef3c76c8949b5e030f"; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret; $res =$this->https_request($url,'get','json'); $access_token = $res["access_token"]; //将重新获取到的access_token存到session里 $_SESSION['access_token']=$access_token; $_SESSION['expire_time']=time()+7200; return $access_token; } } </code>
The conflict is a method under the same controller, and each call uses
<code> $access_token=$this->getWxAccessToken(); </code>
The error message is as follows
<code>array(2) { ["errcode"] => int(40001) ["errmsg"] => string(81) "invalid credential, access_token is invalid or not latest hint: [pd4MfA0688vr40!]" } </code>
I saw what the official said
The official meaning of 0.0 is not to use business logic points to refresh the token. What I wrote seems to be using business logic to refresh the token. What does it mean to use a third-party central control?
Put the absolute path of the method in the QR code generator and scan it. This debugging result feels more correct than direct access through the browser.
In most cases, if the browser reports 40001 when opening it, basically the program is fine
Reply content:
Token expires in 7200 seconds by default. If a second place also requests the same token, the first token will expire within 5 minutes. In other words, if the time is too short during my second request, it will cause a conflict.
I just learned WeChat development and my code writing is not perfect. I only passed the judgment of whether the lifetime is greater than 7200. I saw someone saying that it can judge the reading every minute. I wonder if you have any optimization suggestions for my code? Thank you
<code>function getWxAccessToken(){ if ( $_SESSION['access_token'] && $_SESSION['expire_time'] > time() ) { //未过期 return $_SESSION['access_token']; }else { $appid = "wx3bbf9ae731a6eb07"; $appsecret = "2b14a75fa48825ef3c76c8949b5e030f"; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret; $res =$this->https_request($url,'get','json'); $access_token = $res["access_token"]; //将重新获取到的access_token存到session里 $_SESSION['access_token']=$access_token; $_SESSION['expire_time']=time()+7200; return $access_token; } } </code>
The conflict is a method under the same controller, and each call uses
<code> $access_token=$this->getWxAccessToken(); </code>
The error message is as follows
<code>array(2) { ["errcode"] => int(40001) ["errmsg"] => string(81) "invalid credential, access_token is invalid or not latest hint: [pd4MfA0688vr40!]" } </code>
I saw what the official said
The official meaning of 0.0 is not to use business logic points to refresh the token. What I wrote seems to be using business logic to refresh the token. What does it mean to use a third-party central control?
Put the absolute path of the method in the QR code generator and scan it. This debugging result feels more correct than direct access through the browser.
In most cases, if the browser reports 40001 when opening it, basically the program is fine
It is recommended to store access_token in the database, so that all businesses use the same token, so that each business logic point does not request access_token independently;
The official document means that if the business logic is on multiple servers, Since access_token and expire_time are stored in the session, the session will not be shared between servers, which will cause the business on each server to initiate a request. If the access_token on one of the servers has not expired, and the other server re-requests the access_token , making the access_token on the first server invalid, and then using the expired access_token to request services, resulting in unstable services. Use the central control server to store the access_token, so that unified services will not cause conflicts between businesses and ensure data consistency. Sex
Access_token is common to all calls. There is no need to put the session. Everyone's session is different. It is usually placed in the cache, otherwise you can just put it in the database.
Every time you use it, go to the database. If it is within the validity period, use it directly. If it is invalid, retrieve it again and insert it into the database.
Session is based on users, so you can refresh it once each user visits.
It is recommended to put it in the cache or database and refresh it regularly.

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
