到目前為止我們做的微信小程序都是純粹線上的,在一些文章介紹或者QQ群裡面發内容帶的二維碼是整個小程序的二維碼,例如:《一把刀新華字典》目前還沒有必要讓每個字都帶有自己的二維碼。
不過考慮到以後可能做與線下實體結合的微信小程序,所以也嘗試了批量生成帶參數的二維碼,我不是在小程序裡面生成,而是在後台用一個PHP程序來批量生成的。
官方網站上的說明是:獲取小程序頁面二維碼
我寫的主要程序如下:
//第一步獲取token
function get_access_token($appid,$secret) {
$get_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
$content = file_get_contents($get_url);
$content_json = json_decode($content);
$access_token = $content_json->access_token;
$expires_in = $content_json->expires_in;
return $access_token;
}
//第二步獲取二維碼并保存
function save_erweima($access_token,$xiaochengxu_path,$save_path) {
$post_url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$access_token";
$width = '258';
$post_data='{"path":"'.$xiaochengxu_path.'","width":'.$width.'}';
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/json',
'content' => $post_data
)
);
$context = stream_context_create($opts);
$result = file_get_contents($post_url, false, $context);
$file_path = $save_path;
$bytes = file_put_contents($file_path, $result);
return $bytes;
}
遇到好些報錯:
- post的data格式錯誤,需要json格式;
- 權限錯誤,可以在小程序後台獲取appid、重置secret,來生成正确的access_token;{"errcode":41001,"errmsg":"access_token missing hint: [gioNIA0856vr31!]"}
- 超過當日生成二維碼數量限制;{"errcode":45009,"errmsg":"reach max api daily quota limit hint: [u1F_80062vr46!]"}
實際運行中發現到1000條就報了超過每日限制的錯誤,那隻好分很多天來進行了。
下面是頁面例子“丁”的鍊接和這個字的微信小程序二維碼:
https://xinhuazidian.18dao.cn/zidian/丁

再下面是“一把刀新華字典”這個網站的鍊接和微信小程序二維碼:
https://xinhuazidian.18dao.cn/

另外,摩拜單車可以通過微信小程序掃描二維碼使用,而無需生成專門小程序新的二維碼,這是騰訊專門對他們開放的二維碼跳轉接口,免得需要所有單車上的二維碼都需要更換,而且容量受限。據說不久以後,騰訊也會把這種功能開放給其它微信小程序開發者,那就方便多了。
评论