版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/diandianxiyu/article/details/87921762
业务场景
- 用户对外分享微信小程序,携带用户个人数据
- 总共生成的小程序码数量不确定
具体实现
调用接口
微信实现生成二维码的方式有三种
- 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"));