PHP生成带参数的小程序码

生成小程序码并携带参数

        我们平时在开发微信小程序时,会遇到如下场景,需要制作某个推广链接,然后需要生成一个专属小程序码,扫描这个专属二维码时,获取到推广的链接携带的参数跳转到指定的界面。这个看似很难,其实特别简单,阅读微信官方的接口就很容易弄明白,获取小程序的appid和小程序的secret,然后生成token,再通过这个token请求微信那边的生成小程序码的接口,完事!

        第一步:检测token是否存在于redis中且没有过期,如果都满足就直接到下一步,否则就通过接口获取token后将token存入redis。第二步:调用token,设置生成小程序码的页面、参数、和版本(开发版、体验版、正式版),生成小程序码。生成的小程序码是二进制内容,可以转换成base64编码后存入redis方便调用,也可以直接展示为图片或直接保存为图片。

<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$getToken = $redis->exists("Token");
if ($getToken==0){
    $appid = '小程序appid';
    $secret = '小程序secret';
    $urlss = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $urlss);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    $redis->set("Token", $output);
    $redis->expire("Token","7000");
}
$tk = json_decode($redis->get("Token"))->access_token;

$urlss = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$tk;
$ch = curl_init();
$datass = json_encode(array("page"=>"pages/login/login","env_version"=>"develop", "scene"=>"aa&bb&cc"));
curl_setopt($ch, CURLOPT_URL, $urlss);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $datass);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
$output1 = curl_exec($ch);
curl_close($ch);

        转换成base64编码

$imgUrl = 'data:image/jpg;base64,'.base64_encode($output1);

        直接在页面显示为图片

header("Content-type: image/jpg;charset=gb2312");
echo $output1;

        保存为图片

$url = "test.jpg";
file_put_contents($url, $output1, true);

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

慕慕慕慕公子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值