php生成小程序二維碼出(chū)現40001的(de)情況
發表時(shí)間:2020-10-21
發布人(rén):融晨科技
浏覽次數:102
php生成小程序二維碼出(chū)現40001的(de)情況
獲取二維碼時(shí),小程序的(de)access_token莫名奇妙失效了(le/liǎo)?
生成小程序二維碼時(shí)遇到(dào)的(de)坑,明明剛獲取到(dào)的(de)access_token,生成二維碼時(shí)總是(shì)提示說(shuō) "errcode: 40001, errmsg: “invalid credential, access_token is invalid or not latest hint: [IUwBwa07644522]”。這(zhè)個(gè)access_token時(shí)靈時(shí)不(bù)靈
不(bù)廢話,直接說(shuō)解決方案
出(chū)現獲取小程序二維碼經常失敗偶爾成功或者偶爾失敗的(de)情況,并提示40001。這(zhè)個(gè)很大(dà)程度上(shàng)是(shì)因爲(wéi / wèi)你的(de)程序中有多個(gè)地(dì / de)方使用了(le/liǎo)獲取access_token的(de)方法 會失效是(shì)其它地(dì / de)方刷新了(le/liǎo)assess_token導緻在(zài)當前頁面刷新時(shí)和(hé / huò)另一個(gè)地(dì / de)方沖突,導緻token失效
解決方式就(jiù)是(shì)将獲取access_token的(de)方法統一管理,這(zhè)樣将不(bù)會存在(zài)沖突
附上(shàng)本人(rén)生成二維碼的(de)部分代碼(使用tp5.1框架)
/**
* @descr 得到(dào)小程序二維碼
*/
public function getQrCode(){
header('content-type:text/html;charset=utf-8');
if (Session::get('access_token')){
$token=Session::get('access_token');
}else{
$token = access_token();
}
$qcode ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$token."";
$param = json_encode([
//"scene"=>"uid=".$this->app['userID'],
"scene"=>"uid=21",
"path"=>"pages/active-receive/index",
//"width"=> 430
]);
$result = Common::httpRequest($qcode,$param,"POST");
//file_put_contents("qrcode.png", $result);
$base64_image ="data:image/jpeg;base64,".base64_encode($result);
return $base64_image;
}
function access_token(){
$config = Config('weChat.');
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=". $config['WX_APPID']."&secret=".$config['WX_SECRET']."";
$json = \tool\Common::httpRequest($url);
$json = json_decode($json,true);
Session::set('access_token',$json['access_token'],7200);
return $json['access_token'];
}
//curl
public static 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;
}
分享一下自己的(de)采坑經曆,目的(de)是(shì)爲(wéi / wèi)了(le/liǎo)大(dà)家不(bù)再重複我的(de)錯誤。
寫的(de)不(bù)好,請大(dà)家不(bù)要(yào / yāo)介意,謝謝