業務場景
- 用戶對外分享微信小程序,攜帶用戶個人數據
- 總共生成的小程序碼數量不確定
具體實現
調用接口
微信實現生成二維碼的方式有三種
- createWXAQRCode
- getWXACode
- getWXACodeUnlimit
這裏需要採用getWXACodeUnlimit,通過該接口生成的小程序碼,永久有效,數量暫無限制。
參數
業務通過scene傳遞參數,其他用於修飾樣式。
限制爲最大32個可見字符,只支持數字,大小寫英文以及部分特殊字符:!#$&'()*+,/:;=?@-._~
示例代碼(基於Yii2)
除了生成小程序二維碼,還做了access_token
的獲取調用。
/**
* 生成C端小程序二維碼
* @param $scene
*/
public static function makeQrCodeUnlimit($scene){
$accessToken = self::getAccessToken();
$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$accessToken;
$post = [
'scene'=>$scene
];
$result = Curl::httpRequest($url,json_encode($post));
echo($result);
}
public static function getAccessToken(){
$expiresIn = 'user_wx_expires_in';
$accessToken = "user_wx_access_token";
$expiresInValue = SystemParam::getKey($expiresIn);
if(strtotime($expiresInValue) < time()){
$appId = \Yii::$app->params['userWxapp']['appId'];
$appSecret = \Yii::$app->params['userWxapp']['secretKey'];
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
$result = json_decode(Curl::httpRequest($url),true);
$accessTokenValue = $result['access_token'];
$expiresInValue = date("Y-m-d H:i:s", time() + $result['expires_in']);
SystemParam::setKey($expiresIn,$expiresInValue);
SystemParam::setKey($accessToken,$accessTokenValue);
return $accessTokenValue;
}else{
$accessTokenValue = SystemParam::getKey($accessToken);
return $accessTokenValue;
}
}
/**
* [httpRequest curl請求封裝]
* @param [type] $url curl請求路徑
* @param [type] $post_xml [curl請求的數據]
* @param integer $type [1爲需要傳證書 0不傳]
* @return [type] [description]
*/
public static function httpRequest($url,$post = '',$type = 0,$str='')
{
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
if($type == 1){
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,1);//證書檢查
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
curl_setopt($ch,CURLOPT_SSLCERT,$_SERVER['DOCUMENT_ROOT'].'/cert/apiclient_cert.pem');
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'pem');
curl_setopt($ch,CURLOPT_SSLKEY,$_SERVER['DOCUMENT_ROOT'].'/cert/apiclient_key.pem');
}
// if($cookie) {
// curl_setopt($ch, CURLOPT_COOKIE, $cookie);
// }
// curl_setopt($ch, CURLOPT_HEADER, $returnCookie);
if($str != ''){
curl_setopt($ch, CURLOPT_HEADER, $str);
}
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data=curl_exec($ch);
if (curl_errno($ch)) {
return curl_error($ch);
}
curl_close($ch);
return $data;
}
接口調用結果爲圖片二進制內容,這裏需要設置header.
header('Content-type: image/jpg');
QrCode::makeQrCodeUnlimit("a=b&c=d"));