• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

后台生成小程序分享二维码

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

java 后台生成微信小程序分享二维码

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;


/**
 * 2019/8/10
 */
public class QrCodeUtil {

    /**
     * 向指定URL发送GET方法的请求 获取 accessToken
     * @param url
     * 发送请求的URL
     */
    public static String get(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
//            // 获取所有响应头字段
//            Map<String, java.util.List<String>> headerFields = connection.getHeaderFields();
//            // 遍历所有的响应头字段
//            for (String key : headerFields.keySet()) {
//                System.out.println(key + "--->" + headerFields.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
           // e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    public static String postWriteImage(String sceneStr, String accessToken,String base) {
        RestTemplate rest = new RestTemplate();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        String PA1=IdGen.uuid()+".jpg";
        String PA=base+"/"+ PA1;
        try {
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
            Map<String,Object> param = new HashMap<>();
            param.put("scene", sceneStr);
            param.put("page", "");
            param.put("width", 256);
            param.put("auto_color", false);
            Map<String,Object> line_color = new HashMap<>();
            line_color.put("r", 0);
            line_color.put("g", 0);
            line_color.put("b", 0);
            param.put("line_color", line_color);
            //  LOG.info("调用生成微信URL接口传参:" + param);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
           // System.out.println("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
            byte[] result = entity.getBody();
//            System.out.println(Base64.encodeBase64String(result));
            inputStream = new ByteArrayInputStream(result);
            File pFile = new File(base);
            if (!pFile.exists()) {
                pFile.mkdirs();
            }
            outputStream = new FileOutputStream(PA);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
        } catch (Exception e) {
            //  LOG.error("调用小程序生成微信永久小程序码URL接口异常",e);
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return PA1;
    }
}

Service 层

import com.alibaba.fastjson.JSONObject;
import com.hwj.pjname.common.utils.IdGen;
import com.hwj.pjname.common.utils.WeChat.QrCodeUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 2019/8/1
 * 生成含有商户Id的分享码
 */
@Service
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
public class QrcodeShareService {
    @Value("${basicsUploadPath}")
    String base;
    public String writeShopImage(String shopId,String appid,String secret){

    //       首先获取AccessToken 调用的凭证
    String res="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
    String token  = QrCodeUtil.get(res);
    JSONObject jsontoken = JSONObject.parseObject(token);
//        if(!jsontoken.get("errcode").equals("0")){
//        System.out.println("请求凭证失败");
//        return "";
//    }
    token= jsontoken.getString("access_token");
      //  System.out.println("获取到的凭证信息"+token);

    //String Path = base+"//"+IdGen.uuid()+".png";
    //你的json数据 ,格式不要错
//    String json = "{\"scene\":\""+shopId+"\","+
//            "\"page\":"+""+","+
//            "\"width\":85" +
//            "}";
//    System.out.println("json: "+json);
        return  QrCodeUtil.postWriteImage(shopId, token, base);

    }

}

controller层

@RestController
public class testController {
    @Autowired
    QrcodeShareService qrcodeShareService;

    @PostMapping("/123")
    public void test(HttpServletRequest request, HttpServletResponse response, String shopId) {
        String str = qrcodeShareService.writeShopImage(shopId, "申请的appid", "自己申请的secret");
        System.out.println("wxf679409476756da2" + str);

    }
}

我用的是微信的c接口可以生成不限制数量的分享码

python 生成微信二维码

 url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % (APP_ID, SECRET)
    res = requests.get(url=url)
    access_token = eval(res.text).get("access_token")
    print(access_token)
    url = \'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s\' % access_token

    data = {
        \'scene\': "%s-%s" % (shopid,2),
        \'page\': \'pages/auth/auth\',
        \'width\':256
    }
    params_string = json.dumps(data)
    res = requests.post(url=url, data=params_string, verify=False)
    t = datetime.datetime.now()
    num = random.randint(1000, 9999)


    with open(BASE_DIR + \'/static/Wcode/\' + t.strftime("%Y-%m-%d-%H-%M-%S") + str(num) + ".jpg",
              \'wb\') as f:
        f.write(res.content)
    return "static/Wcode/" + t.strftime("%Y-%m-%d-%H-%M-%S") + str(num) + ".png"

 注意:生成的二维码要等小程序发布不然前端获取不到二维码传递过来的参数。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap