1. 程式人生 > 其它 >微信小程式生成太陽碼

微信小程式生成太陽碼

<?php

/**
 * User: Eden
 * Date: 2019/3/21
 * 共有內容
 */
namespace Common\Service;
use Common\Util\JsonUtil;
use Vendor\Func\Http;
use Vendor\Func\Red;

class WxService extends CommonService {
    /**
     * 獲取小程式token
     * $app_id
     * $app_secret
     */
    public function getXcxAccessToken($app_id,$app_secret) {
        // 存到redis中
        $red_key = 'xcx:access_token:'.$app_id;
        $redis = Red::create();
        $access_token = $redis->get($red_key);
        if (!$access_token) {
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$app_id.'&secret='.$app_secret;
            $return_data = Http::doGet($url);
            $return_data = JsonUtil::jsonDecode($return_data);
            $redis->set($red_key,JsonUtil::jsonEncode($return_data['access_token']),$return_data['expires_in'] - 1000); // 存兩小時以內
            $access_token = $return_data['access_token'];
        } else {
            $access_token = JsonUtil::jsonDecode($access_token);
        }
        return $access_token;
    }

    /**
     * 獲取小程式太陽碼
     */
    public function getXcxCodeUrl($access_token,$scene,$page) {
        $request_data = [
            'page'  => $page, // 如: pages/index/index 。 這裡pages前面沒有斜槓'/' 。
            'scene' => $scene,
            'width' => 690
        ];

        $request_url='https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
        $result = Http::doPostJson($request_url,$request_data);

//        ob_clean();
//        header('Content-Type: image/png; charset=UTF-8');
//        echo $result;exit;

        $uploadService = new UploadService();
        // 存入cdn
        $cdn_result = $uploadService->upload_cdn($result,'suncode');

        if ($cdn_result['errno'] == 0) {
            return $cdn_result['save_name'];
        } else {
            return false;
        }
    }
}