This commit is contained in:
xl
2023-11-14 00:15:27 +08:00
parent fbdbcbccd9
commit e721fe4f36
53 changed files with 1 additions and 1 deletions
+212
View File
@@ -0,0 +1,212 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/19 0019
* Time: 16:12
*/
namespace wchat\wx;
use Exception;
use Kiri\Client;
use wchat\common\Decode;
use wchat\common\HttpClient;
use wchat\common\Result;
class Account extends SmallProgram
{
/**
* @param $code
* @return Result
*/
public function login($code): Result
{
$param['appid'] = $this->config->getAppid();
$param['secret'] = $this->config->getAppsecret();
$param['js_code'] = $code;
$param['grant_type'] = 'authorization_code';
$client = new Client('api.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'application/json']);
if (!empty($this->getConfig()->getProxyHost()) && $this->getConfig()->getProxyPort() > 0) {
$client->withProxyHost("192.168.0.57")->withProxyPort(12286);
}
$client->get('sns/jscode2session', $param);
$client->close();
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$body = json_decode($client->getBody(), true);
if (isset($body['errcode']) && $body['errcode'] != 0) {
return new Result(code: $body['errcode'], message: $body['errmsg']);
} else {
return new Result(code: 0, data: $body);
}
}
/**
* @param $openid
* @return Result
* @throws Exception
*/
public function getPublicUserInfo($openid): Result
{
$query = [
'access_token' => $this->config->getAccessToken(),
'openid' => $openid,
'lang' => 'zh_CN'
];
$client = new Client('api.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'application/json']);
if (!empty($this->getConfig()->getProxyHost()) && $this->getConfig()->getProxyPort() > 0) {
$client->withProxyHost("192.168.0.57")->withProxyPort(12286);
}
$client->get('cgi-bin/user/info', $query);
$client->close();
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$body = json_decode($client->getBody(), true);
if (isset($body['errcode']) && $body['errcode'] != 0) {
return new Result(code: $body['errcode'], message: $body['errmsg']);
}
return new Result(code: 0, data: $body);
}
/**
* @param $encryptedData
* @param $iv
* @param $sessionKey
* @param bool $asArray
* @return object|array
* @throws
*
* * <li>-41001: encodingAesKey 非法</li>
* <li>-41003: aes 解密失败</li>
* <li>-41004: 解密后得到的buffer非法</li>
* <li>-41005: base64加密失败</li>
* <li>-41016: base64解密失败</li>
*/
public function decode($encryptedData, $iv, $sessionKey, bool $asArray = false): object|array
{
$decode = new Decode();
$decode->setSessionKey($sessionKey);
$decode->setEncryptedData($encryptedData);
$decode->setAppId($this->config->getAppid());
$decode->setIv($iv);
return $decode->decode($asArray);
}
/**
* @param $path
* @param $width
* @return array|mixed|Result
* @throws Exception
*/
public function createwxaqrcode($path, $width): mixed
{
$url = 'cgi-bin/wxaapp/createwxaqrcode?access_token=';
$sendBody['path'] = $path;
$sendBody['width'] = $width;
$client = new Client('api.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'application/json']);
$proxyHost = $this->getConfig()->getProxyHost();
$proxyPort = $this->getConfig()->getProxyPort();
if (!empty($proxyHost) && $proxyPort > 0) {
$client->withProxyHost($proxyHost)->withProxyPort($proxyPort);
}
$client->post($url . $this->getConfig()->getAccessToken(), $sendBody);
$client->close();
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$body = json_decode($client->getBody(), true);
if (!is_null($body)) {
return new Result(code: $body['errcode'], message: $body['errmsg']);
} else {
return new Result(code: 0, data: $client->getBody());
}
}
/**
* @param $path
* @param $width
* @param bool $is_hyaline
* @param bool $auto_color
* @param string $line_color
* @return Result
*/
public function getwxacode($path, $width, bool $is_hyaline = false, bool $auto_color = false, string $line_color = ''): Result
{
$sendBody['path'] = $path;
$sendBody['width'] = $width;
$sendBody['auto_color'] = $auto_color;
$sendBody['is_hyaline'] = $is_hyaline;
if ($auto_color) {
$sendBody['line_color'] = $line_color;
}
$url = 'wxa/getwxacode?access_token=' . $this->getConfig()->getAccessToken();
$client = new Client('api.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'application/json']);
$client->post($url . $this->getConfig()->getAccessToken(), $sendBody);
$client->close();
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$body = json_decode($client->getBody(), true);
if (!is_null($body)) {
return new Result(code: $body['errcode'], message: $body['errmsg']);
} else {
return new Result(code: 0, data: $client->getBody());
}
}
/**
* @param $path
* @param $width
* @param bool $is_hyaline
* @param bool $auto_color
* @param string $line_color
* @return Result
*/
public function getwxacodeunlimit($path, $width, bool $is_hyaline = false, bool $auto_color = false, string $line_color = ''): Result
{
$sendBody['path'] = $path;
$sendBody['width'] = $width;
$sendBody['auto_color'] = $auto_color;
$sendBody['is_hyaline'] = $is_hyaline;
if ($auto_color) {
$sendBody['line_color'] = $line_color;
}
$url = 'wxa/getwxacodeunlimit?access_token=' . $this->getConfig()->getAccessToken();
$client = new Client('api.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'application/json']);
$client->post($url . $this->getConfig()->getAccessToken(), $sendBody);
$client->close();
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$body = json_decode($client->getBody(), true);
if (!is_null($body)) {
return new Result(code: $body['errcode'], message: $body['errmsg']);
} else {
return new Result(code: 0, data: $client->getBody());
}
}
}
+145
View File
@@ -0,0 +1,145 @@
<?php
namespace wchat\wx;
/**
* Class ContentAsyncCheck
* @package wchat
*/
class ContentAsyncCheck
{
private mixed $_ToUserName = '';
private mixed $_FromUserName = '';
private mixed $_CreateTime = '';
private mixed $_MsgType = '';
private mixed $_Event = '';
private mixed $_isrisky = '';
private mixed $_extra_info_json = '';
private mixed $_appid = '';
private mixed $_trace_id = '';
private mixed $_status_code = '';
/**
* @return string
*/
public function getToUserName(): mixed
{
return $this->_ToUserName;
}
/**
* @return string
*/
public function getFromUserName(): mixed
{
return $this->_FromUserName;
}
/**
* @return string
*/
public function getCreateTime(): mixed
{
return $this->_CreateTime;
}
/**
* @return string
*/
public function getMsgType(): mixed
{
return $this->_MsgType;
}
/**
* @return string
*/
public function getEvent(): mixed
{
return $this->_Event;
}
/**
* @return string
*/
public function getIsrisky(): mixed
{
return $this->_isrisky;
}
/**
* @return string
*/
public function getExtraInfoJson(): mixed
{
return $this->_extra_info_json;
}
/**
* @return string
*/
public function getAppid(): mixed
{
return $this->_appid;
}
/**
* @return string
*/
public function getTraceId(): mixed
{
return $this->_trace_id;
}
/**
* @return string
*/
public function getStatusCode(): mixed
{
return $this->_status_code;
}
/**
* @param array $params
* @return ContentAsyncCheck
*/
public static function instance(array $params): static
{
static $class = null;
if ($class === null) {
$class = new ContentAsyncCheck();
}
return $class->init($params);
}
/**
* @param $params
* @return $this
*/
private function init($params): static
{
foreach ($params as $item => $param) {
$this->{'_' . $item} = $param;
}
return $this;
}
/**
* @return bool
*/
public function isRisky(): bool
{
return intval($this->_isrisky) === 0;
}
/**
* @return bool
*/
public function isSuccess(): bool
{
return $this->_status_code === 0;
}
}
+325
View File
@@ -0,0 +1,325 @@
<?php
namespace wchat\wx;
use Exception;
use Kiri\Client;
use wchat\common\Result;
/**
* Class Message
* @package wchat\wx
*/
class Message extends SmallProgram
{
private array $msgData = [];
/**
* @param $openid
*/
public function setOpenid($openid)
{
$this->msgData['touser'] = $openid;
}
/**
* @param $content
* @return Result
* @throws Exception
*/
public function sendTextNews($content): Result
{
$this->msgData['msgtype'] = 'text';
$this->msgData['text'] = ['content' => $content];
return $this->sendKefuMsg();
}
/**
* @param $media_id
* @return Result
* @throws Exception
*/
public function sendImageNews($media_id): Result
{
$this->msgData['msgtype'] = 'image';
$this->msgData['image'] = ['media_id' => $media_id];
return $this->sendKefuMsg();
}
/**
* @param $media_id
* @return Result
* @throws Exception
*/
public function sendVoiceNews($media_id): Result
{
$this->msgData['msgtype'] = 'voice';
$this->msgData['voice'] = ['media_id' => $media_id];
return $this->sendKefuMsg();
}
/**
* @param $media_id
* @return Result
* @throws Exception
*/
public function sendMpNewsNews($media_id): Result
{
$this->msgData['msgtype'] = 'mpnews';
$this->msgData['mpnews'] = ['media_id' => $media_id];
return $this->sendKefuMsg();
}
/**
* @param $title
* @param $description
* @param $url
* @param $picurl
* @return Result
* @throws Exception
*/
public function sendNewsNews($title, $description, $url, $picurl): Result
{
$this->msgData['msgtype'] = 'news';
$this->msgData['news'] = [
'articles' => [
[
'title' => $title,
'description' => $description,
'url' => $url,
'picurl' => $picurl
]
]
];
return $this->sendKefuMsg();
}
/**
* @param $title
* @return Result
* @throws Exception
*/
public function sendCardNews($title): Result
{
$this->msgData['msgtype'] = 'wxcard';
$this->msgData['wxcard'] = ['card_id' => $title];
return $this->sendKefuMsg();
}
/**
* @param $media_id
* @param $thumb_media_id
* @param $title
* @param $description
* @return Result
* @throws Exception
*/
public function sendVideoNews($media_id, $thumb_media_id, $title, $description): Result
{
$this->msgData['msgtype'] = 'video';
$this->msgData['video'] = [
'media_id' => [
'media_id' => $media_id,
'thumb_media_id' => $thumb_media_id,
'title' => $title,
'description' => $description
]
];
return $this->sendKefuMsg();
}
/**
* @param $musicurl
* @param $hqmusicurl
* @param $thumb_media_id
* @param $title
* @param $description
* @return Result
* @throws Exception
*/
public function sendMusicNews($musicurl, $hqmusicurl, $thumb_media_id, $title, $description): Result
{
$this->msgData['msgtype'] = 'music';
$this->msgData['music'] = [
'title' => $title,
'description' => $description,
'musicurl' => $musicurl,
'hqmusicurl' => $hqmusicurl,
'thumb_media_id' => $thumb_media_id
];
return $this->sendKefuMsg();
}
/**
* @param $head_content
* @param $tail_content
* @param array $menus
* @return Result
* @throws Exception
*/
public function sendMenuNews($head_content, $tail_content, array $menus = []): Result
{
$this->msgData['msgtype'] = 'msgmenu';
$this->msgData['msgmenu'] = [
'head_content' => $head_content,
'tail_content' => $tail_content,
];
if (empty($menus) || !is_array($menus) || count($menus) < 2) {
throw new Exception('菜单选项必须有2个');
}
foreach ($menus as $val) {
$this->addNewsMenu($val['id'], $val['name']);
}
return $this->sendKefuMsg();
}
private int $index = 0;
/**
* @param $id
* @param $menuName
* @return $this
*/
public function addNewsMenu($id, $menuName): static
{
$lists['id'] = $id;
$lists['content'] = $menuName;
$this->msgData['msgmenu']['list'][$this->index] = $lists;
++$this->index;
return $this;
}
/**
* @param $title
* @param $appid
* @param $pagepath
* @param $thumb_media_id
* @return Result
* @throws Exception
*/
public function sendMiniprogrampageNews($title, $appid, $pagepath, $thumb_media_id): Result
{
$this->msgData['msgtype'] = 'msgmenu';
$this->msgData['miniprogrampage'] = [
'title' => $title,
'appid' => $appid,
'pagepath' => $pagepath,
'thumb_media_id' => $thumb_media_id,
];
return $this->sendKefuMsg();
}
/**
* @param $filePath
* @param $type
* @param bool $isPermanent
* @param string $title
* @param string $introduction
* @return mixed
* @throws Exception
*/
public function upload($filePath, $type, bool $isPermanent = false, string $title = '', string $introduction = ''): Result
{
if (!file_exists($filePath)) {
throw new Exception('文件不存在');
}
if (!in_array($type, ['image', 'voice', 'video', 'thumb'])) {
throw new Exception('暂不支持的文件类型');
}
$token = $this->config->getAccessToken();
if ($isPermanent) {
$url = "/cgi-bin/material/add_material?access_token={$token}&type={$type}";
} else {
$url = "/cgi-bin/media/upload?access_token={$token}&type={$type}";
}
$mime = mime_content_type($filePath);
$real_path = new \CURLFile(realpath($filePath));
$data = ["media" => $real_path, 'form-data[filename]' => $filePath, 'form-data[Content-Type]' => $mime];
if ($isPermanent && $mime == 'video/mp3') {
$data = ['media' => $real_path, 'description[title]' => $title, 'description[introduction]' => $introduction];
}
$client = new Client('api.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'multipart/form-data']);
$proxyHost = $this->getConfig()->getProxyHost();
$proxyPort = $this->getConfig()->getProxyPort();
if (!empty($proxyHost) && $proxyPort > 0) {
$client->withProxyHost($proxyHost)->withProxyPort($proxyPort);
}
$client->post($url, $data);
$client->close();
$this->msgData = [];
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$body = json_decode($client->getBody(), true);
if (isset($body['errcode']) && $body['errcode'] != 0) {
return new Result(code: $body['errcode'], message: $body['errmsg']);
} else {
return new Result(code: 0, data: $body);
}
}
/**
* @return array
*/
public function getContents(): array
{
return $this->msgData;
}
/**
* @return Result
* @throws Exception
*/
private function sendKefuMsg()
{
$url = '/cgi-bin/message/custom/send?access_token=' . $this->config->getAccessToken();
$client = new Client('api.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'application/json']);
$proxyHost = $this->getConfig()->getProxyHost();
$proxyPort = $this->getConfig()->getProxyPort();
if (!empty($proxyHost) && $proxyPort > 0) {
$client->withProxyHost($proxyHost)->withProxyPort($proxyPort);
}
$client->post($url, $this->msgData);
$client->close();
$this->msgData = [];
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$body = json_decode($client->getBody(), true);
if (isset($body['errcode']) && $body['errcode'] != 0) {
return new Result(code: $body['errcode'], message: $body['errmsg']);
} else {
return new Result(code: 0, data: $body);
}
}
}
+553
View File
@@ -0,0 +1,553 @@
<?php
namespace wchat\wx;
use wchat\common\Help;
class Notify extends SmallProgram
{
public mixed $appid = '';
public mixed $mch_id = '';
public mixed $device_info = '';
public mixed $nonce_str = '';
public mixed $sign = '';
public mixed $sign_type = '';
public mixed $result_code = '';
public mixed $err_code = '';
public mixed $err_code_des = '';
public mixed $openid = '';
public mixed $is_subscribe = '';
public mixed $trade_type = '';
public mixed $bank_type = '';
public mixed $total_fee = '';
public mixed $settlement_total_fee = '';
public mixed $fee_type = '';
public mixed $cash_fee = '';
public mixed $cash_fee_type = '';
public mixed $coupon_fee = '';
public mixed $coupon_count = '';
public mixed $coupon_type_n = '';
public mixed $coupon_id_n = '';
public mixed $coupon_fee_n = '';
public mixed $transaction_id = '';
public mixed $out_trade_no = '';
public mixed $attach = '';
public mixed $time_end = '';
public mixed $return_code = '';
/**
* @return bool
* 判断是否完成支付
*/
public function isSuccess(): bool
{
if ($this->getReturnCode() != "SUCCESS") {
return false;
}
if ($this->getResultCode() != 'SUCCESS') {
return false;
}
return true;
}
/**
* @param array $params
* @return $this
*/
public function setPayNotifyData(array $params): static
{
if (!$this->validation($params)) {
$this->setResultCode('FAIL');
$this->setErrCodeDes('签名错误');
unset($params['result_code'], $params['err_code_des']);
}
foreach ($params as $key => $val) {
$this->__set($key, $val);
}
return $this;
}
/**
* @param string $name
* @param $value
* @return void
*/
public function __set(string $name, $value): void
{
if (property_exists($this, $name)) {
$this->$name = $value;
}
}
/**
* @param array $params
* @return bool
*/
public function validation(array $params): bool
{
$sign = $params['sign'];
unset($params['sign']);
$signType = $this->config->getSignType();
$privateKey = $this->config->getKey();
$nowSign = Help::sign($params, $privateKey, $signType);
if ($sign === $nowSign) {
return true;
}
return false;
}
/**
* @return mixed|string
*/
public function getAppid(): mixed
{
return $this->appid;
}
/**
* @param mixed|string $appid
*/
public function setAppid(mixed $appid): void
{
$this->appid = $appid;
}
/**
* @return mixed|string
*/
public function getMchId(): mixed
{
return $this->mch_id;
}
/**
* @param mixed|string $mch_id
*/
public function setMchId(mixed $mch_id): void
{
$this->mch_id = $mch_id;
}
/**
* @return mixed|string
*/
public function getDeviceInfo(): mixed
{
return $this->device_info;
}
/**
* @param mixed|string $device_info
*/
public function setDeviceInfo(mixed $device_info): void
{
$this->device_info = $device_info;
}
/**
* @return mixed|string
*/
public function getNonceStr(): mixed
{
return $this->nonce_str;
}
/**
* @param mixed|string $nonce_str
*/
public function setNonceStr(mixed $nonce_str): void
{
$this->nonce_str = $nonce_str;
}
/**
* @return mixed|string
*/
public function getSign(): mixed
{
return $this->sign;
}
/**
* @param mixed|string $sign
*/
public function setSign(mixed $sign): void
{
$this->sign = $sign;
}
/**
* @return mixed|string
*/
public function getSignType(): mixed
{
return $this->sign_type;
}
/**
* @param mixed|string $sign_type
*/
public function setSignType(mixed $sign_type): void
{
$this->sign_type = $sign_type;
}
/**
* @return mixed|string
*/
public function getResultCode(): mixed
{
return $this->result_code;
}
/**
* @param mixed|string $result_code
*/
public function setResultCode(mixed $result_code): void
{
$this->result_code = $result_code;
}
/**
* @return mixed|string
*/
public function getErrCode(): mixed
{
return $this->err_code;
}
/**
* @param mixed|string $err_code
*/
public function setErrCode(mixed $err_code): void
{
$this->err_code = $err_code;
}
/**
* @return mixed|string
*/
public function getErrCodeDes(): mixed
{
return $this->err_code_des;
}
/**
* @param mixed|string $err_code_des
*/
public function setErrCodeDes(mixed $err_code_des): void
{
$this->err_code_des = $err_code_des;
}
/**
* @return mixed|string
*/
public function getOpenid(): mixed
{
return $this->openid;
}
/**
* @param mixed|string $openid
*/
public function setOpenid(mixed $openid): void
{
$this->openid = $openid;
}
/**
* @return mixed|string
*/
public function getIsSubscribe(): mixed
{
return $this->is_subscribe;
}
/**
* @param mixed|string $is_subscribe
*/
public function setIsSubscribe(mixed $is_subscribe): void
{
$this->is_subscribe = $is_subscribe;
}
/**
* @return mixed|string
*/
public function getTradeType(): mixed
{
return $this->trade_type;
}
/**
* @param mixed|string $trade_type
*/
public function setTradeType(mixed $trade_type): void
{
$this->trade_type = $trade_type;
}
/**
* @return mixed|string
*/
public function getBankType(): mixed
{
return $this->bank_type;
}
/**
* @param mixed|string $bank_type
*/
public function setBankType(mixed $bank_type): void
{
$this->bank_type = $bank_type;
}
/**
* @return mixed|string
*/
public function getTotalFee(): mixed
{
return $this->total_fee;
}
/**
* @param mixed|string $total_fee
*/
public function setTotalFee(mixed $total_fee): void
{
$this->total_fee = $total_fee;
}
/**
* @return mixed|string
*/
public function getSettlementTotalFee(): mixed
{
return $this->settlement_total_fee;
}
/**
* @param mixed|string $settlement_total_fee
*/
public function setSettlementTotalFee(mixed $settlement_total_fee): void
{
$this->settlement_total_fee = $settlement_total_fee;
}
/**
* @return mixed|string
*/
public function getFeeType(): mixed
{
return $this->fee_type;
}
/**
* @param mixed|string $fee_type
*/
public function setFeeType(mixed $fee_type): void
{
$this->fee_type = $fee_type;
}
/**
* @return mixed|string
*/
public function getCashFee(): mixed
{
return $this->cash_fee;
}
/**
* @param mixed|string $cash_fee
*/
public function setCashFee(mixed $cash_fee): void
{
$this->cash_fee = $cash_fee;
}
/**
* @return mixed|string
*/
public function getCashFeeType(): mixed
{
return $this->cash_fee_type;
}
/**
* @param mixed|string $cash_fee_type
*/
public function setCashFeeType(mixed $cash_fee_type): void
{
$this->cash_fee_type = $cash_fee_type;
}
/**
* @return mixed|string
*/
public function getCouponFee(): mixed
{
return $this->coupon_fee;
}
/**
* @param mixed|string $coupon_fee
*/
public function setCouponFee(mixed $coupon_fee): void
{
$this->coupon_fee = $coupon_fee;
}
/**
* @return mixed|string
*/
public function getCouponCount(): mixed
{
return $this->coupon_count;
}
/**
* @param mixed|string $coupon_count
*/
public function setCouponCount(mixed $coupon_count): void
{
$this->coupon_count = $coupon_count;
}
/**
* @return mixed|string
*/
public function getCouponTypeN(): mixed
{
return $this->coupon_type_n;
}
/**
* @param mixed|string $coupon_type_n
*/
public function setCouponTypeN(mixed $coupon_type_n): void
{
$this->coupon_type_n = $coupon_type_n;
}
/**
* @return mixed|string
*/
public function getCouponIdN(): mixed
{
return $this->coupon_id_n;
}
/**
* @param mixed|string $coupon_id_n
*/
public function setCouponIdN(mixed $coupon_id_n): void
{
$this->coupon_id_n = $coupon_id_n;
}
/**
* @return mixed|string
*/
public function getCouponFeeN(): mixed
{
return $this->coupon_fee_n;
}
/**
* @param mixed|string $coupon_fee_n
*/
public function setCouponFeeN(mixed $coupon_fee_n): void
{
$this->coupon_fee_n = $coupon_fee_n;
}
/**
* @return mixed|string
*/
public function getTransactionId(): mixed
{
return $this->transaction_id;
}
/**
* @param mixed|string $transaction_id
*/
public function setTransactionId(mixed $transaction_id): void
{
$this->transaction_id = $transaction_id;
}
/**
* @return mixed|string
*/
public function getOutTradeNo(): mixed
{
return $this->out_trade_no;
}
/**
* @param mixed|string $out_trade_no
*/
public function setOutTradeNo(mixed $out_trade_no): void
{
$this->out_trade_no = $out_trade_no;
}
/**
* @return mixed|string
*/
public function getAttach(): mixed
{
return $this->attach;
}
/**
* @param mixed|string $attach
*/
public function setAttach(mixed $attach): void
{
$this->attach = $attach;
}
/**
* @return mixed|string
*/
public function getTimeEnd(): mixed
{
return $this->time_end;
}
/**
* @param mixed|string $time_end
*/
public function setTimeEnd(mixed $time_end): void
{
$this->time_end = $time_end;
}
/**
* @return mixed|string
*/
public function getReturnCode(): mixed
{
return $this->return_code;
}
/**
* @param mixed|string $return_code
*/
public function setReturnCode(mixed $return_code): void
{
$this->return_code = $return_code;
}
}
+169
View File
@@ -0,0 +1,169 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/8 0008
* Time: 9:49
*/
namespace wchat\wx;
use Kiri\Client;
use wchat\common\Result;
class PublicTemplate extends SmallProgram
{
private array $keywords = [];
private string $templateId = '';
private array $first = [];
private array $remark = [];
private string $openId = '';
private string $defaultUrl = 'http://weixin.qq.com/download';
private string $sendUrl = '/cgi-bin/message/template/send';
private array $miniprogram = [];
/**
* @param array $keywords
*/
public function setKeywords(array $keywords)
{
$this->keywords = $keywords;
}
/**
* @param $templateId
*/
public function setTemplateId($templateId)
{
$this->templateId = $templateId;
}
/**
* @param $openId
*/
public function setOpenId($openId)
{
$this->openId = $openId;
}
/**
* @param $defaultUrl
*/
public function setDefaultUrl($defaultUrl)
{
$this->defaultUrl = $defaultUrl;
}
/**
* @param $name
* @param $context
* @param string $color
*/
public function replaceKeyword($name, $context, string $color = '')
{
$this->keywords[$name] = ['value' => $context, 'color' => $color];
}
/**
* @param $name
* @param $context
* @param null $color
*/
public function addKeyword($name, $context, $color = null)
{
if (empty($color)) {
$color = '#000';
}
$this->keywords[$name] = [
'value' => $context,
'color' => $color
];
}
/**
* @param $context
* @param string $color
* @return void
*/
public function setFirst($context, string $color = '#f00'): void
{
$this->first = [
'value' => $context,
'color' => $color
];
}
/**
* @param $context
* @param string $color
* @return void
*/
public function setRemark($context, string $color = '#000'): void
{
$this->remark = [
'value' => $context,
'color' => $color
];
}
/**
* @param $appid
* @param string $pagepath
* @return void
*/
public function setMiniprogram($appid, string $pagepath): void
{
$this->miniprogram = [
'appid' => $appid,
'pagepath' => $pagepath
];
}
/**
* @return Result
* @throws \Exception
*
* 奴隶交易通知
*/
public function sendTemplate(): Result
{
$url = $this->sendUrl . '?access_token=' . $this->config->getAccessToken();
$keywords = $this->keywords;
$keywords['first'] = $this->first;
$keywords['remark'] = $this->remark;
$default = [
"touser" => $this->openId,
"template_id" => $this->templateId,
"url" => $this->defaultUrl,
"data" => $keywords,
];
if (!empty($this->miniprogram)) {
$default['miniprogram'] = $this->miniprogram;
}
$client = new Client('api.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'application/json']);
$proxyHost = $this->getConfig()->getProxyHost();
$proxyPort = $this->getConfig()->getProxyPort();
if (!empty($proxyHost) && $proxyPort > 0) {
$client->withProxyHost($proxyHost)->withProxyPort($proxyPort);
}
$client->post($url, $default);
$client->close();
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$body = json_decode($client->getBody(), true);
if (isset($body['errcode']) && $body['errcode'] != 0) {
return new Result(code: $body['errcode'], message: $body['errmsg']);
} else {
return new Result(code: 0, data: $body);
}
}
}
+136
View File
@@ -0,0 +1,136 @@
<?php
namespace wchat\wx;
use Kiri\Client;
use wchat\common\Result;
/**
* Class SecCheck
* @package wchat
*/
class SecCheck extends SmallProgram
{
private string $_url = '/wxa/img_sec_check?access_token=';
private string $_msgUrl = '/wxa/msg_sec_check?access_token=';
private string $_mediaCheckAsync = '/wxa/media_check_async?access_token=';
const MEDIA_VIDEO = 1;
const MEDIA_IMAGE = 1;
/**
* @param string $path
* @return Result
*/
public function image(string $path = ''): Result
{
if (!file_exists($path)) {
return $this->sendError('文件不存在', 404);
}
$access_token = $this->config->getAccessToken();
$client = new Client('api.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'multipart/form-data']);
$proxyHost = $this->getConfig()->getProxyHost();
$proxyPort = $this->getConfig()->getProxyPort();
if (!empty($proxyHost) && $proxyPort > 0) {
$client->withProxyHost($proxyHost)->withProxyPort($proxyPort);
}
$client->upload($this->_url . '?access_token=' . $access_token, [
'media' => new \CURLFile($path)
]);
$client->close();
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$body = json_decode($client->getBody(), true);
if (isset($body['errcode']) && $body['errcode'] != 0) {
return new Result(code: $body['errcode'], message: $body['errmsg']);
}
return new Result(code: 0, data: $body);
}
/**
* @param string $url
* @param int $type
* @return mixed
* @throws
*/
public function mediaAsync(string $url, int $type = SecCheck::MEDIA_IMAGE): Result
{
if (!in_array($type, [self::MEDIA_IMAGE, self::MEDIA_VIDEO])) {
throw new \Exception('暂不支持的文件类型');
}
$requestUrl = $this->_mediaCheckAsync . $this->config->getAccessToken();
$client = new Client('api.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'application/json']);
$proxyHost = $this->getConfig()->getProxyHost();
$proxyPort = $this->getConfig()->getProxyPort();
if (!empty($proxyHost) && $proxyPort > 0) {
$client->withProxyHost($proxyHost)->withProxyPort($proxyPort);
}
$client->post($requestUrl, ['media_url' => $url, 'media_type' => $type]);
$client->close();
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$body = json_decode($client->getBody(), true);
if (isset($body['errcode']) && $body['errcode'] != 0) {
return new Result(code: $body['errcode'], message: $body['errmsg']);
} else {
return new Result(code: 0, data: $body);
}
}
/**
* @param $params
* @return ContentAsyncCheck|null
*/
public function readByEvent($params): ?ContentAsyncCheck
{
return ContentAsyncCheck::instance($params);
}
/**
* @param $content
* @return Result
*/
public function text($content): Result
{
if (empty($content)) {
return $this->sendError('文件不存在', 404);
}
$requestUrl = $this->_msgUrl . $this->config->getAccessToken();
$client = new Client('api.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'application/json']);
$proxyHost = $this->getConfig()->getProxyHost();
$proxyPort = $this->getConfig()->getProxyPort();
if (!empty($proxyHost) && $proxyPort > 0) {
$client->withProxyHost($proxyHost)->withProxyPort($proxyPort);
}
$client->post($requestUrl, ['content' => $content]);
$client->close();
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$body = json_decode($client->getBody(), true);
if (isset($body['errcode']) && $body['errcode'] != 0) {
return new Result(code: $body['errcode'], message: $body['errmsg']);
} else {
return new Result(code: 0, data: $body);
}
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace wchat\wx;
use wchat\common\Multiprogramming;
class SmallProgram extends Multiprogramming
{
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace wchat\wx;
use wchat\common\Result;
/**
* Class Subject
* @package wchat\wx
*/
class Subject extends \wchat\base\Subject
{
/**
* @return string
*/
public function getUrl(): string
{
return 'cgi-bin/message/subscribe/send';
}
/**
* @return string
*/
public function getHost(): string
{
return 'api.weixin.qq.com';
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/8 0008
* Time: 9:49
*/
namespace wchat\wx;
/**
* Class Template
* @package wchat\wx
*/
class Template extends \wchat\base\Template
{
/**
* @return string
*/
public function getUrl(): string
{
return '/cgi-bin/message/wxopen/template/send';
}
/**
* @return string
*/
public function getHost(): string
{
return 'api.weixin.qq.com';
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace wchat\wx;
use Kiri\Client;
use wchat\common\Result;
class Token extends SmallProgram
{
/**
* @return Result
*/
public function token(): Result
{
$query = [
'grant_type' => 'client_credential',
'appid' => $this->config->getAppid(),
'secret' => $this->config->getAppsecret()
];
$client = new Client('api.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'application/json']);
$proxyHost = $this->getConfig()->getProxyHost();
$proxyPort = $this->getConfig()->getProxyPort();
if (!empty($proxyHost) && $proxyPort > 0) {
$client->withProxyHost($proxyHost)->withProxyPort($proxyPort);
}
$client->get('cgi-bin/token', $query);
$client->close();
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$body = json_decode($client->getBody(), true);
if (isset($body['errcode']) && $body['errcode'] != 0) {
return new Result(code: $body['errcode'], message: $body['errmsg']);
}
return new Result(code: 0, data: $body);
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
namespace wchat\wx\V2;
use Kiri\Client;
use wchat\common\Help;
use wchat\common\Result;
use wchat\wx\SmallProgram;
class WxV2AppPayment extends SmallProgram
{
private string $uniformed = '/pay/unifiedorder';
use WxV2PayTait;
/**
* @param int $money
* @param string $orderNo
* @param string $spbill_create_ip
* @return Result
*/
public function payment(int $money, string $orderNo, string $spbill_create_ip = '127.0.0.1'): Result
{
if ($money < 0) {
return new Result(code: 400, message: '充值金额不能小于0.');
}
$body = $this->getInitCore($orderNo, $money);
$body['trade_type'] = 'APP';
$body['spbill_create_ip'] = $spbill_create_ip;
$client = new Client('api.mch.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'application/json']);
$proxyHost = $this->getConfig()->getProxyHost();
$proxyPort = $this->getConfig()->getProxyPort();
if (!empty($proxyHost) && $proxyPort > 0) {
$client->withProxyHost($proxyHost)->withProxyPort($proxyPort);
}
$client->withBody($this->sign($body));
$client->post($this->uniformed);
$client->close();
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$data = Help::toArray($client->getBody());
if (isset($data['return_code']) && $data['return_code'] != 'SUCCESS') {
return new Result(code: 503, message: $data['return_msg']);
}
if ($data['result_code'] != 'SUCCESS') {
return new Result(code: 504, message: $data['err_code_des']);
}
return new Result(code: 0, data: $this->reception($data['prepayid']));
}
/**
* @param string $prepay_id
* @return string
*/
public function reception(string $prepay_id): string
{
return $this->sign([
'appId' => $this->config->getAppid(),
'partnerid' => $this->config->getMchId(),
'prepayid' => $prepay_id,
'package' => 'Sign=WXPay',
'noncestr' => Help::random(32),
'timestamp' => time()
]);
}
}
+230
View File
@@ -0,0 +1,230 @@
<?php
namespace wchat\wx\V2;
use Kiri\Client;
use Phalcon\Cache\Frontend\Json;
use wchat\common\Help;
use wchat\common\Result;
use wchat\wx\SmallProgram;
class WxV2PayJsApi extends SmallProgram
{
private string $uniformed = '/pay/unifiedorder';
use WxV2PayTait;
/**
* @param int $money
* @param string $orderNo
* @param string $openId
* @param string $spbill_create_ip
* @return Result
*/
public function applet(int $money, string $orderNo, string $openId, string $spbill_create_ip = '127.0.0.1'): Result
{
if ($money < 0) {
return new Result(code: 400, message: '充值金额不能小于0.');
}
$body = $this->getInitCore($orderNo, $money);
$body['trade_type'] = 'JSAPI';
$body['spbill_create_ip'] = $spbill_create_ip;
$body['openid'] = $openId;
$client = new Client('api.mch.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'application/json']);
$client->withBody($this->sign($body));
$proxyHost = $this->getConfig()->getProxyHost();
$proxyPort = $this->getConfig()->getProxyPort();
if (!empty($proxyHost) && $proxyPort > 0) {
$client->withProxyHost($proxyHost)->withProxyPort($proxyPort);
}
$client->post($this->uniformed);
$client->close();
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$data = Help::toArray($client->getBody());
if (isset($data['return_code']) && $data['return_code'] != 'SUCCESS') {
return new Result(code: 503, message: $data['return_msg']);
}
if ($data['result_code'] != 'SUCCESS') {
return new Result(code: 504, message: $data['err_code_des']);
}
return new Result(code: 0, data: $this->reception($data['prepayid']));
}
/**
* @param int $money
* @param string $orderNo
* @param string $app_name
* @param string $package_name
* @param string $spbill_create_ip
* @return Result
*/
public function h5Android(int $money, string $orderNo, string $app_name, string $package_name, string $spbill_create_ip = '127.0.0.1'): Result
{
if ($money < 0) {
return new Result(code: 400, message: '充值金额不能小于0.');
}
$body = $this->getInitCore($orderNo, $money);
$body['trade_type'] = 'MWEB';
$body['spbill_create_ip'] = $spbill_create_ip;
$body['scene_info'] = json_encode([
'h5_info' => [
'type' => 'Android',
'app_name' => $app_name,
'package_name' => $package_name
]
], JSON_UNESCAPED_UNICODE);
$client = new Client('api.mch.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'application/json']);
$client->withBody($this->sign($body));
$proxyHost = $this->getConfig()->getProxyHost();
$proxyPort = $this->getConfig()->getProxyPort();
if (!empty($proxyHost) && $proxyPort > 0) {
$client->withProxyHost($proxyHost)->withProxyPort($proxyPort);
}
$client->post($this->uniformed);
$client->close();
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$data = Help::toArray($client->getBody());
if (isset($data['return_code']) && $data['return_code'] != 'SUCCESS') {
return new Result(code: 503, message: $data['return_msg']);
}
if ($data['result_code'] != 'SUCCESS') {
return new Result(code: 504, message: $data['err_code_des']);
}
return new Result(code: 0, data: $this->reception($data['prepayid']));
}
/**
* @param int $money
* @param string $orderNo
* @param string $app_name
* @param string $bundle_id
* @param string $spbill_create_ip
* @return Result
*/
public function h5Ios(int $money, string $orderNo, string $app_name, string $bundle_id, string $spbill_create_ip = '127.0.0.1'): Result
{
if ($money < 0) {
return new Result(code: 400, message: '充值金额不能小于0.');
}
$body = $this->getInitCore($orderNo, $money);
$body['trade_type'] = 'MWEB';
$body['spbill_create_ip'] = $spbill_create_ip;
$body['scene_info'] = json_encode([
'h5_info' => [
'type' => 'IOS',
'app_name' => $app_name,
'bundle_id' => $bundle_id
]
], JSON_UNESCAPED_UNICODE);
$client = new Client('api.mch.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'application/json']);
$client->withBody($this->sign($body));
$proxyHost = $this->getConfig()->getProxyHost();
$proxyPort = $this->getConfig()->getProxyPort();
if (!empty($proxyHost) && $proxyPort > 0) {
$client->withProxyHost($proxyHost)->withProxyPort($proxyPort);
}
$client->post($this->uniformed);
$client->close();
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$data = Help::toArray($client->getBody());
if (isset($data['return_code']) && $data['return_code'] != 'SUCCESS') {
return new Result(code: 503, message: $data['return_msg']);
}
if ($data['result_code'] != 'SUCCESS') {
return new Result(code: 504, message: $data['err_code_des']);
}
return new Result(code: 0, data: $this->reception($data['prepayid']));
}
/**
* @param int $money
* @param string $orderNo
* @param string $wap_url
* @param string $wap_name
* @param string $spbill_create_ip
* @return Result
*/
public function h5(int $money, string $orderNo, string $wap_url, string $wap_name, string $spbill_create_ip = '127.0.0.1'): Result
{
if ($money < 0) {
return new Result(code: 400, message: '充值金额不能小于0.');
}
$body = $this->getInitCore($orderNo, $money);
$body['trade_type'] = 'MWEB';
$body['spbill_create_ip'] = $spbill_create_ip;
$body['scene_info'] = json_encode([
'h5_info' => [
'type' => 'IOS',
'wap_url' => $wap_url,
'wap_name' => $wap_name
]
], JSON_UNESCAPED_UNICODE);
$client = new Client('api.mch.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'application/json']);
$client->withBody($this->sign($body));
$proxyHost = $this->getConfig()->getProxyHost();
$proxyPort = $this->getConfig()->getProxyPort();
if (!empty($proxyHost) && $proxyPort > 0) {
$client->withProxyHost($proxyHost)->withProxyPort($proxyPort);
}
$client->post($this->uniformed);
$client->close();
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$data = Help::toArray($client->getBody());
if (isset($data['return_code']) && $data['return_code'] != 'SUCCESS') {
return new Result(code: 503, message: $data['return_msg']);
}
if ($data['result_code'] != 'SUCCESS') {
return new Result(code: 504, message: $data['err_code_des']);
}
return new Result(code: 0, data: $this->reception($data['prepayid']));
}
/**
* @param string $prepay_id
* @return string
*/
public function reception(string $prepay_id): string
{
return $this->sign([
'signType' => $this->config->getSignType(),
'package' => 'prepay_id=' . $prepay_id,
'nonceStr' => Help::random(32),
'timestamp' => time()
]);
}
}
+100
View File
@@ -0,0 +1,100 @@
<?php
namespace wchat\wx\V2;
use JetBrains\PhpStorm\ArrayShape;
use wchat\common\Help;
trait WxV2PayTait
{
/**
* 'appId' => $result['appid'],
* 'nonceStr' => $result['nonce_str'],
* 'package' => 'prepay_id=' . $result['prepay_id'],
* 'signType' => 'MD5',
* 'timeStamp' => (string)time(),
* @param $prepay_id
* @return array
*/
#[ArrayShape(['appId' => "string", 'nonceStr' => "string", 'package' => "string", 'signType' => "string", 'timeStamp' => "string", 'paySign' => "string"])]
public function reception($prepay_id): array
{
$array = [
'appId' => $this->config->getAppid(),
'nonceStr' => Help::random(32),
'package' => 'prepay_id=' . $prepay_id,
'signType' => 'MD5',
'timeStamp' => (string)time(),
];
$key = $this->config->getKey();
$sign_type = $this->config->getSignType();
$array['paySign'] = Help::sign($array, $key, $sign_type);
return $array;
}
/**
* @param string $orderNo
* @param float|int $total
* @return array
*/
#[ArrayShape(['appid' => "string", 'mch_id' => "string", 'nonce_str' => "string", 'body' => "string", 'out_trade_no' => "string", 'total_fee' => "float|int", 'spbill_create_ip' => "mixed", 'notify_url' => "string", 'trade_type' => "string"])]
protected function getInitCore(string $orderNo, float|int $total): array
{
return [
'appid' => $this->config->getAppid(),
'mch_id' => $this->config->getMchId(),
'nonce_str' => Help::random(32),
'body' => $this->config->getBody(),
'out_trade_no' => $orderNo,
'total_fee' => $total,
'notify_url' => $this->config->getNotifyUrl(),
'trade_type' => $this->config->getTradeType(),
];
}
/**
* @param array $data
* @return string
*/
protected function sign(array $data): string
{
$key = $this->config->getKey();
$sign_type = $this->config->getSignType();
$data['sign'] = Help::sign($data, $key, $sign_type);
return Help::toXml($data);
}
/**
* @param string $orderNo
* @param int|float $money
* @param string $openid
* @return string
*/
protected function builder(string $orderNo, int|float $money, string $openid): string
{
$data = [
'appid' => $this->config->getAppid(),
'mch_id' => $this->config->getMchId(),
'nonce_str' => Help::random(32),
'body' => $this->config->getBody(),
'out_trade_no' => $orderNo,
'total_fee' => $money,
'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
'notify_url' => $this->config->getNotifyUrl(),
'trade_type' => $this->config->getTradeType(),
'openid' => $openid
];
$key = $this->config->getKey();
$sign_type = $this->config->getSignType();
$data['sign'] = Help::sign($data, $key, $sign_type);
return Help::toXml($data);
}
}
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace wchat\wx\V2;
use Kiri\Client;
use wchat\common\Help;
use wchat\common\Result;
use wchat\wx\SmallProgram;
class WxV2Withdrawal extends SmallProgram
{
private string $transfers = '/mmpaymkttransfers/promotion/transfers';
/**
* @param int|float $money
* @param string $openid
* @param string $order
* @param string $desc
* @return Result
*/
public function payment(int|float $money, string $openid, string $order, string $desc = '零钱提现'): Result
{
$array = [
'nonce_str' => Help::random(32),
'partner_trade_no' => $order,
'mchid' => $this->config->getMchId(),
'mch_appid' => $this->config->getAppid(),
'openid' => $openid,
'check_name' => 'NO_CHECK',
'amount' => $money * 100,
'spbill_create_ip' => $this->config->getRemoteAddr(),
'desc' => $desc,
];
$key = $this->config->getKey();
$sign_type = $this->config->getSignType();
$array['sign'] = Help::sign($array, $key, $sign_type);
$client = new Client('api.mch.weixin.qq.com', 443, true);
$client->withHeader(['Content-Type' => 'application/json']);
$client->withBody($body = Help::toXml($array));
$proxyHost = $this->getConfig()->getProxyHost();
$proxyPort = $this->getConfig()->getProxyPort();
if (!empty($proxyHost) && $proxyPort > 0) {
$client->withProxyHost($proxyHost)->withProxyPort($proxyPort);
}
$client->post($this->transfers);
$client->close();
if (!in_array($client->getStatusCode(), [101, 200, 201])) {
return new Result(code: 505, message: $client->getBody());
}
$data = Help::toArray($client->getBody());
$data['body'] = $body;
if ($data['return_code'] == 'FAIL') {
return new Result(code: $array['return_code'], message: $data['return_msg'], data: $data);
} else if ($array['result_code'] != 'SUCCESS') {
return new Result(code: $array['err_code'], message: $data['err_code_des'], data: $data);
} else {
return new Result(code: 0, message: '提现成功', data: $data);
}
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace wchat\wx\V3\Notify;
class GoodsDetail
{
public string $goods_remark = "商品备注信息";
public int $quantity = 1;
public int $discount_amount = 1;
public string $goods_id = "M1006";
public int $unit_price = 100;
/**
* @param array $value
*/
public function __construct(readonly public array $value)
{
$this->goods_remark = $this->value['goods_remark'];
$this->quantity = $this->value['quantity'];
$this->discount_amount = $this->value['discount_amount'];
$this->goods_id = $this->value['goods_id'];
$this->unit_price = $this->value['unit_price'];
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
namespace wchat\wx\V3\Notify;
use JetBrains\PhpStorm\ArrayShape;
class NotifyModel
{
//公众号支付
const PAY_TYPE_JSAPI = 'JSAPI';
//扫码支付
const PAY_TYPE_NATIVE = 'NATIVE';
//App支付
const PAY_TYPE_App = 'App';
//付款码支付
const PAY_TYPE_MICROPAY = 'MICROPAY';
//H5支付
const PAY_TYPE_MWEB = 'MWEB';
//刷脸支付
const PAY_TYPE_FACEPAY = 'FACEPAY';
// 支付成功
const PAY_RESULT_SUCCESS = 'SUCCESS';
// 转入退款
const PAY_RESULT_REFUND = 'REFUND';
// 未支付
const PAY_RESULT_NOTPAY = 'NOTPAY';
// 已关闭
const PAY_RESULT_CLOSED = 'CLOSED';
// 已撤销(付款码支付)
const PAY_RESULT_REVOKED = 'REVOKED';
// 用户支付中(付款码支付)
const PAY_RESULT_USERPAYING = 'USERPAYING';
// 支付失败(其他原因,如银行返回失败)
const PAY_RESULT_PAYERROR = 'PAYERROR';
public string $appid;
public string $mchid;
public string $out_trade_no;
public string $transaction_id;
public string $trade_type;
public string $trade_state;
public string $trade_state_desc;
public string $bank_type;
public string $attach;
public string $success_time;
/**
* @var array|string[]
*/
#[ArrayShape(['openid' => 'string'])]
public array $payer = ['openid' => ''];
/**
* @var array
*/
#[ArrayShape(['payer_total' => 'int', 'total' => 'int', 'currency' => 'string', 'payer_currency' => 'string'])]
public array $amount = [
"payer_total" => 100,
"total" => 100,
"currency" => "CNY",
"payer_currency" => "CNY"
];
/**
* @var array|string[]
*/
#[ArrayShape(['device_id' => 'string'])]
public array $scene_info = [
'device_id' => ''
];
/**
* @var array<PromotionDetail>
*/
public array $promotion_detail = [];
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace wchat\wx\V3\Notify;
class PromotionDetail
{
public int $amount = 100;
public int $wechatpay_contribute = 0;
public string $coupon_id = "109519";
public string $scope = "GLOBAL";
public int $merchant_contribute = 0;
public string $name = "单品惠-6";
public int $other_contribute = 0;
public string $currency = "CNY";
public string $stock_id = "931386";
/**
* @var array<GoodsDetail>
*/
public array $goods_detail = [];
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace wchat\wx\V3;
use Exception;
use JetBrains\PhpStorm\ArrayShape;
use Kiri\Client;
use Kiri\CurlClient;
use wchat\wx\SmallProgram;
class TransferBatches extends SmallProgram
{
use WxV3PaymentTait;
/**
* @param TransferDetail $detail
* @return array
* @throws Exception
*/
#[ArrayShape([])]
public function request(TransferDetail $detail): array
{
$payConfig = $this->getPayConfig();
$body = [];
if ($payConfig->typeIsApp()) {
$body['appid'] = $payConfig->pay->wx->appId;
} else {
$body['appid'] = $payConfig->appId;
}
$body['out_batch_no'] = $detail->out_detail_no;
$body["batch_name"] = $payConfig->getBody();
$body["body"] = $payConfig->getBody();
$body["batch_remark"] = $payConfig->getBody();
$body["total_amount"] = $detail->transfer_amount;
$body["total_num"] = 1;
$body["transfer_detail_list"] = [$detail->toArray()];
$sign = $this->signature('POST', '/v3/transfer/batches', $json = json_encode($body, JSON_UNESCAPED_UNICODE));
$client = $this->createClient($sign, $json);
$client->post('/v3/transfer/batches');
$client->close();
$data = json_decode($client->getBody(), TRUE);
if (json_last_error() != JSON_ERROR_NONE) {
return ['code' => $client->getStatusCode(), 'message' => $client->getBody()];
} else {
return $data;
}
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace wchat\wx\V3;
use JetBrains\PhpStorm\ArrayShape;
class TransferDetail
{
/**
* @param string $out_detail_no
* @param int|float $transfer_amount
* @param string $transfer_remark
* @param string $openid
* @param string $user_name
*/
public function __construct(
readonly public string $out_detail_no,
readonly public int|float $transfer_amount,
readonly public string $transfer_remark,
readonly public string $openid,
readonly public string $user_name = ''
)
{
}
/**
* @return array
*/
#[ArrayShape(['out_detail_no' => "string", 'transfer_amount' => "float|int", 'transfer_remark' => "string", 'openid' => "string", 'user_name' => "string"])]
public function toArray(): array
{
if (empty($this->user_name)) {
return [
'out_detail_no' => $this->out_detail_no,
'transfer_amount' => $this->transfer_amount,
'transfer_remark' => $this->transfer_remark,
'openid' => $this->openid,
];
}
return [
'out_detail_no' => $this->out_detail_no,
'transfer_amount' => $this->transfer_amount,
'transfer_remark' => $this->transfer_remark,
'openid' => $this->openid,
'user_name' => $this->user_name,
];
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace wchat\wx\V3;
use Exception;
use Kiri\Client;
use wchat\wx\SmallProgram;
class WxV3AppPayment extends SmallProgram
{
use WxV3PaymentTait;
/**
* @param $orderNo
* @param int $total
* @param string|null $openId
* @param string $payer_client_ip
* @return array
* @throws Exception
*/
public function payment($orderNo, int $total, string $openId = NULL, string $payer_client_ip = '127.0.0.1'): array
{
$body = $this->getInitCore($orderNo, $total);
$body['scene_info'] = ['payer_client_ip' => $payer_client_ip];
$sign = $this->signature('POST', '/v3/pay/transactions/components', $json = json_encode($body, JSON_UNESCAPED_UNICODE));
$client = $this->createClient($sign, $json);
$client->post('/v3/pay/transactions/components');
$client->close();
$json = json_decode($client->getBody(), TRUE);
if (!isset($json['prepay_id'])) {
throw new Exception('微信支付调用失败');
}
return $this->createResponse($json, $body);
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace wchat\wx\V3;
use Exception;
use Kiri\Client;
use JetBrains\PhpStorm\ArrayShape;
use wchat\wx\SmallProgram;
class WxV3NativePayment extends SmallProgram
{
use WxV3PaymentTait;
/**
* @param $orderNo
* @param int $total
* @param string|null $openId
* @param string $payer_client_ip
* @return array
* @throws Exception
*/
#[ArrayShape(['code_url' => "string"])]
public function payment($orderNo, int $total, string $openId = NULL, string $payer_client_ip = '127.0.0.1'): array
{
$body = $this->getInitCore($orderNo, $total);
$sign = $this->signature('POST', '/v3/pay/transactions/native', $json = json_encode($body, JSON_UNESCAPED_UNICODE));
$client = $this->createClient($sign, $json);
$client->post('/v3/pay/transactions/native');
$client->close();
$json = json_decode($client->getBody(), TRUE);
if (!isset($json['code_url'])) {
throw new Exception('微信支付调用失败');
}
return ['code_url' => $json['code_url']];
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace wchat\wx\V3;
use Exception;
use Kiri\Client;
use wchat\wx\SmallProgram;
class WxV3Payment extends SmallProgram
{
use WxV3PaymentTait;
/**
* @param $orderNo
* @param int $total
* @param string|null $openId
* @param string $payer_client_ip
* @return array
* @throws Exception
*/
public function payment($orderNo, int $total, string $openId = NULL, string $payer_client_ip = '127.0.0.1'): array
{
$body = $this->getInitCore($orderNo, $total);
$body['payer'] = ['openid' => $openId];
$body['scene_info'] = ['payer_client_ip' => $payer_client_ip];
$sign = $this->signature('POST', '/v3/pay/transactions/jsapi', $json = json_encode($body, JSON_UNESCAPED_UNICODE));
$client = $this->createClient($sign, $json);
$client->post('/v3/pay/transactions/jsapi');
$client->close();
$json = json_decode($client->getBody(), TRUE);
if (!isset($json['prepay_id'])) {
throw new Exception('微信支付调用失败');
}
return $this->createResponse($json, $body);
}
}
+167
View File
@@ -0,0 +1,167 @@
<?php
namespace wchat\wx\V3;
use Exception;
use OpenSSLAsymmetricKey;
use Psr\Http\Message\RequestInterface;
use wchat\common\PayConfig;
use wchat\wx\SmallProgram;
use wchat\wx\V3\Notify\GoodsDetail;
use wchat\wx\V3\Notify\NotifyModel;
use wchat\wx\V3\Notify\PromotionDetail;
const KEY_TYPE_PUBLIC = 'public';
const KEY_TYPE_PRIVATE = 'private';
class WxV3PaymentNotify extends SmallProgram
{
use WxV3PaymentTait;
/**
* @param string $id
* @param string $create_time
* @param string $resource_type
* @param string $event_type
* @param string $summary
* @param array $resource
*/
public function __construct(
public string $id = "EV-2018022511223320873",
public string $create_time = "2015-05-20T13:29:35+08:00",
public string $resource_type = "encrypt-resource",
public string $event_type = "TRANSACTION.SUCCESS",
public string $summary = "支付成功",
public array $resource = []
)
{
}
/**
* @var NotifyModel
*/
public NotifyModel $notifyModel;
/**
* @param RequestInterface $request
* @return bool
* @throws Exception
*/
public function verify(RequestInterface $request): bool
{
$platformPublicKeyInstance = $this->rsaFrom($this->payConfig->pay->wx->mchKey, KEY_TYPE_PUBLIC);
$inWechatpaySignature = $request->getHeaderLine('Wechatpay-Signature'); // 请根据实际情况获取
$inWechatpayTimestamp = $request->getHeaderLine('Wechatpay-Timestamp'); // 请根据实际情况获取
$inWechatpayNonce = $request->getHeaderLine('Wechatpay-Nonce'); // 请根据实际情况获取
$inBody = $request->getBody()->getContents(); // 请根据实际情况获取,例如: file_get_contents('php://input');
$timeOffsetStatus = 300 >= abs(time() - (int)$inWechatpayTimestamp);
$verifiedStatus = $this->notifyVerify(
$this->lineFeed([$inWechatpayTimestamp, $inWechatpayNonce, $inBody]),
$inWechatpaySignature,
$platformPublicKeyInstance);
if (!$timeOffsetStatus || !$verifiedStatus) {
return false;
}
return $this->decode($this->resource['ciphertext'], $this->resource['nonce'], $this->resource['associated_data']);
}
/**
* @param ...$pieces
* @return string
*/
protected function lineFeed(...$pieces): string
{
return implode("\n", array_merge($pieces, ['']));
}
/**
* @return string|bool
*/
protected function body(): string|bool
{
return json_encode(['id' => $this->id, 'create_time' => $this->create_time, 'resource_type' => $this->resource_type, 'event_type' => $this->event_type, 'summary' => $this->summary, 'resource' => $this->resource]);
}
/**
* @param string $message
* @param string $signature
* @param $publicKey
* @return bool
*/
protected function notifyVerify(string $message, string $signature, $publicKey): bool
{
if (($result = openssl_verify($message, base64_decode($signature), $publicKey, OPENSSL_ALGO_SHA256)) === false) {
throw new \UnexpectedValueException('Verified the input $message failed, please checking your $publicKey whether or nor correct.');
}
return $result === 1;
}
/**
* @param $thing
* @param string $type
* @return OpenSSLAsymmetricKey
*/
protected function rsaFrom($thing, string $type = KEY_TYPE_PRIVATE): OpenSSLAsymmetricKey
{
$pkey = (($isPublic = $type === KEY_TYPE_PUBLIC) ? openssl_pkey_get_public(file_get_contents($thing)) : openssl_pkey_get_private(file_get_contents($thing)));
if (false === $pkey) {
throw new \UnexpectedValueException(sprintf('Cannot load %s from(%s), please take care about the $thing input.', $isPublic ? 'publicKey' : 'privateKey', gettype($thing)));
}
return $pkey;
}
/**
* @param $ciphertext
* @param $nonce
* @param $associated_data
* @return bool
*/
public function decode($ciphertext, $nonce, $associated_data): bool
{
$data = $this->decrypt($ciphertext, $this->payConfig->pay->wx->secret, $nonce, $associated_data);
$this->notifyModel = new NotifyModel();
$this->notifyModel->amount = $data['amount'];
$this->notifyModel->payer = $data['payer'];
$this->notifyModel->scene_info = $data['payer'];
$this->notifyModel->appid = $data['appid'];
$this->notifyModel->mchid = $data['mchid'];
$this->notifyModel->out_trade_no = $data['out_trade_no'];
$this->notifyModel->transaction_id = $data['transaction_id'];
$this->notifyModel->trade_type = $data['trade_type'];
$this->notifyModel->trade_state = $data['trade_state'];
$this->notifyModel->trade_state_desc = $data['trade_state_desc'];
$this->notifyModel->bank_type = $data['bank_type'];
$this->notifyModel->attach = $data['attach'];
$this->notifyModel->success_time = $data['success_time'];
$this->notifyModel->promotion_detail = [];
foreach ($data['promotion_detail'] as $datum) {
$detail = new PromotionDetail();
$detail->amount = $datum['amount'];
$detail->wechatpay_contribute = $datum['wechatpay_contribute'];
$detail->coupon_id = $datum['coupon_id'];
$detail->scope = $datum['scope'];
$detail->merchant_contribute = $datum['merchant_contribute'];
$detail->name = $datum['name'];
$detail->other_contribute = $datum['other_contribute'];
$detail->currency = $datum['currency'];
$detail->stock_id = $datum['stock_id'];
$detail->goods_detail = [];
foreach ($datum['goods_detail'] as $value) {
$detail->goods_detail[] = new GoodsDetail($value);
}
$this->notifyModel->promotion_detail[] = $detail;
}
return true;
}
}
+166
View File
@@ -0,0 +1,166 @@
<?php
namespace wchat\wx\V3;
use Exception;
use Kiri\Client;
use wchat\common\Help;
/**
* Bytes Length of the AES block
*/
const BLOCK_SIZE = 16;
/**
* Bytes length of the AES secret key.
*/
const KEY_LENGTH_BYTE = 32;
/**
* Bytes Length of the authentication tag in AEAD cipher mode
* @deprecated 1.0 - As of the OpenSSL described, the `auth_tag` length may be one of 16, 15, 14, 13, 12, 8 or 4.
* Keep it only compatible for the samples on the official documentation.
*/
const AUTH_TAG_LENGTH_BYTE = 16;
/**
* The `aes-256-gcm` algorithm string
*/
const ALGO_AES_256_GCM = 'aes-256-gcm';
/**
* The `aes-256-ecb` algorithm string
*/
const ALGO_AES_256_ECB = 'aes-256-ecb';
trait WxV3PaymentTait
{
/**
* @param $orderNo
* @param $total
* @return array
*/
public function getInitCore($orderNo, $total): array
{
$payConfig = $this->getPayConfig();
if ($payConfig->typeIsApp()) {
$body['appid'] = $payConfig->pay->wx->appId;
} else {
$body['appid'] = $payConfig->appId;
}
$body['mchid'] = $payConfig->pay->wx->mchId;
$body['description'] = $payConfig->getBody();
$body['out_trade_no'] = $orderNo;
$body['notify_url'] = $payConfig->getNotifyUrl();
$body['amount'] = ['total' => $total, 'currency' => $payConfig->getCurrency()];
return $body;
}
/**
* @param string $sign
* @param string $json
* @return Client
*/
public function createClient(string $sign, string $json): Client
{
$client = new Client('api.mch.weixin.qq.com', 443, TRUE);
$client->withAddedHeader('Authorization', $sign)
->withContentType('application/json')->withAddedHeader('User-Agent', 'application/json')
->withBody($json)->withAddedHeader("Accept", "*/*");
$proxyHost = $this->getConfig()->getProxyHost();
$proxyPort = $this->getConfig()->getProxyPort();
if (!empty($proxyHost) && $proxyPort > 0) {
$client->withProxyHost($proxyHost)->withProxyPort($proxyPort);
}
return $client;
}
/**
* @param string $http_method
* @param string $canonical_url
* @param string $body
* @return string
* @throws Exception
*/
public function signature(string $http_method, string $canonical_url, string $body = ''): string
{
$payConfig = $this->getPayConfig();
$rand = md5(random_bytes(32));
$time = time();
$message = sprintf("%s\n%s\n%d\n%s\n%s\n", $http_method, $canonical_url, $time, $rand, $body);
$sign = $this->openssl_signature($message);
return sprintf('%s mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"', $payConfig->pay->wx->schema,
$payConfig->pay->wx->mchId, $rand, $time, $payConfig->pay->wx->SerialNumber, $sign);
}
/**
* @param $body
* @return string
*/
public function openssl_signature($body): string
{
$payConfig = $this->getPayConfig();
$mch_private_key = openssl_get_privatekey($payConfig->pay->wx->mchKey);
openssl_sign($body, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
return base64_encode($raw_sign);
}
/**
* @param $json
* @param $body
* @return array
*/
private function createResponse($json, $body): array
{
$responseArray['appId'] = $body['appid'];
$responseArray['timeStamp'] = (string)time();
$responseArray['nonceStr'] = Help::random(32);
$responseArray['package'] = "prepay_id=" . $json['prepay_id'];
$responseBody = $responseArray['appId'] . PHP_EOL . $responseArray['timeStamp'] . PHP_EOL . $responseArray['nonceStr'] . PHP_EOL . $responseArray['package'] . PHP_EOL;
$responseArray['signType'] = 'RSA';
$responseArray['signBody'] = $responseBody;
$responseArray['paySign'] = $this->openssl_signature($responseBody);
$responseArray['prepay_id'] = $json['prepay_id'];
return $responseArray;
}
/**
* @param string $ciphertext
* @param string $v3Key
* @param string $iv
* @param string $aad
* @return array
*/
public function decrypt(string $ciphertext, string $v3Key, string $iv = '', string $aad = ''): array
{
$ciphertext = base64_decode($ciphertext);
$authTag = substr($ciphertext, $tailLength = 0 - BLOCK_SIZE);
$tagLength = strlen($authTag);
/* Manually checking the length of the tag, because the `openssl_decrypt` was mentioned there, it's the caller's responsibility. */
if ($tagLength > BLOCK_SIZE || ($tagLength < 12 && $tagLength !== 8 && $tagLength !== 4)) {
throw new \RuntimeException('The inputs `$ciphertext` incomplete, the bytes length must be one of 16, 15, 14, 13, 12, 8 or 4.');
}
$plaintext = openssl_decrypt(substr($ciphertext, 0, $tailLength), ALGO_AES_256_GCM, $v3Key, OPENSSL_RAW_DATA, $iv, $authTag, $aad);
if (false === $plaintext) {
throw new \UnexpectedValueException('Decrypting the input $ciphertext failed, please checking your $key and $iv whether or nor correct.');
}
return json_decode($plaintext, true);
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace wchat\wx\V3;
use Exception;
use JetBrains\PhpStorm\ArrayShape;
use Kiri\Client;
use wchat\wx\SmallProgram;
class WxV3Withdrawal extends SmallProgram
{
use WxV3PaymentTait;
/**
* @param $orderNo
* @param string $batch_name
* @param string $batch_remark
* @param TransferDetail[] $details
* @return array
* @throws Exception
*/
public function payment($orderNo, string $batch_name, string $batch_remark, array $details): array
{
$body = $this->create($orderNo, $batch_name, $batch_remark, $details);
$sign = $this->signature('POST', '/v3/pay/transactions/batches', $json = json_encode($body, JSON_UNESCAPED_UNICODE));
$client = $this->createClient($sign, $json);
$client->post('/v3/pay/transactions/batches');
$client->close();
$json = json_decode($client->getBody(), TRUE);
if (!isset($json['prepay_id'])) {
throw new Exception('微信支付调用失败');
}
return $this->createResponse($json, $body);
}
#[ArrayShape(['transfer_detail_list' => "array", 'total_amount' => "int", 'total_num' => "int", 'batch_remark' => "string", 'batch_name' => "string", 'out_batch_no' => ""])]
private function create($orderNo, string $batch_name, string $batch_remark, array $details): array
{
$total = 0;
$body = ['transfer_detail_list' => []];
$body['out_batch_no'] = $orderNo;
$body['batch_name'] = $batch_name;
$body['batch_remark'] = $batch_remark;
$body['total_num'] = count($details);
foreach ($details as $detail) {
$total += $detail->transfer_amount;
$body['transfer_detail_list'][] = $detail->toArray();
}
$body['total_amount'] = $total;
return $body;
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace wchat\wx;
use Kiri\Di\Container;
use ReflectionException;
use wchat\common\Config;
class WxFactory
{
/**
* @param $class
* @param Config $config
* @return object|null
* @throws ReflectionException
*/
public static function get($class, Config $config): ?object
{
$container = Container::instance();
$object = $container->get($class);
$object->setConfig($config);
return $object;
}
}