${title}
+ return `
${title}
`;
} else return klass === "details" ? `
` : `
@@ -35731,8 +35732,12 @@ async function createMarkdownRenderer(srcDir, options = {}, base = "/", logger =
{ target: "_blank", rel: "noreferrer", ...options.externalLinks },
base
).use(lineNumberPlugin, options.lineNumbers);
+ const orgi = md.renderer.rules.table_open;
md.renderer.rules.table_open = function(tokens, idx, options2, env, self) {
- return '
\n';
+ tokens[idx].attrGet("tabindex") ?? tokens[idx].attrJoin("tabindex", "0");
+ return orgi
+ ? orgi(tokens, idx, options2, env, self)
+ : self.renderToken(tokens, idx, options2);
};
if (options.gfmAlerts !== false) {
md.use(gitHubAlertsPlugin);
================================================
FILE: docs/README.md
================================================
# easywechat.com
## Contributing
This site is built with [VitePress](https://github.com/vuejs/vitepress) and depends on [@vue/theme](https://github.com/vuejs/vue-theme). Site content is written in Markdown format located in `src`. For simple edits, you can directly edit the file on GitHub and generate a Pull Request.
For local development, [pnpm](https://pnpm.io/) is preferred as package manager:
```bash
pnpm i
pnpm run dev
```
## Working on the content
- See VitePress docs on supported [Markdown Extensions](https://vitepress.vuejs.org/guide/markdown.html) and the ability to [use Vue syntax inside markdown](https://vitepress.vuejs.org/guide/using-vue.html).
## Working on the theme
If changes need to made for the theme, check out the [instructions for developing the theme alongside the docs](https://github.com/vuejs/vue-theme#developing-with-real-content).
================================================
FILE: docs/env.d.ts
================================================
///
///
declare module '@overtrue/easywechat-theme/config' {
import { UserConfig } from 'vitepress'
const config: () => Promise
export default config
}
declare module '@overtrue/easywechat-theme/highlight' {
const createHighlighter: () => Promise<(input: string) => string>
export default createHighlighter
}
================================================
FILE: docs/package.json
================================================
{
"private": true,
"scripts": {
"dev": "vitepress dev",
"build": "vitepress build",
"serve": "vitepress serve",
"purge-caches": "./purge-caches",
"preinstall": "npx only-allow pnpm"
},
"dependencies": {
"autoprefixer": "^10.4.21",
"clipboard": "^2.0.11",
"dynamics.js": "^1.1.5",
"gsap": "^3.13.0",
"tailwindcss": "^3.4.18"
},
"devDependencies": {
"@types/markdown-it": "^14.1.2",
"@types/node": "^22.18.12",
"postcss": "^8.5.6",
"postcss-import": "^16.1.1",
"tenyun": "^0.14.0",
"vitepress": "1.6.3"
},
"packageManager": "pnpm@9.12.3+sha512.cce0f9de9c5a7c95bef944169cc5dfe8741abfb145078c0d508b868056848a87c81e626246cb60967cbd7fd29a6c062ef73ff840d96b3c86c40ac92cf4a813ee"
}
================================================
FILE: docs/postcss.config.js
================================================
module.exports = {
plugins: [
require('postcss-import'),
require("tailwindcss")("./tailwind.config.js"),
require("autoprefixer"),
require('postcss-nested')
]
}
================================================
FILE: docs/purge-caches
================================================
#!/usr/bin/env node
const { default: TenYun } = require('tenyun');
const tc = new TenYun(process.env.COS_SECRET_ID ?? '', process.env.COS_SECRET_KEY ?? '');
tc.cdn.PurgePathCache({
Paths: [process.env.domain ?? ''],
FlushType: 'flush',
})
.then(({ data }) => {
console.log(data);
return tc.cdn.DescribePurgeTasks({
TaskId: data.TaskId,
PurgeType: 'path',
});
})
.then(({ data }) => console.log(data));
================================================
FILE: docs/src/3.x/access_token.md
================================================
# Access Token
SDK 中有一个 [Access Token](https://github.com/overtrue/wechat/blob/master/src/Core/AccessToken.php) 对象,它是一个全局使用的东西,请把它与 OAuth 中的 code 换取的 Access Token 区别开。
我们一个 SDK 应用在初始化以后,你可以在任何时机从应用中拿到该配置下的 Access Token 实例:
```php
use EasyWeChat\Foundation\Application;
$options = [
//...
];
$app = new Application($options);
// 获取 access token 实例
$accessToken = $app->access_token; // EasyWeChat\Core\AccessToken 实例
$token = $accessToken->getToken(); // token 字符串
$token = $accessToken->getToken(true); // 强制重新从微信服务器获取 token.
```
## 修改 `$app` 的 Access Token
```php
$app['access_token']->setToken($newAccessToken, $expires);
```
例如:
```php
$app['access_token']->setToken('ccfdec35bd7ba359f6101c2da321d675');
// 或者指定过期时间
$app['access_token']->setToken('ccfdec35bd7ba359f6101c2da321d675', 3600); // 单位:秒
```
## 设置 AccessToken 的缓存
你也可以自定义 token 的缓存方式,把一个实现了 `Doctrine\Common\Cache\Cache` 缓存接口的实例作为 AccessToken 构造函数的第三个参数传入即可:
本项目使用 [doctrine/cache](https://github.com/doctrine/cache) 来完成缓存工作,它支持几乎目前所有的缓存引擎。
以 Redis 为例:
```php
use Doctrine\Common\Cache\RedisCache; // RedisCache 实例了 `Doctrine\Common\Cache\Cache` 接口
$cache = new RedisCache();
// 创建 redis 实例
$redis = new Redis();
$redis->connect('redis_host', 6379);
$cache->setRedis($redis);
$app->access_token->setCache($cache);
```
================================================
FILE: docs/src/3.x/accounts.md
================================================
# 账号接入
如果你想使用本项目接入多个公众号,在本程序中,您可以为每个帐号都设置一个id,此id对应了该帐号的appid、token等信息。
如下表
| id | appId | secret | 其它... |
| --- | --- | --- | --- |
| 1 | `wx3cf0f39249eb0e60` | `f28f735d4f1c242f4687abb469072a29` | ... |
| 2 | `wx49eb0e63cf0f39s2` | `8f735d4687abb469f1c2422a29f4f207` | ... |
| N | `wx5cfeb0e60f392490` | `35f8f27d46f1c242f487a9072a29bb46` | ... |
在微信公众平台的设置中,您可以将您帐号中平台的 `url` 设置为 `您的网址/?id=xxx`,如:
```
http://www.example.com/wechat?id=1
```
而在程序入口处,根据 `id` 查找对应帐号的 `appid` 和 其它信息, 传入 'Overtrue\Wechat\Server',完成初始化。
================================================
FILE: docs/src/3.x/anaylsis.md
================================================
# 数据统计与分析
通过数据接口,开发者可以获取与公众平台官网统计模块类似但更灵活的数据,还可根据需要进行高级处理。
> 1. 接口侧的公众号数据的数据库中仅存储了 **2014年12月1日之后**的数据,将查询不到在此之前的日期,即使有查到,也是不可信的脏数据;
> 2. 请开发者在调用接口获取数据后,将数据保存在自身数据库中,即加快下次用户的访问速度,也降低了微信侧接口调用的不必要损耗。
> 3. 额外注意,获取图文群发每日数据接口的结果中,只有**中间页阅读人数+原文页阅读人数+分享转发人数+分享转发次数+收藏次数 >=3** 的结果才会得到统计,过小的阅读量的图文消息无法统计。
### 获取实例
```php
stats;
```
## API
$from example: `2014-02-13` 获取数据的起始日期
$to example: `2014-02-18` 获取数据的结束日期,`$to`允许设置的最大值为昨日
`$from` 和 `$to` 的差值需小于 “最大时间跨度”(比如最大时间跨度为 1 时,`$from` 和 `$to` 的差值只能为 0,才能小于 1 ),否则会报错
+ `array userSummary($from, $to)` 获取用户增减数据, 最大时间跨度:**7**;
+ `array userCumulate($from, $to)` 获取累计用户数据, 最大时间跨度:**7**;
+ `array articleSummary($from, $to)` 获取图文群发每日数据, 最大时间跨度:**1**;
+ `array articleTotal($from, $to)` 获取图文群发总数据, 最大时间跨度:**1**;
+ `array userReadSummary($from, $to)` 获取图文统计数据, 最大时间跨度:**3**;
+ `array userReadHourly($from, $to)` 获取图文统计分时数据, 最大时间跨度:**1**;
+ `array userShareSummary($from, $to)` 获取图文分享转发数据, 最大时间跨度:**7**;
+ `array userShareHourly($from, $to)` 获取图文分享转发分时数据, 最大时间跨度:**1**;
+ `array upstreamMessageSummary($from, $to)` 获取消息发送概况数据, 最大时间跨度:**7**;
+ `array upstreamMessageHourly($from, $to)` 获取消息发送分时数据, 最大时间跨度:**1**;
+ `array upstreamMessageWeekly($from, $to)` 获取消息发送周数据, 最大时间跨度:**30**;
+ `array upstreamMessageMonthly($from, $to)` 获取消息发送月数据, 最大时间跨度:**30**;
+ `array upstreamMessageDistSummary($from, $to)` 获取消息发送分布数据, 最大时间跨度:**15**;
+ `array upstreamMessageDistWeekly($from, $to)` 获取消息发送分布周数据, 最大时间跨度:**30**;
+ `array upstreamMessageDistMonthly($from, $to)` 获取消息发送分布月数据, 最大时间跨度:**30**;
+ `array interfaceSummary($from, $to)` 获取接口分析数据, 最大时间跨度:**30**;
+ `array interfaceSummaryHourly($from, $to)` 获取接口分析分时数据, 最大时间跨度:**1**;
example:
```php
$userSummary = $stats->userSummary('2014-12-07', '2014-12-08');
var_dump($userSummary);
//
//[
// {
// "ref_date": "2014-12-07",
// "user_source": 0,
// "new_user": 0,
// "cancel_user": 0
// }
// //后续还有ref_date在begin_date和end_date之间的数据
// ]
```
更多详细内容与协议说明,请查看微信官方文档:http://mp.weixin.qq.com/wiki/ **数据统计** 章节
================================================
FILE: docs/src/3.x/broadcast.md
================================================
# 群发
微信的群发消息接口有各种乱七八糟的注意事项及限制,具体请阅读微信官方文档:http://mp.weixin.qq.com/wiki/15/5380a4e6f02f2ffdc7981a8ed7a40753.html
## 获取实例
```php
broadcast;
```
## API
> 注意:
下面提到的 `$messageType` 、`$message` 可以是:
- `$messageType = Broadcast::MSG_TYPE_NEWS;` 图文消息类型,所对应的 `$message` 为 media_id
- `$messageType = Broadcast::MSG_TYPE_TEXT;` 文本消息类型,所对应的 `$message` 为一个文本字符串
- `$messageType = Broadcast::MSG_TYPE_VOICE;` 语音消息类型,所对应的 `$message` 为 media_id
- `$messageType = Broadcast::MSG_TYPE_IMAGE;` 图片消息类型,所对应的 `$message` 为 media_id
- `$messageType = Broadcast::MSG_TYPE_CARD;` 卡券消息类型,所对应的 `$message` 为 card_id
- `$messageType = Broadcast::MSG_TYPE_VIDEO;` 视频消息为两种情况:
- 视频消息类型,群发视频消息给**组或预览群发视频消息**给用户时所对应的 `$message` 为`media_id`
- 群发视频消息**给指定用户**时所对应的 `$message` 为一个数组 `['MEDIA_ID', 'TITLE', 'DESCRIPTION']`
### 群发消息给所有粉丝
```php
$broadcast->send($messageType, $message);
// 别名方式
$broadcast->sendText("大家好!欢迎使用 EasyWeChat。");
$broadcast->sendNews($mediaId);
$broadcast->sendVoice($mediaId);
$broadcast->sendImage($mediaId);
//视频:
// - 群发给组用户,或者预览群发视频时 $message 为 media_id
// - 群发给指定用户时为数组:[$media_Id, $title, $description]
$broadcast->sendVideo($message);
$broadcast->sendCard($cardId);
```
### 群发消息给指定组
```php
$broadcast->send($messageType, $message, $groupId);
// 别名方式
$broadcast->sendText($text, $groupId);
$broadcast->sendNews($mediaId, $groupId);
$broadcast->sendVoice($mediaId, $groupId);
$broadcast->sendImage($mediaId, $groupId);
$broadcast->sendVideo($message, $groupId);
$broadcast->sendCard($cardId, $groupId);
```
### 群发消息给指定用户
至少两个用户的openid,必须是数组。
```php
$broadcast->send($messageType, $message, [$openId1, $openId2]);
// 别名方式
$broadcast->sendText($text, [$openId1, $openId2]);
$broadcast->sendNews($mediaId, [$openId1, $openId2]);
$broadcast->sendVoice($mediaId, [$openId1, $openId2]);
$broadcast->sendImage($mediaId, [$openId1, $openId2]);
$broadcast->sendVideo($message, [$openId1, $openId2]);
$broadcast->sendCard($cardId, [$openId1, $openId2]);
```
### 发送预览群发消息给指定的 `openId` 用户
```php
$broadcast->preview($messageType, $message, $openId);
// 别名方式
$broadcast->previewText($text, $openId);
$broadcast->previewNews($mediaId, $openId);
$broadcast->previewVoice($mediaId, $openId);
$broadcast->previewImage($mediaId, $openId);
$broadcast->previewVideo($message, $openId);
$broadcast->previewCard($cardId, $openId);
```
### 发送预览群发消息给指定的微信号用户
```php
$broadcast->previewByName($messageType, $message, $wxname);
// 别名方式
$broadcast->previewTextByName($text, $wxname);
$broadcast->previewNewsByName($mediaId, $wxname);
$broadcast->previewVoiceByName($mediaId, $wxname);
$broadcast->previewImageByName($mediaId, $wxname);
$broadcast->previewVideoByName($message, $wxname);
$broadcast->previewCardByName($cardId, $wxname);
```
### 删除群发消息
```php
$broadcast->delete($msgId);
```
### 查询群发消息发送状态
```php
$broadcast->status($msgId);
```
有关群发信息的更多细节请参考微信官方文档:http://mp.weixin.qq.com/wiki/
================================================
FILE: docs/src/3.x/cache.md
================================================
# 缓存
本项目使用 [doctrine/cache](https://github.com/doctrine/cache) 来完成缓存工作,它支持基本目前所有的缓存引擎。
在我们的 SDK 中的所有缓存默认使用文件缓存,缓存路径取决于 PHP 的临时目录,如果你需要自定义缓存,那么你需要做如下的事情:
你可以参考[doctrine/cache官方文档](http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/caching.html)来替换掉应用中默认的缓存配置:
> 以 redis 为例
> 请先安装 redis 拓展:https://github.com/phpredis/phpredis
```php
use Doctrine\Common\Cache\RedisCache;
$cacheDriver = new RedisCache();
// 创建 redis 实例
$redis = new Redis();
$redis->connect('redis_host', 6379);
$cacheDriver->setRedis($redis);
$options = [
'debug' => false,
'app_id' => $wechatInfo['app_id'],
'secret' => $wechatInfo['app_secret'],
'token' => $wechatInfo['token'],
'aes_key' => $wechatInfo['aes_key'], // 可选
'cache' => $cacheDriver,
];
$wechatApp = new Application($options);
```
### Laravel 中使用
在 Laravel 中框架使用 [predis/predis](https://github.com/nrk/predis),那么我们就得使用 `Doctrine\Common\Cache\PredisCache`:
```php
use Doctrine\Common\Cache\PredisCache;
$predis = app('redis')->connection();// connection($name), $name 默认为 `default`
$cacheDriver = new PredisCache($predis);
$app->cache = $cacheDriver;
```
> 上面提到的 `app('redis')->connection($name)`, 这里的 `$name` 是 laravel 项目中配置文件 `database.php` 中 `redis` 配置名 `default`:https://github.com/laravel/laravel/blob/master/config/database.php#L118
> 如果你使用的其它连接,对应传名称就好了。
> 如果你在使用Laravel 5.4,应将`$predis = app('redis')->connection();`修改为:`$predis = app('redis')->connection()->client();`
## 使用自定义的缓存方式
如果你发现 doctrine 提供的几十种缓存方式都满足不了你的需求的话,那么你可以自己建立一个类来完成缓存操作,前提这个类得实现接口:[Doctrine\Common\Cache\Cache](https://github.com/doctrine/cache/blob/master/lib/Doctrine/Common/Cache/Cache.php)
该接口有以下方法需要实现:
```php
public function fetch($id); // 读取缓存
public function contains($id); // 检查是否存在缓存
public function save($id, $data, $lifeTime = 0); // 设置缓存
public function delete($id); // 删除缓存
public function getStats(); // 获取状态
```
下面为一个示例:
```php
$myCacheDriver,
];
$wechatApp = new Application($options);
```
OK,这样就完成了自定义缓存的操作。
================================================
FILE: docs/src/3.x/card.md
================================================
# 卡券
-
> Version `>=3.1.2`
## 获取实例
```php
card;
```
## API列表
### 获取卡券颜色
```php
$card->getColors();
```
example:
```php
$result = $card->getColors();
```
### 创建卡券
创建卡券接口是微信卡券的基础接口,用于创建一类新的卡券,获取card_id,创建成功并通过审核后,商家可以通过文档提供的其他接口将卡券下发给用户,每次成功领取,库存数量相应扣除。
```php
$card->create($cardType, $baseInfo, $especial);
```
- `cardType` string - 是要添加卡券的类型
- `baseInfo` array - 为卡券的基本数据
- `especial` array - 是扩展字段
example:
```php
'http://mmbiz.qpic.cn/mmbiz/2aJY6aCPatSeibYAyy7yct9zJXL9WsNVL4JdkTbBr184gNWS6nibcA75Hia9CqxicsqjYiaw2xuxYZiaibkmORS2oovdg/0',
'brand_name' => '测试商户造梦空间',
'code_type' => 'CODE_TYPE_QRCODE',
'title' => '测试',
'sub_title' => '测试副标题',
'color' => 'Color010',
'notice' => '测试使用时请出示此券',
'service_phone' => '15311931577',
'description' => "测试不可与其他优惠同享\n如需团购券发票,请在消费时向商户提出\n店内均可使用,仅限堂食",
'date_info' => [
'type' => 'DATE_TYPE_FIX_TERM',
'fixed_term' => 90, //表示自领取后多少天内有效,不支持填写0
'fixed_begin_term' => 0, //表示自领取后多少天开始生效,领取后当天生效填写0。
],
'sku' => [
'quantity' => '0', //自定义code时设置库存为0
],
'location_id_list' => ['461907340'], //获取门店位置poi_id,具备线下门店的商户为必填
'get_limit' => 1,
'use_custom_code' => true, //自定义code时必须为true
'get_custom_code_mode' => 'GET_CUSTOM_CODE_MODE_DEPOSIT', //自定义code时设置
'bind_openid' => false,
'can_share' => true,
'can_give_friend' => false,
'center_title' => '顶部居中按钮',
'center_sub_title' => '按钮下方的wording',
'center_url' => 'http://www.qq.com',
'custom_url_name' => '立即使用',
'custom_url' => 'http://www.qq.com',
'custom_url_sub_title' => '6个汉字tips',
'promotion_url_name' => '更多优惠',
'promotion_url' => 'http://www.qq.com',
'source' => '造梦空间',
];
$especial = [
'deal_detail' => 'deal_detail',
];
$result = $card->create($cardType, $baseInfo, $especial);
```
### 创建二维码
开发者可调用该接口生成一张卡券二维码供用户扫码后添加卡券到卡包。
自定义Code码的卡券调用接口时,POST数据中需指定code,非自定义code不需指定,指定openid同理。指定后的二维码只能被用户扫描领取一次。
```php
$card->QRCode($cards);
```
- `cards` array - 卡券相关信息
example:
```php
//领取单张卡券
$cards = [
'action_name' => 'QR_CARD',
'expire_seconds' => 1800,
'action_info' => [
'card' => [
'card_id' => 'pdkJ9uFS2WWCFfbbEfsAzrzizVyY',
'is_unique_code' => false,
'outer_id' => 1,
],
],
];
$result = $card->QRCode($cards);
```
```php
//领取多张卡券
$cards = [
'action_name' => 'QR_MULTIPLE_CARD',
'action_info' => [
'multiple_card' => [
'card_list' => [
['card_id' => 'pdkJ9uFS2WWCFfbbEfsAzrzizVyY'],
],
],
],
];
$result = $card->QRCode($cardList);
```
请求成功返回值示例:
```php
array(4) {
["ticket"]=>
string(96) "gQHa7joAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xLzdrUFlQMHJsV3Zvanc5a2NzV1N5AAIEJUVyVwMEAKd2AA=="
["expire_seconds"]=>
int(7776000)
["url"]=>
string(43) "http://weixin.qq.com/q/7kPYP0rlWvojw9kcsWSy"
["show_qrcode_url"]=>
string(151) "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQHa7joAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xLzdrUFlQMHJsV3Zvanc5a2NzV1N5AAIEJUVyVwMEAKd2AA%3D%3D"
}
```
成功返回值列表说明:
| 参数名 | 描述 |
| :-------------: | :--------------------------------------- |
| ticket | 获取的二维码ticket,凭借此ticket调用[通过ticket换取二维码接口](http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1443433542&token=&lang=zh_CN)可以在有效时间内换取二维码。 |
| expire_seconds | 二维码的有效时间 |
| url | 二维码图片解析后的地址,开发者可根据该地址自行生成需要的二维码图片 |
| show_qrcode_url | 二维码显示地址,点击后跳转二维码页面 |
### ticket 换取二维码图片
获取二维码 ticket 后,开发者可用 ticket 换取二维码图片。
```php
$card->showQRCode($ticket);
```
- `ticket` string - 获取的二维码 ticket,凭借此 ticket 可以在有效时间内换取二维码。
example:
```php
$ticket = 'gQFF8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL01VTzN0T0hsS1BwUlBBYUszbVN5AAIEughxVwMEAKd2AA==';
$result = $card->showQRCode($ticket);
```
### ticket 换取二维码链接
```php
$card->getQRCodeUrl($ticket); //获取的二维码ticket
```
example:
```php
$ticket = 'gQFF8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL01VTzN0T0hsS1BwUlBBYUszbVN5AAIEughxVwMEAKd2AA==';
$card->getQRCodeUrl($ticket);
```
### JSAPI 卡券批量下发到用户
微信卡券:JSAPI 卡券
```php
$cards = [
['card_id' => 'pdkJ9uLRSbnB3UFEjZAgUxAJrjeY', 'outer_id' => 2],
['card_id' => 'pdkJ9uJ37aU-tyRj4_grs8S45k1c', 'outer_id' => 3],
];
$json = $card->jsConfigForAssign($cards); // 返回 json 格式
```
返回 json,在模板里的用法:
```html
wx.addCard({
cardList: = $json ?>, // 需要打开的卡券列表
success: function (res) {
var cardList = res.cardList; // 添加的卡券列表信息
}
});
```
### 创建货架接口
开发者需调用该接口创建货架链接,用于卡券投放。创建货架时需填写投放路径的场景字段。
```php
$card->createLandingPage($banner, $pageTitle, $canShare, $scene, $cards);
```
- `banner` string -页面的 banner 图;
- `pageTitle` string - 页面的 title
- `canShare` bool - 页面是不是可以分享,true 或 false
- `scene` string - 投放页面的场景值,具体值请参考下面的 example
- `cards` array - 卡券列表,每个元素有两个字段
example:
```php
$banner = 'http://mmbiz.qpic.cn/mmbiz/iaL1LJM1mF9aRKPZJkmG8xXhiaHqkKSVMMWeN3hLut7X7hicFN';
$pageTitle = '惠城优惠大派送';
$canShare = true;
//SCENE_NEAR_BY 附近
//SCENE_MENU 自定义菜单
//SCENE_QRCODE 二维码
//SCENE_ARTICLE 公众号文章
//SCENE_H5 h5页面
//SCENE_IVR 自动回复
//SCENE_CARD_CUSTOM_CELL 卡券自定义cell
$scene = 'SCENE_NEAR_BY';
$cardList = [
['card_id' => 'pdkJ9uLRSbnB3UFEjZAgUxAJrjeY', 'thumb_url' => 'http://test.digilinx.cn/wxApi/Uploads/test.png'],
['card_id' => 'pdkJ9uJ37aU-tyRj4_grs8S45k1c', 'thumb_url' => 'http://test.digilinx.cn/wxApi/Uploads/aa.jpg'],
];
$result = $card->createLandingPage($banner, $pageTitle, $canShare, $scene, $cardList);
```
### 导入code接口
在自定义code卡券成功创建并且通过审核后,必须将自定义code按照与发券方的约定数量调用导入code接口导入微信后台。
```php
$card->deposit($card_id, $code);
```
- `cardId` string - 要导入code的卡券ID
- `code` string - 要导入微信卡券后台的自定义 code,最多100个
example:
```php
$cardId = 'pdkJ9uLCEF_HSKO7JdQOUcZ-PUzo';
$code = ['11111', '22222', '33333'];
$result = $card->deposit($cardId, $code);
```
### 查询导入code数目
```php
$card->getDepositedCount($cardId); //要导入code的卡券ID
```
example:
```php
$cardId = 'pdkJ9uLCEF_HSKO7JdQOUcZ-PUzo';
$result = $card->getDepositedCount($cardId);
```
### 核查code接口
为了避免出现导入差错,强烈建议开发者在查询完code数目的时候核查code接口校验code导入微信后台的情况。
```php
$card->checkCode($cardId, $code);
```
example:
```php
$cardId = 'pdkJ9uLCEF_HSKO7JdQOUcZ-PUzo';
$code = ['807732265476', '22222', '33333'];
$result = $card->checkCode($cardId, $code);
```
### 图文消息群发卡券
特别注意:目前该接口仅支持填入非自定义code的卡券,自定义code的卡券需先进行code导入后调用。
```php
$card->getHtml($cardId);
```
example:
```php
$cardId = 'pdkJ9uLCEF_HSKO7JdQOUcZ-PUzo';
$result = $card->getHtml($cardId);
```
### 设置测试白名单
同时支持“openid”、“username”两种字段设置白名单,总数上限为10个。
```php
$card->setTestWhitelist($openids); // 使用 openid
$card->setTestWhitelistByUsername($usernames); // 使用 username
```
- `openids` array - 测试的openid列表
- `usernames` array - 测试的微信号列表
example:
```php
// by openid
$openids = [$openId, $openId2, $openid3...];
$result = $card->setTestWhitelist($openids);
// by username
$usernames = ['tianye0327', 'iovertrue'];
$result = $card->setTestWhitelistByUsername($usernames);
```
### 查询Code接口
```php
$card->getCode($code, $checkConsume, $cardId);
```
- checkConsume 是否校验code核销状态,true和false
example:
```php
$code = '736052543512';
$checkConsume = true;
$cardId = 'pdkJ9uDgnm0pKfrTb1yV0dFMO_Gk';
$result = $card->getCode($code, $checkConsume, $cardId);
```
### 核销Code接口
```php
$card->consume($code);
// 或者指定 cardId
$card->consume($code, $cardId);
```
example:
```php
$cardId = 'pdkJ9uDmhkLj6l5bm3cq9iteQBck';
$code = '789248558333';
$result = $card->consume($code);
//或
$result = $card->consume($code, $cardId);
```
### Code解码接口
```php
$card->decryptCode($encryptedCode);
```
example:
```php
$encryptedCode = 'XXIzTtMqCxwOaawoE91+VJdsFmv7b8g0VZIZkqf4GWA60Fzpc8ksZ/5ZZ0DVkXdE';
$result = $card->decryptCode($encryptedCode);
```
### 获取用户已领取卡券接口
用于获取用户卡包里的,属于该appid下所有**可用卡券,包括正常状态和未生效状态**。
```php
$card->getUserCards($openid, $cardId);
```
example:
```php
$openid = 'odkJ9uDUz26RY-7DN1mxkznfo9xU';
$cardId = ''; //卡券ID。不填写时默认查询当前appid下的卡券。
$result = $card->getUserCards($openid, $cardId);
```
### 查看卡券详情
开发者可以调用该接口查询某个card_id的创建信息、审核状态以及库存数量。
```php
$card->getCard($cardId);
```
example:
```php
$cardId = 'pdkJ9uLRSbnB3UFEjZAgUxAJrjeY';
$result = $card->getCard($cardId);
```
### 批量查询卡列表
```php
$card->lists($offset, $count, $statusList);
```
- `offset` int - 查询卡列表的起始偏移量,从0开始
- `count` int - 需要查询的卡片的数量
- `statusList` - 支持开发者拉出指定状态的卡券列表,详见example
example:
```php
$offset = 0;
$count = 10;
//CARD_STATUS_NOT_VERIFY,待审核;
//CARD_STATUS_VERIFY_FAIL,审核失败;
//CARD_STATUS_VERIFY_OK,通过审核;
//CARD_STATUS_USER_DELETE,卡券被商户删除;
//CARD_STATUS_DISPATCH,在公众平台投放过的卡券;
$statusList = 'CARD_STATUS_VERIFY_OK';
$result = $card->lists($offset, $count, $statusList);
```
### 更改卡券信息接口
支持更新所有卡券类型的部分通用字段及特殊卡券中特定字段的信息。
```php
$card->update($cardId, $type, $baseInfo);
```
- `type` string - 卡券类型
example:
```php
$cardId = 'pdkJ9uCzKWebwgNjxosee0ZuO3Os';
$type = 'groupon';
$baseInfo = [
'logo_url' => 'http://mmbiz.qpic.cn/mmbiz/2aJY6aCPatSeibYAyy7yct9zJXL9WsNVL4JdkTbBr184gNWS6nibcA75Hia9CqxicsqjYiaw2xuxYZiaibkmORS2oovdg/0',
'center_title' => '顶部居中按钮',
'center_sub_title' => '按钮下方的wording',
'center_url' => 'http://www.baidu.com',
'custom_url_name' => '立即使用',
'custom_url' => 'http://www.qq.com',
'custom_url_sub_title' => '6个汉字tips',
'promotion_url_name' => '更多优惠',
'promotion_url' => 'http://www.qq.com',
];
$result = $card->update($cardId, $type, $baseInfo);
```
### 设置微信买单接口
```php
$card->setPayCell($cardId, $isOpen);
```
- `isOpen` string - 是否开启买单功能,填 true/false,不填默认 true
example:
```php
$cardId = 'pdkJ9uH7u11R-Tu1kilbaW_zDFow';
$isOpen = true;
$result = $card->setPayCell($cardId, $isOpen);
```
### 修改库存接口
```php
$card->increaseStock($cardId, $amount); // 增加库存
$card->reductStock($cardId, $amount); // 减少库存
```
- `cardId` string - 卡券 ID
- `amount` int - 修改多少库存
example:
```php
$cardId = 'pdkJ9uLRSbnB3UFEjZAgUxAJrjeY';
$result = $card->increaseStock($cardId, 100);
```
### 更改Code接口
```php
$card->updateCode($code, $newCode, $cardId);
```
- `newCode` string - 变更后的有效Code码
example:
```php
$code = '148246271394';
$newCode = '659266965266';
$cardId = '';
$result = $card->updateCode($code, $newCode, $cardId);
```
### 删除卡券接口
```php
$card->delete($cardId);
```
example:
```php
$cardId = 'pdkJ9uItT7iUpBp4GjZp8Cae0Vig';
$result = $card->delete($cardId);
```
### 设置卡券失效
```php
$card->disable($code, $cardId);
```
example:
```php
$code = '736052543512';
$cardId = '';
$result = $card->disable($code, $cardId);
```
### 会员卡接口激活
```php
$result = $card->activate($info);
```
- `info` - 需要激活的会员卡信息
example:
```php
$activate = [
'membership_number' => '357898858', //会员卡编号,由开发者填入,作为序列号显示在用户的卡包里。可与Code码保持等值。
'code' => '916679873278', //创建会员卡时获取的初始code。
'activate_begin_time' => '1397577600', //激活后的有效起始时间。若不填写默认以创建时的 data_info 为准。Unix时间戳格式
'activate_end_time' => '1422724261', //激活后的有效截至时间。若不填写默认以创建时的 data_info 为准。Unix时间戳格式。
'init_bonus' => '持白金会员卡到店消费,可享8折优惠。', //初始积分,不填为0。
'init_balance' => '持白金会员卡到店消费,可享8折优惠。', //初始余额,不填为0。
'init_custom_field_value1' => '白银', //创建时字段custom_field1定义类型的初始值,限制为4个汉字,12字节。
'init_custom_field_value2' => '9折', //创建时字段custom_field2定义类型的初始值,限制为4个汉字,12字节。
'init_custom_field_value3' => '200', //创建时字段custom_field3定义类型的初始值,限制为4个汉字,12字节。
];
$result = $card->activate($activate);
```
### 设置开卡字段接口
```php
$card->activateUserForm($cardId, $requiredForm, $optionalForm);
```
- `requiredForm` array - 会员卡激活时的必填选项
- `optionalForm` array - 会员卡激活时的选填项
example:
```php
$cardId = 'pdkJ9uJYAyfLXsUCwI2LdH2Pn1AU';
$requiredForm = [
'required_form' => [
'common_field_id_list' => [
'USER_FORM_INFO_FLAG_MOBILE',
'USER_FORM_INFO_FLAG_LOCATION',
'USER_FORM_INFO_FLAG_BIRTHDAY',
],
'custom_field_list' => [
'喜欢的食物',
],
],
];
$optionalForm = [
'optional_form' => [
'common_field_id_list' => [
'USER_FORM_INFO_FLAG_EMAIL',
],
'custom_field_list' => [
'喜欢的食物',
],
],
];
$result = $card->activateUserForm($cardId, $requiredForm, $optionalForm);
```
### 拉取会员信息接口
```php
$card->getMemberCardUser($cardId, $code);
```
example:
```php
$cardId = 'pbLatjtZ7v1BG_ZnTjbW85GYc_E8';
$code = '916679873278';
$result = $card->getMemberCardUser($cardId, $code);
```
### 更新会员信息
```php
$card->updateMemberCardUser($updateUser);
```
- `updateUser` array - 可以更新的会员信息
example:
```php
$updateUser = [
'code' => '916679873278', //卡券Code码。
'card_id' => 'pbLatjtZ7v1BG_ZnTjbW85GYc_E8', //卡券ID。
'record_bonus' => '消费30元,获得3积分', //商家自定义积分消耗记录,不超过14个汉字。
'bonus' => '100', //需要设置的积分全量值,传入的数值会直接显示,如果同时传入add_bonus和bonus,则前者无效。
'balance' => '持白金会员卡到店消费,可享8折优惠。', //需要设置的余额全量值,传入的数值会直接显示,如果同时传入add_balance和balance,则前者无效。
'record_balance' => '持白金会员卡到店消费,可享8折优惠。', //商家自定义金额消耗记录,不超过14个汉字。
'custom_field_value1' => '100', //创建时字段custom_field1定义类型的最新数值,限制为4个汉字,12字节。
'custom_field_value2' => '200', //创建时字段custom_field2定义类型的最新数值,限制为4个汉字,12字节。
'custom_field_value3' => '300', //创建时字段custom_field3定义类型的最新数值,限制为4个汉字,12字节。
];
$result = $card->updateMemberCardUser($updateUser);
```
### 添加子商户
```php
$card->craeteSubMerchant($brandName, $logoUrl, $protocol, $endTime, $primaryCategoryId, $secondaryCategoryId, $agreementMediaId, $operatorMediaId, $appId);
```
- `brand_name` string - 子商户名称(12个汉字内),该名称将在制券时填入并显示在卡券页面上
- `logo_url` string - 子商户 logo,可通过上传 logo 接口获取。该 logo 将在制券时填入并显示在卡券页面上
- `protocol` string - 授权函ID,即通过上传临时素材接口上传授权函后获得的 meida_id
- `primary_category_id` int - 一级类目id,可以通过本文档中接口查询
- `secondary_category_id` int - 二级类目id,可以通过本文档中接口查询
- `agreement_media_id` string - 营业执照或个体工商户营业执照彩照或扫描件
- `operator_media_id` string - 营业执照内登记的经营者身份证彩照或扫描件
- `app_id` string - 子商户的公众号 app_id,配置后子商户卡券券面上的 app_id 为该 app_id, app_id 须经过认证
example:
```php
$info = [
'brand_name' => 'overtrue',
'logo_url' => 'http://mmbiz.qpic.cn/mmbiz/iaL1LJM1mF9aRKPZJkmG8xXhiaHqkKSVMMWeN3hLut7X7hicFNjakmxibMLGWpXrEXB33367o7zHN0CwngnQY7zb7g/0',
'protocol' => 'qIqwTfzAdJ_1-VJFT0fIV53DSY4sZY2WyhkzZzbV498Qgdp-K5HJtZihbHLS0Ys0',
'end_time' => '1438990559',
'primary_category_id' => 1,
'secondary_category_id' => 101,
'agreement_media_id' => '',
'operator_media_id' => '',
'app_id' => '',
];
$result = $card->createSubMerchant($info);
```
### 更新子商户
```php
$card->updateSubMerchant($merchantId, $info);
```
- `$merchantId` int - 子商户 ID
- `$info` array - 参数与创建子商户参数一样
example:
```php
$info = [
//...
];
$result = $card->updateSubMerchant('12', $info);
```
### 卡券开放类目查询接口
```php
$card->getCategories();
```
example:
```php
$result = $card->getCategories();
```
关于卡券接口的使用请参阅官方文档:http://mp.weixin.qq.com/wiki/
================================================
FILE: docs/src/3.x/configuration.md
================================================
# 配置
在前面我们已经讲过,初始化 SDK 的时候方法就是创建一个 `EasyWeChat\Foundation\Application` 实例:
```php
use EasyWeChat\Foundation\Application;
$options = [
// ...
];
$app = new Application($options);
/**
* 如果想要在Application实例化完成之后, 修改某一个options的值,
* 比如服务商+子商户支付回调场景, 所有子商户订单支付信息都是通过同一个服务商的$option 配置进来的,
* 当oauth在微信端验证完成之后, 可以通过动态设置merchant_id来区分具体是哪个子商户
*/
$app['config']->set('oauth.callback','wechat/oauthcallback/'. $sub_merchant_id->id);
```
那么配置的具体选项有哪些,下面是一个完整的列表:
```php
true,
/**
* 账号基本信息,请从微信公众平台/开放平台获取
*/
'app_id' => 'your-app-id', // AppID
'secret' => 'your-app-secret', // AppSecret
'token' => 'your-token', // Token
'aes_key' => '', // EncodingAESKey,安全模式与兼容模式下请一定要填写!!!
/**
* 日志配置
*
* level: 日志级别, 可选为:
* debug/info/notice/warning/error/critical/alert/emergency
* permission:日志文件权限(可选),默认为null(若为null值,monolog会取0644)
* file:日志文件位置(绝对路径!!!),要求可写权限
*/
'log' => [
'level' => 'debug',
'permission' => 0777,
'file' => '/tmp/easywechat.log',
],
/**
* OAuth 配置
*
* scopes:公众平台(snsapi_userinfo / snsapi_base),开放平台:snsapi_login
* callback:OAuth授权完成后的回调页地址
*/
'oauth' => [
'scopes' => ['snsapi_userinfo'],
'callback' => '/examples/oauth_callback.php',
],
/**
* 微信支付
*/
'payment' => [
'merchant_id' => 'your-mch-id',
'key' => 'key-for-signature',
'cert_path' => 'path/to/your/cert.pem', // XXX: 绝对路径!!!!
'key_path' => 'path/to/your/key', // XXX: 绝对路径!!!!
// 'device_info' => '013467007045764',
// 'sub_app_id' => '',
// 'sub_merchant_id' => '',
// ...
],
/**
* Guzzle 全局设置
*
* 更多请参考: http://docs.guzzlephp.org/en/latest/request-options.html
*/
'guzzle' => [
'timeout' => 3.0, // 超时时间(秒)
//'verify' => false, // 关掉 SSL 认证(强烈不建议!!!)
],
];
```
> :heart: 安全模式下请一定要填写 `aes_key`
## 日志文件
配置文件里的`/tmp/...`是绝对路径
如果在 windows 下,去把它改成`C:\foo\bar`的形式,
如果是 Linux ,你已经懂了……
如果需要按日独立存储,可以配置成`'file' => storage_path('/tmp/easywechat/easywechat_'.date('Ymd').'.log'),`
其它同理……
================================================
FILE: docs/src/3.x/contributing.md
================================================
# 贡献代码
## 开发
我们欢迎广大开发者贡献大家的智慧,让我们共同让它变得更完美.
### 开始之前
请严格遵循以下代码标准:
- [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md).
- 使用 4 个空格作为缩进。
### 流程
1. Fork [overtrue/wechat](https://github.com/overtrue/wechat) 到本地.
2. 创建新的分支:
```bash
git checkout -b new_feature
```
3. 编写代码。
4. Push 到你的分支:
```bash
git push origin new_feature
```
5. 创建 Pull Request 并描述你完成的功能或者做出的修改。
> 注意:注释请使用英文
## 更新文档
我们的文档也是开源的,源代码在 [w7corp/EasyWeChat/docs](https://github.com/w7corp/easywechat/tree/master/docs)。
### 流程
1. Fork [w7corp/EasyWeChat](https://github.com/w7corp/EasyWeChat)
2. Clone 到你的电脑:
```bash
git clone https://github.com/[你的账号]/EasyWeChat
cd docs
```
3. 创建新的分支,编辑文档
4. Push 到你的分支。
5. 创建 Pull Request 并描述你完成的功能或者做出的修改。
## 报告 Bug
当你在使用过程中遇到问题,请查阅 [疑难解答](troubleshooting.html) 或者在这里提问 [GitHub](https://github.com/overtrue/wechat/issues). 如果还是不能解决你的问题,请到 GitHub 联系我们。
[overtrue/wechat]: https://github.com/overtrue/wechat
================================================
FILE: docs/src/3.x/events.md
================================================
# 事件
> 注意:3.0 起,所有服务端的入口(**消息与事件**)都已经合并为一个方法来处理:`setMessageHandler()`
### 在服务端接收用户端产生的事件
```php
server;
$server->setMessageHandler(function($message){
// 注意,这里的 $message 不仅仅是用户发来的消息,也可能是事件
// 当 $message->MsgType 为 event 时为事件
if ($message->MsgType == 'event') {
# code...
switch ($message->Event) {
case 'subscribe':
# code...
break;
default:
# code...
break;
}
}
});
$response = $server->serve();
$response->send(); // Laravel 里请使用:return $response;
```
> 注意:`$response` 是一个对象,不要直接 echo.
更多请参考:[服务端](server.html)
关于事件类型请参考微信官方文档:http://mp.weixin.qq.com/wiki/
================================================
FILE: docs/src/3.x/index.md
================================================
> 👋🏼 您当前浏览的文档为 3.x,其它版本的文档请参考:[6.x](/6.x/)、[5.x](/5.x/)、[4.x](/4.x/)
# EasyWeChat
EasyWeChat 是一个开源的 [微信](http://www.wechat.com) 非官方 SDK。安装非常简单,因为它是一个标准的 [Composer](https://getcomposer.org/) 包,这意味着任何满足下列安装条件的 PHP 项目支持 Composer 都可以使用它。
## 环境要求
- PHP >= 5.5.9
- [PHP cURL 扩展](http://php.net/manual/en/book.curl.php)
- [PHP OpenSSL 扩展](http://php.net/manual/en/book.openssl.php)
- [PHP fileinfo 拓展](http://php.net/manual/en/book.fileinfo.php)
# 参与贡献
1. fork 当前库到你的名下
2. 切换到你想要修改的分支,`zh-cn` 或者 `en`
3. 在你的本地修改完成审阅过后提交到你的仓库的对应分支
4. 提交 PR 并描述你的修改,等待合并
# License
MIT
================================================
FILE: docs/src/3.x/installation.md
================================================
# 安装
## 环境要求
- PHP >= 5.5.9
- [PHP cURL 扩展](http://php.net/manual/en/book.curl.php)
- [PHP OpenSSL 扩展](http://php.net/manual/en/book.openssl.php)
- [PHP fileinfo 拓展](http://php.net/manual/en/book.fileinfo.php) 素材管理模块需要用到
Laravel 5 拓展包: [overtrue/laravel-wechat](https://github.com/overtrue/laravel-wechat)
## 安装
使用 [composer](http://getcomposer.org/):
```shell
$ composer require overtrue/wechat:~3.1 -vvv
```
================================================
FILE: docs/src/3.x/integration.md
================================================
# 在框架中使用
EasyWeChat 是一个通用的 Composer 包,所以不需要对框架单独做修改,只要支持 Composer 就能直接使用,当然了,为了更方便的使用,我们收集了以下框架单独提供的拓展包:
## Laravel
- [overtrue/laravel-wechat](https://github.com/overtrue/laravel-wechat)
## Symfony
- [lilocon/WechatBundle](https://github.com/lilocon/WechatBundle)
## Yii
- [max-wen/yii2-easy-wechat](https://github.com/max-wen/yii2-easy-wechat)
## CI
TODO
## Phalcon
TODO
... more
================================================
FILE: docs/src/3.x/js.md
================================================
# JSSDK
## 获取实例
```php
js;
```
## API
- `$js->config(array $APIs, $debug = false, $beta = false, $json = true);` 获取JSSDK的配置数组,默认返回 JSON 字符串,当 `$json` 为 `false` 时返回数组,你可以直接使用到网页中。
- `$js->setUrl($url)` 设置当前URL,如果不想用默认读取的URL,可以使用此方法手动设置,通常不需要。
example:
我们可以生成js配置文件:
```js
```
结果如下:
```js
```
更多 JSSDK 的使用请参考 [微信官方文档](http://mp.weixin.qq.com/wiki/) 中 **JSSDK章节**
================================================
FILE: docs/src/3.x/lucky-money.md
================================================
# 红包
你在阅读本文之前确认你已经仔细阅读了:[微信支付 | 现金红包文档 ](https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_1)。
## 配置
与支付接口一样,红包接口也需要配置如下参数,需要特别注意的是,红包相关的全部接口**都需要使用 SSL 证书**,因此** cert_path 以及 cert_key 必须正确配置**。
```php
[
'merchant_id' => 'your-mch-id',
'key' => 'key-for-signature',
'cert_path' => 'path/to/your/cert.pem',
'key_path' => 'path/to/your/key',
// ...
],
];
$app = new Application($options);
$luckyMoney = $app->lucky_money;
```
## 发送红包
微信的现金红包分为**普通红包**和**裂变红包**两类。SDK 中对其分别进行了封装,同时也提供了一个统一的调用方法。
**默认情况下,通过接口发送的红包金额应该在200元以内,但可以通过在调用发送接口时传递场景 ID (scene_id)来发送特定场景的红包,不同场景红包可以由商户自己登录商户平台设置最大金额。scene_id 的可选值及对应含义可参阅微信支付官方文档。**
### 通用发送接口
```php
'xy123456',
'send_name' => '测试红包',
're_openid' => 'oxTWIuGaIt6gTKsQRLau2M0yL16E',
'total_num' => 1, //普通红包固定为1,裂变红包不小于3
'total_amount' => 100, //单位为分,普通红包不小于100,裂变红包不小于300
'wishing' => '祝福语',
'client_ip' => '192.168.0.1', //可不传,不传则由 SDK 取当前客户端 IP
'act_name' => '测试活动',
'remark' => '测试备注',
// ...
];
$result = $luckyMoney->send($luckyMoneyData, \EasyWeChat\Payment\LuckyMoney\API::TYPE_NORMAL);
或
$result = $luckyMoney->send($luckyMoneyData, \EasyWeChat\Payment\LuckyMoney\API::TYPE_GROUP);
```
> 不同类型红包所传参数有所差别,请参考官方文档中参数列表。
### 发送普通红包接口
```php
'xy123456',
'send_name' => '测试红包',
're_openid' => 'oxTWIuGaIt6gTKsQRLau2M0yL16E',
'total_num' => 1, //固定为1,可不传
'total_amount' => 100, //单位为分,不小于100
'wishing' => '祝福语',
'client_ip' => '192.168.0.1', //可不传,不传则由 SDK 取当前客户端 IP
'act_name' => '测试活动',
'remark' => '测试备注',
// ...
];
$result = $luckyMoney->sendNormal($luckyMoneyData);
```
### 发送裂变红包接口
```php
'xy123456',
'send_name' => '测试红包',
're_openid' => 'oxTWIuGaIt6gTKsQRLau2M0yL16E',
'total_num' => 3, //不小于3
'total_amount' => 300, //单位为分,不小于300
'wishing' => '祝福语',
'act_name' => '测试活动',
'remark' => '测试备注',
'amt_type' => 'ALL_RAND', //可不传
// ...
];
$result = $luckyMoney->sendGroup($luckyMoneyData);
```
## 红包预下单接口
红包预下单接口是为摇一摇红包接口配合使用的,在开发摇一摇周边的摇红包相关功能时,需要调用本接口获取红包单号。详情参见[官方文档](http://mp.weixin.qq.com/wiki/7/0ddd50ed2421b99fedd071281c074aab.html#.E7.BA.A2.E5.8C.85.E9.A2.84.E4.B8.8B.E5.8D.95.E6.8E.A5.E5.8F.A3)
```php
'NORMAL', //NORMAL 或 GROUP
'mch_billno' => 'xy123456',
'send_name' => '测试红包',
're_openid' => 'oxTWIuGaIt6gTKsQRLau2M0yL16E',
'total_num' => 1, //普通红包固定为1,裂变红包不小于3
'total_amount' => 100, //单位为分,普通红包不小于100,裂变红包不小于300
'wishing' => '祝福语',
'client_ip' => '192.168.0.1', //可不传,不传则由 SDK 取当前客户端 IP
'act_name' => '测试活动',
'remark' => '测试备注',
'amt_type' => 'ALL_RAND',
// ...
];
$result = $luckyMoney->prepare($luckyMoneyData);
```
## 查询红包信息
用于商户对已发放的红包进行查询红包的具体信息以及领取情况 ,普通红包和裂变包均使用这一接口进行查询。
```php
$mchBillNo = "商户系统内部的订单号(mch_billno)";
$luckyMoney->query($mchBillNo);
```
================================================
FILE: docs/src/3.x/material.md
================================================
# 素材管理
在微信里的图片,音乐,视频等等都需要先上传到微信服务器作为素材才可以在消息中使用。
> 请注意:
> 1. 限制:
> - 图片(image): 1M,支持 bmp/png/jpeg/jpg/gif 格式
> - 语音(voice):2M,播放长度不超过 60s,支持 mp3/wma/wav/amr 格式
> - 视频(video):10MB,支持MP4格式
> - 缩略图(thumb):64KB,支持JPG格式
> 2. `media_id` 是可复用的;
> 3. 素材分为 `临时素材` 与 `永久素材`, 临时素材媒体文件在后台保存时间为3天,即 3 天后 `media_id` 失效;
> 4. 新增的永久素材也可以在公众平台官网素材管理模块中看到;
> 5. 永久素材的数量是有上限的,请谨慎新增。图文消息素材和图片素材的上限为5000,其他类型为1000;
## 获取实例
```php
material;
// 临时素材
$temporary = $app->material_temporary;
```
## 永久素材 API:
### 上传图片:
> 注意:微信图片上传服务有敏感检测系统,图片内容如果含有敏感内容,如色情,商品推广,虚假信息等,上传可能失败。
```php
$result = $material->uploadImage("/path/to/your/image.jpg"); // 请使用绝对路径写法!除非你正确的理解了相对路径(好多人是没理解对的)!
var_dump($result);
// {
// "media_id":MEDIA_ID,
// "url":URL
// }
```
> `url` 只有上传图片素材有返回值。
### 上传声音
语音**大小不超过 5M**,**长度不超过 60 秒**,支持 `mp3/wma/wav/amr` 格式。
```php
$result = $material->uploadVoice("/path/to/your/voice.mp3"); // 请使用绝对路径写法!除非你正确的理解了相对路径(好多人是没理解对的)!
$mediaId = $result->media_id;
// {
// "media_id":MEDIA_ID,
// }
```
### 上传视频
```php
$result = $material->uploadVideo("/path/to/your/video.mp4", "视频标题", "视频描述"); // 请使用绝对路径写法!除非你正确的理解了相对路径(好多人是没理解对的)!
$mediaId = $result->media_id;
// {
// "media_id":MEDIA_ID,
// }
```
### 上传缩略图
用于视频封面或者音乐封面。
```php
$result = $material->uploadThumb("/path/to/your/thumb.jpg"); // 请使用绝对路径写法!除非你正确的理解了相对路径(好多人是没理解对的)!
$mediaId = $result->media_id;
// {
// "media_id":MEDIA_ID,
// }
```
### 上传永久图文消息
图文消息没有临时一说。
```php
use EasyWeChat\Message\Article;
// 上传单篇图文
$article = new Article([
'title' => 'xxx',
'thumb_media_id' => $mediaId,
//...
]);
$material->uploadArticle($article);
// 或者多篇图文
$material->uploadArticle([$article, $article2, ...]);
```
### 修改永久图文消息
有三个参数:
- `$mediaId` 要更新的文章的 `mediaId`
- `$article` 文章内容,`Article` 实例或者 全字段数组
- `$index` 要更新的文章在图文消息中的位置(多图文消息时,此字段才有意义,单图片忽略此参数),第一篇为 0;
```php
$result = $material->updateArticle($mediaId, new Article(...));
$mediaId = $result->media_id;
// or
$result = $material->updateArticle($mediaId, [
'title' => 'xxx',
'thumb_media_id' => 'xxx',
// ...
]);
// 指定更新多图文中的第 2 篇
$result = $material->updateArticle($mediaId, new Article(...), 1); // 第 2 篇
```
### 上传永久文章内容图片
> 注意:微信图片上传服务有敏感检测系统,图片内容如果含有敏感内容,如色情,商品推广,虚假信息等,上传可能失败。
返回值中 url 就是上传图片的 URL,可用于后续群发中,放置到图文消息中。
```php
$result = $material->uploadArticleImage($path);
$url = $result->url;
//{
// "url": "http://mmbiz.qpic.cn/mmbiz/gLO17UPS6FS2xsypf378iaNhWacZ1G1UplZYWEYfwvuU6Ont96b1roYsCNFwaRrSaKTPCUdBK9DgEHicsKwWCBRQ/0"
//}
```
### 获取永久素材
```php
$resource = $material->get($mediaId);
```
如果请求的素材为图文消息,则响应如下:
```
{
"news_item": [
{
"title":TITLE,
"thumb_media_id"::THUMB_MEDIA_ID,
"show_cover_pic":SHOW_COVER_PIC(0/1),
"author":AUTHOR,
"digest":DIGEST,
"content":CONTENT,
"url":URL,
"content_source_url":CONTENT_SOURCE_URL
},
//多图文消息有多篇文章
]
}
```
如果返回的是视频消息素材,则内容如下:
```
{
"title":TITLE,
"description":DESCRIPTION,
"down_url":DOWN_URL,
}
```
其他类型的素材消息,则响应的直接为素材的内容,开发者可以自行保存为文件。例如
```
$image = $material->get($mediaId);
file_put_contents('/foo/abc.jpg', $image);
```
### 获取永久素材列表
参考:[微信公众平台开发者文档:获取永久素材列表](http://mp.weixin.qq.com/wiki/12/2108cd7aafff7f388f41f37efa710204.html)
- `$type` 素材的类型,图片(`image`)、视频(`video`)、语音 (`voice`)、图文(`news`)
- `$offset` 从全部素材的该偏移位置开始返回,可选,默认 `0`,0 表示从第一个素材 返回
- `$count` 返回素材的数量,可选,默认 `20`, 取值在 1 到 20 之间
```php
$material->lists($type, $offset, $count);
```
example:
```
$lists = $material->lists('image', 0, 10);
```
图片、语音、视频 等类型的返回如下
```
{
"total_count": TOTAL_COUNT,
"item_count": ITEM_COUNT,
"item": [{
"media_id": MEDIA_ID,
"name": NAME,
"update_time": UPDATE_TIME,
"url":URL
},
//可能会有多个素材
]
}
```
永久图文消息素材列表的响应如下:
```
{
"total_count": TOTAL_COUNT,
"item_count": ITEM_COUNT,
"item": [{
"media_id": MEDIA_ID,
"content": {
"news_item": [{
"title": TITLE,
"thumb_media_id": THUMB_MEDIA_ID,
"show_cover_pic": SHOW_COVER_PIC(0 / 1),
"author": AUTHOR,
"digest": DIGEST,
"content": CONTENT,
"url": URL,
"content_source_url": CONTETN_SOURCE_URL
},
//多图文消息会在此处有多篇文章
]
},
"update_time": UPDATE_TIME
},
//可能有多个图文消息item结构
]
}
```
### 获取素材计数
```php
$stats = $material->stats();
// {
// "voice_count":COUNT,
// "video_count":COUNT,
// "image_count":COUNT,
// "news_count":COUNT
// }
```
### 删除永久素材;
```php
$material->delete($mediaId);
```
## 临时素材 API
上传的临时多媒体文件有格式和大小限制,如下:
- 图片(image): 1M,支持 `JPG` 格式
- 语音(voice):2M,播放长度不超过 `60s`,支持 `AMR\MP3` 格式
- 视频(video):10MB,支持 `MP4` 格式
- 缩略图(thumb):64KB,支持 `JPG` 格式
### 上传图片
> 注意:微信图片上传服务有敏感检测系统,图片内容如果含有敏感内容,如色情,商品推广,虚假信息等,上传可能失败。
```php
$temporary->uploadImage($path);
```
### 上传声音
```php
$temporary->uploadVoice($path);
```
### 上传视频
```php
$temporary->uploadVideo($path, $title, $description);
```
### 上传缩略图
用于视频封面或者音乐封面。
```php
$temporary->uploadThumb($path);
```
### 获取临时素材内容
比如图片、视频、声音等二进制流内容。
```php
$content = $temporary->getStream($mediaId);
file_put_contents('/tmp/abc.jpg', $content);// 请使用绝对路径写法!除非你正确的理解了相对路径(好多人是没理解对的)!
```
### 下载临时素材到本地
其实就是上一个 API 的封装。
```php
$temporary->download($mediaId, "/tmp/", "abc.jpg");
```
参数说明:
- `$directory` 为目标目录,
- `$filename` 为新的文件名,可以为空,默认使用 `$mediaId` 作为文件名。
更多请参考 [微信官方文档](http://mp.weixin.qq.com/wiki) `素材管理` 章节
================================================
FILE: docs/src/3.x/menu.md
================================================
# 自定义菜单
3.0 的菜单组件有所简化,相比 2.x 版本变化如下:
- 去除 `MenuItem` 类,创建菜单直接使用数组不再支持 `callback` 与 `MenuItem` 类似的繁杂的方式
- `set()` 方法与 `addConditional()` 合并为一个方法 `add()`
- `get()` 改名为 `all()`
- `delete()` 与 `deleteById()` 合并为 `destroy()`
- 所有 API 的返回值(非调用失败情况)均为官方文档原样返回(Collection形式),不再取返回值中部分 `key` 返回。
> 例如原来的 `get()` 方法,官方返回的数组为: `{ menu: [...]}`,SDK 取了其中的 `menu` 内容作为返回值,在 3.0 后将直接整体返回。
## 获取菜单模块实例
```php
menu;
```
## API 列表
### 读取(查询)已设置菜单
微信的菜单读取有两个不同的方式:
一种叫 **[查询菜单](http://mp.weixin.qq.com/wiki/5/f287d1a5b78a35a8884326312ac3e4ed.html)**,在 SDK 中以 `all()` 方法来调用:
```php
$menus = $menu->all();
```
另外一种叫 **[获取自定义菜单](http://mp.weixin.qq.com/wiki/14/293d0cb8de95e916d1216a33fcb81fd6.html)**,使用 `current()` 方法来调用:
```php
$menus = $menu->current();
```
### 添加菜单
#### 添加普通菜单
```php
$buttons = [
[
"type" => "click",
"name" => "今日歌曲",
"key" => "V1001_TODAY_MUSIC"
],
[
"name" => "菜单",
"sub_button" => [
[
"type" => "view",
"name" => "搜索",
"url" => "http://www.soso.com/"
],
[
"type" => "view",
"name" => "视频",
"url" => "http://v.qq.com/"
],
[
"type" => "click",
"name" => "赞一下我们",
"key" => "V1001_GOOD"
],
],
],
];
$menu->add($buttons);
```
以上将会创建一个普通菜单。
#### 添加个性化菜单
与创建普通菜单不同的是,需要在 `add()` 方法中将个性化匹配规则作为第二个参数传进去:
```php
$buttons = [
// ...
];
$matchRule = [
"tag_id" => "2",
"sex" => "1",
"country" => "中国",
"province" => "广东",
"city" => "广州",
"client_platform_type" => "2",
"language" => "zh_CN"
];
$menu->add($buttons, $matchRule);
```
### 删除菜单
有两种删除方式,一种是**全部删除**,另外一种是**根据菜单 ID 来删除**(删除个性化菜单时用,ID 从查询接口获取):
```php
$menu->destroy(); // 全部
$menu->destroy($menuId);
```
### 测试个性化菜单
```php
$menus = $menu->test($userId);
```
> `$userId` 可以是粉丝的 OpenID,也可以是粉丝的微信号。
返回 `$menus` 与指定的 `$userId` 匹配的菜单项。
更多关于微信自定义菜单 API 请参考: http://mp.weixin.qq.com/wiki `自定义菜单` 章节。
================================================
FILE: docs/src/3.x/merchant_payment.md
================================================
# 企业支付
你在阅读本文之前确认你已经仔细阅读了:[微信支付 | 企业付款文档 ](https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_1)。
## 配置
与其他支付接口一样,企业支付接口也需要配置如下参数,需要特别注意的是,企业支付相关的全部接口 **都需要使用 SSL 证书**,因此 **cert_path 以及 cert_key 必须正确配置**。
```php
'your-app-id',
// payment
'payment' => [
'merchant_id' => 'your-mch-id',
'key' => 'key-for-signature',
'cert_path' => 'path/to/your/cert.pem',
'key_path' => 'path/to/your/key',
// ...
],
];
$app = new Application($options);
$merchantPay = $app->merchant_pay;
```
## 企业付款
企业付款使用的余额跟微信支付的收款并非同一账户,请注意充值。
### 发送接口
```php
str_random(16), //随机字符串作为订单号,跟红包和支付一个概念。
'openid' => $openid, //收款人的openid
'check_name' => 'NO_CHECK', //文档中有三种校验实名的方法 NO_CHECK OPTION_CHECK FORCE_CHECK
're_user_name'=>'张三', //OPTION_CHECK FORCE_CHECK 校验实名的时候必须提交
'amount' => 100, //单位为分
'desc' => '企业付款',
'spbill_create_ip' => '192.168.0.1', //发起交易的IP地址
];
$result = $merchantPay->send($merchantPayData);
```
> 更多参数请参考官方文档中参数列表。
## 查询付款信息
用于商户对已发放的企业支付进行查询企业支付的具体信息。
```php
$partnerTradeNo = "商户系统内部的订单号(partner_trade_no)";
$merchantPay->query($partnerTradeNo);
```
================================================
FILE: docs/src/3.x/message-transfer.md
================================================
# 多客服消息转发
多客服的消息转发绝对是超级的简单,转发的消息类型为 `transfer`:
```php
// 转发收到的消息给客服
$server->setMessageHandler(function($message) {
return new \EasyWeChat\Message\Transfer();
});
$result = $server->serve();
echo $result;
```
当然,你也可以指定转发给某一个客服:
```php
$server->setMessageHandler(function($message) {
$transfer = new \EasyWeChat\Message\Transfer();
$transfer->account($account);// 或者 $transfer->to($account);
return $transfer;
});
```
更多请参考 [微信官方文档](http://mp.weixin.qq.com/wiki/) **多客服消息转发** 章节
================================================
FILE: docs/src/3.x/messages.md
================================================
# 消息
我把微信的 API 里的所有“消息”都按类型抽象出来了,也就是说,你不用区分它是回复消息还是主动推送消息,免去了你去手动拼装微信那帮 SB 那么恶心的 XML 以及乱七八糟命名不统一的 JSON 了,我替你承受这份苦,不要问是谁,我是雷锋他弟弟,雷管。
在阅读以下内容时请忽略是**接收消息**还是**回复消息**,后面我会给你讲它们的区别。
## 消息类型
消息分为以下几种:`文本`、`图片`、`视频`、`声音`、`链接`、`坐标`、`图文`、`文章` 和一种特殊的 `原始消息`。
另外还有一种特殊的消息类型:**素材消息**,用于群发或者客服时发送已有素材用。
> 注意:回复消息与客服消息里的图文类型为:**图文**,群发与素材中的图文为**文章**
所有的消息类都在 `EasyWeChat\Message` 这个命名空间下, 下面我们来分开讲解:
### 文本消息
属性列表:
```
- content 文本内容
```
```php
'您好!overtrue。']);
// or
$text = new Text();
$text->content = '您好!overtrue。';
// or
$text = new Text();
$text->setAttribute('content', '您好!overtrue。');
```
### 图片消息
属性列表:
```
- media_id 媒体资源 ID
```
```php
$mediaId]);
// or
$text = new Image();
$text->media_id = $mediaId; // or $text->mediaId = $media;
// or
$text = new Image();
$text->setAttribute('media_id', $mediaId);
```
### 视频消息
属性列表:
```
- title 标题
- description 描述
- media_id 媒体资源 ID
- thumb_media_id 封面资源 ID
```
```php
$title,
'media_id' => $mediaId,
'description' => '...',
// ...
]);
// or
$video = new Video();
$video->media_id = $mediaId; // or $video->mediaId = $media;
$video->description = 'video description...'; // or $video->description = $description;
// ...
// or
$video = new Video();
$video->setAttribute('media_id', $mediaId);
// ...
```
### 声音消息
属性列表:
```
- media_id 媒体资源 ID
```
```php
$mediaId]);
// or
$voice = new Voice();
$voice->media_id = $mediaId; // or $voice->mediaId = $media;
// or
$voice = new Voice();
$voice->setAttribute('media_id', $mediaId);
```
### 链接消息
> 微信目前不支持回复链接消息
### 坐标消息
> 微信目前不支持回复坐标消息
### 图文消息
属性列表:
```
- title 标题
- description 描述
- image 图片链接
- url 链接 URL
```
```php
$title,
'description' => '...',
'url' => $url,
'image' => $image,
// ...
]);
// or
$news = new News();
$news->title = 'EasyWeChat';
$news->description = '微信 SDK ...';
// ...
```
### 文章消息
属性列表:
```
- title 标题
- author 作者
- content 具体内容
- thumb_media_id 图文消息的封面图片素材id(必须是永久mediaID)
- digest 图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空
- source_url 来源 URL
- show_cover 是否显示封面,0 为 false,即不显示,1 为 true,即显示
```
```php
'EasyWeChat',
'author' => 'overtrue',
'content' => 'EasyWeChat 是一个开源的微信 SDK,它... ...',
// ...
]);
// or
$article = new Article();
$article->title = 'EasyWeChat';
$article->author = 'overtrue';
$article->content = '微信 SDK ...';
// ...
```
### 素材消息
素材消息用于群发与客服消息时使用。
属性就一个:`media_id`。
在构造时有两个参数:
- `$type` 素材类型,目前只支持:`mpnews`、 `mpvideo`、`voice`、`image` 等。
- `$mediaId` 素材 ID,从接口查询或者上传后得到。
```php
use EasyWeChat\Message\Material;
$material = new Material('mpnews', $mediaId);
```
以上呢,是所有微信支持的基本消息类型。
> 需要注意的是,你不需要关心微信的消息字段叫啥,因为这里我们使用了更标准的命名,然后最终在中间做了转换,所以你不需要关注。
### 原始消息
原始消息是一种特殊的消息,它的场景是:**你不想使用其它消息类型,你想自己手动拼消息**。比如,回复消息时,你想自己拼 XML,那么你就直接用它就可以了:
```php
use EasyWeChat\Message\Raw;
$message = new Raw('
12345678
');
```
比如,你要用于客服消息(客服消息是JSON结构):
```php
use EasyWeChat\Message\Raw;
$message = new Raw('{
"touser":"OPENID",
"msgtype":"text",
"text":
{
"content":"Hello World"
}
}');
```
总之,就是直接写微信接口要求的格式内容就好,此类型消息在 SDK 中不存在转换行为,所以请注意不要写错格式。
## 在 SDK 中使用消息
### 在服务端回复消息
在 [服务端](server.html) 一节中,我们讲了回复消息的写法:
```php
// ... 前面部分省略
$app = new Application($options);
$server = $app->server;
$server->setMessageHandler(function ($message) {
return "您好!欢迎关注我!";
});
$server->serve()->send();
```
上面 `return` 了一句普通的文本内容,这里只是为了方便大家,实际上最后会有一个隐式转换为 `Text` 类型的动作。
如果你要回复其它类型的消息,就需要返回一个具体的实例了,比如回复一个图片类型的消息:
```php
use EasyWeChat\Message\Image;
// ...
$server->setMessageHandler(function ($message) {
return new Image(['media_id' => '........']);
});
// ...
```
#### 回复多图文消息
多图文消息其实就是单图文消息的一个数组而已了:
```php
use EasyWeChat\Message\News;
// ...
$server->setMessageHandler(function ($message) {
$news1 = new News(...);
$news2 = new News(...);
$news3 = new News(...);
$news4 = new News(...);
return [$news1, $news2, $news3, $news4];
});
// ...
```
### 作为客服消息发送
在客服消息里的使用也一样,都是直接传入消息实例即可:
```php
use EasyWeChat\Message\Text;
$message = new Text(['content' => 'Hello world!']);
$result = $app->staff->message($message)->to($openId)->send();
//...
```
#### 发送多图文消息
多图文消息其实就是单图文消息的一个数组而已了:
```php
$news1 = new News(...);
$news2 = new News(...);
$news3 = new News(...);
$news4 = new News(...);
$app->staff->message([$news1, $news2, $news3, $news4])->to($openId)->send();
```
### 群发消息
请参考:[群发消息](broadcast.html)
## 消息转发给客服系统
参见:[多客服消息转发](message-transfer.html)
================================================
FILE: docs/src/3.x/mini_program.md
================================================
title: 小程序
---
## 实例化
```php
[
'app_id' => 'component-app-id',
'secret' => 'component-app-secret',
'token' => 'component-token',
'aes_key' => 'component-aes-key'
],
// ...
];
$app = new Application($options);
$miniProgram = $app->mini_program;
```
## 登录
### 通过 Code 换取 SessionKey
```php
// 3.2 版本
$miniProgram->user->getSessionKey($code);
// 3.3 版本
$miniProgram->sns->getSessionKey($code);
```
## 加密数据解密
```php
$miniProgram->encryptor->decryptData($sessionKey, $iv, $encryptData);
```
## 数据分析
### API
- `summaryTrend($from, $to)` 概况趋势,限定查询1天数据,即 `$from` 要与 `$to` 相同;
- `dailyVisitTrend($from, $to)` 访问日趋势,限定查询1天数据,即 `$from` 要与 `$to` 相同;
- `weeklyVisitTrend($from, $to)` 访问周趋势, `$from` 为周一日期, `$to` 为周日日期;
- `monthlyVisitTrend($from, $to)` 访问月趋势, `$from` 为月初日期, `$to` 为月末日期;
- `visitDistribution($from, $to)` 访问分布,限定查询1天数据,即 `$from` 要与 `$to` 相同;
- `dailyRetainInfo($from, $to)` 访问日留存,限定查询1天数据,即 `$from` 要与 `$to` 相同;
- `weeklyRetainInfo($from, $to)` 访问周留存, `$from` 为周一日期, `$to` 为周日日期;
- `montylyRetainInfo($from, $to)` 访问月留存, `$from` 为月初日期, `$to` 为月末日期;
- `visitPage($from, $to)` 访问页面,限定查询1天数据,即 `$from` 要与 `$to` 相同;
### 代码示例
```php
$miniProgram->stats->summaryTrend('20170313', '20170313');
```
================================================
FILE: docs/src/3.x/miscellaneous.md
================================================
# 其它
### 其它
================================================
FILE: docs/src/3.x/notice.md
================================================
# 模板消息
模板消息仅用于公众号向用户发送重要的服务通知,只能用于符合其要求的服务场景中,如信用卡刷卡通知,商品购买成功通知等。不支持广告等营销类消息以及其它所有可能对用户造成骚扰的消息。
## 获取实例
```php
notice;
```
### API
- `boolean setIndustry($industryId1, $industryId2)` 修改账号所属行业;
- `array getIndustry()` 返回所有支持的行业列表,用于做下拉选择行业可视化更新;
- `string addTemplate($shortId)` 添加模板并获取模板 ID;
- `collection send($message)` 发送模板消息, 返回消息 ID;
- `array getPrivateTemplates()` 获取所有模板列表;
- `array deletePrivateTemplate($templateId)` 删除指定 ID 的模板。
非链接调用方法:
```php
$messageId = $notice->send([
'touser' => 'user-openid',
'template_id' => 'template-id',
'url' => 'xxxxx',
'data' => [
//...
],
]);
```
链式调用方法:
设置模板ID:template / templateId / uses
设置接收者openId: to / receiver
设置详情链接:url / link / linkTo
设置模板数据:data / with
以上方法都支持 `withXXX` 与 `andXXX` 形式链式调用
```php
$messageId = $notice->to($userOpenId)->uses($templateId)->andUrl($url)->data($data)->send();
// 或者
$messageId = $notice->to($userOpenId)->url($url)->template($templateId)->andData($data)->send();
// 或者
$messageId = $notice->withTo($userOpenId)->withUrl($url)->withTemplate($templateId)->withData($data)->send();
// 或者
$messageId = $notice->to($userOpenId)->url($url)->withTemplateId($templateId)->send();
// ... ...
```
## 示例:
### 模板
```
{{ first.DATA }}
商品明细:
名称:{{ name.DATA }}
价格:{{ price.DATA }}
{{ remark.DATA }}
```
发送模板消息:
```php
$userId = 'OPENID';
$templateId = 'ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY';
$url = 'http://overtrue.me';
$data = array(
"first" => "恭喜你购买成功!",
"name" => "巧克力",
"price" => "39.8元",
"remark" => "欢迎再次购买!",
);
$result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();
var_dump($result);
// {
// "errcode":0,
// "errmsg":"ok",
// "msgid":200228332
// }
```
## 模板数据
为了方便大家开发,我们拓展支持以下格式的模板数据,其它格式的数据可能会导致接口调用失败:
- 所有数据项颜色一样的(这是方便的一种方式):
```php
$data = array(
"first" => "恭喜你购买成功!",
"keynote1" => "巧克力",
"keynote2" => "39.8元",
"keynote3" => "2014年9月16日",
"remark" => "欢迎再次购买!",
);
```
默认颜色为'#173177', 你可以通过 `defaultColor($color)` 来修改
- 独立设置每个模板项颜色的:
- 简便型:
```php
$data = array(
"first" => array("恭喜你购买成功!", '#555555'),
"keynote1" => array("巧克力", "#336699"),
"keynote2" => array("39.8元", "#FF0000"),
"keynote3" => array("2014年9月16日", "#888888"),
"remark" => array("欢迎再次购买!", "#5599FF"),
);
```
- 复杂型(也是微信官方唯一支持的方式,估计没有人想这么用):
```php
$data = array(
"first" => array("value" => "恭喜你购买成功!", "color" => '#555555'),
"keynote1" => array("value" => "巧克力", "color" => "#336699"),
"keynote2" => array("value" => "39.8元","color" => "#FF0000"),
"keynote3" => array("value" => "2014年9月16日", "color" => "#888888"),
"remark" => array("value" => "欢迎再次购买!", "color" => "#5599FF"),
);
```
关于模板消息的使用请参考 [微信官方文档](http://mp.weixin.qq.com/wiki/)
================================================
FILE: docs/src/3.x/oauth.md
================================================
# 网页授权
## 关于 OAuth2.0
OAuth 是一个关于授权(authorization)的开放网络标准,在全世界得到广泛应用,目前的版本是 2.0 版。
```
+--------+ +---------------+
| |--(A)- Authorization Request ->| Resource |
| | | Owner |
| |<-(B)-- Authorization Grant ---| |
| | +---------------+
| |
| | +---------------+
| |--(C)-- Authorization Grant -->| Authorization |
| Client | | Server |
| |<-(D)----- Access Token -------| |
| | +---------------+
| |
| | +---------------+
| |--(E)----- Access Token ------>| Resource |
| | | Server |
| |<-(F)--- Protected Resource ---| |
+--------+ +---------------+
OAuth 授权流程
```
> 摘自:[RFC 6749](https://datatracker.ietf.org/doc/rfc6749/?include_text=1)
步骤解释:
(A)用户打开客户端以后,客户端要求用户给予授权。
(B)用户同意给予客户端授权。
(C)客户端使用上一步获得的授权,向认证服务器申请令牌。
(D)认证服务器对客户端进行认证以后,确认无误,同意发放令牌。
(E)客户端使用令牌,向资源服务器申请获取资源。
(F)资源服务器确认令牌无误,同意向客户端开放资源。
关于 OAuth 协议我们就简单了解到这里,如果还有不熟悉的同学,请 [Google 相关资料](https://www.google.com.hk/?gws_rd=ssl#safe=strict&q=OAuth2)
## 微信 OAuth
在微信里的 OAuth 其实有两种:[公众平台网页授权获取用户信息](http://mp.weixin.qq.com/wiki/9/01f711493b5a02f24b04365ac5d8fd95.html)、[开放平台网页登录](https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN)。
它们的区别有两处,授权地址不同,`scope` 不同。
- **公众平台网页授权获取用户信息**
**授权 URL**: `https://open.weixin.qq.com/connect/oauth2/authorize`
**Scopes**: `snsapi_base` 与 `snsapi_userinfo`
- **开放平台网页登录**
**授权 URL**: `https://open.weixin.qq.com/connect/qrconnect`
**Scopes**: `snsapi_login`
他们的逻辑都一样:
1. 用户尝试访问一个我们的业务页面,例如: `/user/profile`
2. 如果用户已经登录,则正常显示该页面
3. 系统检查当前访问的用户并未登录(从 session 或者其它方式检查),则跳转到**跳转到微信授权服务器**(上面的两种中一种**授权 URL**),并告知微信授权服务器我的**回调 URL(redirect_uri=callback.php)**,此时用户看到蓝色的授权确认页面(`scope` 为 `snsapi_base` 时不显示)
4. 用户点击确定完成授权,浏览器跳转到**回调 URL**: `callback.php` 并带上 `code`: `?code=CODE&state=STATE`。
5. 在 `callback.php` 中得到 `code` 后,通过 `code` 再次向微信服务器请求得到 **网页授权 access_token** 与 `openid`
6. 你可以选择拿 `openid` 去请求 API 得到用户信息(可选)
7. 将用户信息写入 SESSION。
8. 跳转到第 3 步写入的 `target_url` 页面(`/user/profile`)。
> 看懵了?没事,使用 SDK,你不用管这么多。:smile:
>
> 注意,上面的第 3 步:redirect_uri=callback.php 实际上我们会在 `callback.php` 后面还会带上授权目标页面 `user/profile`,所以完整的 `redirect_uri` 应该是下面的这样的 PHP 去拼出来:`'redirect_uri='.urlencode('callback.php?target=user/profile')`
> 结果:redirect_uri=callback.php%3Ftarget%3Duser%2Fprofile
## 逻辑组成
从上面我们所描述的授权流程来看,我们至少有 3 个页面:
1. **业务页面**,也就是需要授权才能访问的页面。
2. **发起授权页**,此页面其实可以省略,可以做成一个中间件,全局检查未登录就发起授权。
3. **授权回调页**,接收用户授权后的状态,并获取用户信息,写入用户会话状态(SESSION)。
## 开始之前
在开始之前请一定要记住,先登录公众号后台,找到**边栏 “开发”** 模块下的 **“接口权限”**,点击 **“网页授权获取用户基本信息”** 后面的修改,添加你的网页授权域名。
> 如果你的授权地址为:`http://www.abc.com/xxxxx`,那么请填写 `www.abc.com`,也就是说请填写与网址匹配的域名,前者如果填写 `abc.com` 是通过不了的。
## SDK 中 OAuth 模块的 API
在 SDK 中,我们使用名称为 `oauth` 的模块来完成授权服务,我们主要用到以下两个 API:
### 发起授权
```php
$response = $app->oauth->scopes(['snsapi_userinfo'])
->redirect();
```
当你的应用是分布式架构且没有会话保持的情况下,你需要自行设置请求对象以实现会话共享。比如在 [Laravel](http://laravel.com) 框架中支持 Session 储存在 Redis 中,那么需要这样:
```php
$response = $app->oauth->scopes(['snsapi_userinfo'])
->setRequest($request)
->redirect();
//回调后获取user时也要设置$request对象
//$user = $app->oauth->setRequest($request)->user();
```
它的返回值 `$response` 是一个 [Symfony\Component\HttpFoundation\RedirectResponse](http://api.symfony.com/3.0/Symfony/Component/HttpFoundation/RedirectResponse.html) 实例。
你可以选择在框架中做一些正确的响应,比如在 [Laravel](http://laravel.com) 框架中控制器方法是要求返回响应值的,那么你就直接:
```php
return $response;
```
在有的框架 (比如 yii2) 中是直接 `echo` 或者 `$this->display()` 这种的时候,你就直接:
```php
$response->send(); // Laravel 里请使用:return $response;
```
### 获取已授权用户
```php
$user = $app->oauth->user();
// $user 可以用的方法:
// $user->getId(); // 对应微信的 OPENID
// $user->getNickname(); // 对应微信的 nickname
// $user->getName(); // 对应微信的 nickname
// $user->getAvatar(); // 头像网址
// $user->getOriginal(); // 原始API返回的结果
// $user->getToken(); // access_token, 比如用于地址共享时使用
```
返回的 `$user` 是 [Overtrue\Socialite\User](https://github.com/overtrue/socialite/blob/master/src/User.php) 对象,你可以从该对象拿到[更多的信息](https://github.com/overtrue/socialite#user-interface)。
> :pray: 注意:`$user` 里没有 `openid`, `$user->id` 便是 `openid`.
> 如果你想拿微信返回给你的原样的全部信息,请使用:$user->getOriginal();
当 `scope` 为 `snsapi_base` 时 `$oauth->user();` 对象里只有 `id`,没有其它信息。
## 网页授权实例
我们这里来用原生 PHP 写法举个例子,`oauth_callback` 是我们的授权回调 URL (未 urlencode 编码的 URL), `user/profile` 是我们需要授权才能访问的页面,它的 PHP 代码如下:
```php
// http://easywechat.com/user/profile
[
'scopes' => ['snsapi_userinfo'],
'callback' => '/oauth_callback',
],
// ..
];
$app = new Application($config);
$oauth = $app->oauth;
// 未登录
if (empty($_SESSION['wechat_user'])) {
$_SESSION['target_url'] = 'user/profile';
return $oauth->redirect();
// 这里不一定是return,如果你的框架action不是返回内容的话你就得使用
// $oauth->redirect()->send();
}
// 已经登录过
$user = $_SESSION['wechat_user'];
// ...
```
授权回调页:
```php
// http://easywechat.com/oauth_callback
oauth;
// 获取 OAuth 授权结果用户信息
$user = $oauth->user();
$_SESSION['wechat_user'] = $user->toArray();
$targetUrl = empty($_SESSION['target_url']) ? '/' : $_SESSION['target_url'];
header('location:'. $targetUrl); // 跳转到 user/profile
```
上面的例子呢都是基于 `$_SESSION` 来保持会话的,在微信客户端中,你可以结合 COOKIE 来存储,但是有效期平台不一样时间也不一样,好像 Android 的失效会快一些,不过基本也够用了。
更多关于微信网页授权 API 请参考: http://mp.weixin.qq.com/wiki/
更多开放平台网页登录请参考:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN
================================================
FILE: docs/src/3.x/open_platform.md
================================================
# 微信开放平台
### 实例化
```php
[
'app_id' => 'component-app-id',
'secret' => 'component-app-secret',
'token' => 'component-token',
'aes_key' => 'component-aes-key'
],
// ...
];
$app = new Application($options);
$openPlatform = $app->open_platform;
```
### 监听微信服务器推送事件
公众号第三方平台推送的有四个事件:授权成功(`authorized`),授权更新(`updateauthorized`),授权取消(`unauthorized`),以及 `component_verify_ticket`。
本 SDK 默认处理方式为:
- `authorized` / `updateauthorized`: 获取授权方(Authorizer)的所有信息,并缓存 `authorizer_access_token` 和 `authorizer_refresh_token`,授权方的信息则需要开发者手动处理。
- `unauthorized`: 删除 `authorizer_access_token` 和 `authorizer_refresh_token` 的缓存。
- `component_verify_ticket`: 缓存 `component_veirfy_ticket`。
当然也允许自定义处理这些事件,不过以上默认处理仍然会先执行,为的是帮助开发者免去缓存的困扰。
```php
// 默认处理方式
$openPlatform->server->serve();
// 自定义处理
$openPlatform->server->setMessageHandler(function($event) {
// 事件类型常量定义在 \EasyWeChat\OpenPlatform\Guard 类里
switch ($event->InfoType) {
case 'authorized':
// ...
case 'unauthorized':
// ...
case 'updateauthorized':
// ...
case 'component_verify_ticket':
// ...
}
});
$openPlatform->server->serve();
// 或者
$openPlatform->server->listen(function ($event) {
switch ($event->InfoType) {
// ...
}
});
```
#### 授权成功,授权更新
这两个事件下,SDK 默认抓取了所有授权方所有的信息,并缓存 `authorizer_access_token` 和 `authorizer_refresh_token`,授权方的信息为原微信 API 的返回结果,由开发者自行处理,比如保存到数据库。
```php
// 自定义处理
// 其中 $event 变量里有微信推送事件本身的信息,也有授权方所有的信息。
$openPlatform->server->setMessageHandler(function($event) {
// 事件类型常量定义在 \EasyWeChat\OpenPlatform\Guard 类里
switch ($event->InfoType) {
case 'authorized':
// 授权信息,主要是 token 和授权域
$info1 = $event->authorization_info;
// 授权方信息,就是授权方公众号的信息了
$info2 = $event->authorizer_info;
}
});
```
目前 SDK 对这两个事件的处理方式没有区别。
#### 授权取消
SDK 默认处理:删除 `authorizer_access_token` 和 `authorizer_refresh_token` 的缓存。开发者可以自行处理数据库删除授权方信息等操作。
#### 推送 component_verify_ticket
在公众号第三方平台创建审核通过后,微信服务器会向其“授权事件接收URL”每隔10分钟定时推送 `component_verify_ticket`。SDK 内部已实现缓存 `component_veirfy_ticket`,无需开发者另行缓存。
注:需要在URL路由中写上触发代码,并且注册路由后需要等待微信服务器推送 `component_verify_ticket`,才能进行后续操作,否则报"Component verify ticket does not exists."
### 调用 API
#### 设置授权方的 App Id
开发者必须设置授权方来调用 API。
```php
$openPlatform = new Application($options)->open_platform;
// 加载授权方信息,比如 $authorizer = Authorizer::find($id);
$authorizerAppId = $authorizer->app_id;
$authorizerRefreshToken = $authorizer->refresh_token;
$app = $openPlatform->createAuthorizerApplication($authorizerAppId, $authorizerRefreshToken);
// 然后调用方法和普通调用一致。
// ...
```
### 授权 API
#### 获取预授权网址
```php
// 直接跳转
$response = $openPlatform->pre_auth->redirect('https://domain.com/callback');
// 获取跳转的链接
$response->getTargetUrl();
```
用户授权后会带上 `code` 跳转到 `redirect` 指定的链接。
#### 使用授权码换取公众号的接口调用凭据和授权信息
```php
// 使用授权码换取公众号的接口调用凭据和授权信息
// Optional: $authorizationCode 不传值时会自动获取 URL 中 auth_code 值
$openPlatform->getAuthorizationInfo($authorizationCode = null);
```
#### 获取授权方的公众号帐号基本信息
```php
$openPlatform->getAuthorizerInfo($authorizerAppId);
```
#### 获取授权方的选项设置信息
```php
$openPlatform->getAuthorizerOption($authorizerAppId, $optionName);
```
#### 设置授权方的选项信息
```php
$openPlatform->setAuthorizerOption($authorizerAppId, $optionName, $optionValue);
```
================================================
FILE: docs/src/3.x/overview.md
================================================
# EasyWeChat
## EasyWeChat 是什么?
EasyWeChat 是一个开源的 [微信](http://www.wechat.com) 非官方 SDK。
EasyWeChat 的安装非常简单,因为它是一个标准的 [Composer](https://getcomposer.org/) 包,这意味着任何满足下列安装条件的 PHP 项目支持 Composer 都可以使用它。
### 环境需求
- PHP >= 5.5.9 (其实你不必惊讶,PHP 7 的时代了)
- [PHP cURL 扩展](http://php.net/manual/en/book.curl.php)
- [PHP OpenSSL 扩展](http://php.net/manual/en/book.openssl.php)
- [PHP fileinfo 拓展](http://php.net/manual/en/book.fileinfo.php) 素材管理模块需要用到
### 加入我们
ID: 319502940
> 为了避免广告及不看文档用户,加群需要付费,所以请使用 能支持群费的客户端。
> 另外:付费加群不代表我们有责任在群里回答你的问题,所以请认真阅读微信官方文档与 SDK 使用文档再使用,否则提的低级问题不会有人理你
> 不喜勿加,谢谢!
> 除非你发现了明确的 Bug,否则不要在群里 @ 我,否则直接 T 人(当然了,不退群费):pray:
你有以下两种方式加入到我们中来,为广大开发者提供更优质的免费开源的服务:
- **贡献代码**:我们 3.0 的代码都在 [overtrue/wechat](https://github.com/overtrue/wechat) ,你可以提交 PR 到任何一个项目,当然,前提是代码质量必须是 OK 的。
- **翻译或补充文档**:我们的文档在:[w7corp/EasyWeChat/docs](https://github.com/w7corp/easywechat/tree/master/docs),你可以选择补充文档或者参与英文文档的翻译,目前有 `zh-cn` 与 `en` 两个分支,你可以提交对应的 PR 到目标分支参与翻译工作。
### 开始之前
本 SDK 不是一个全新再造的东西,所以我不会从 0 开始教会你开发微信,你完全有必要在使用本 SDK 前做好以下工作:
- 具备 PHP 基础知识,不要连闭包是啥都不明白,可以参考我在知乎的回答: [想要开发自己的 PHP 框架需要那些知识储备?](http://www.zhihu.com/question/26635323/answer/33812516)
- 熟悉 PHP 常见的知识:自动加载、composer 的使用、JSON 处理、Curl 的使用等;
- **仔细阅读并看懂** (不是**看过**,是**看明白+看完** :exclamation:) [微信官方文档](http://mp.weixin.qq.com/wiki/13/80a1a25adbc46faf2716774c423b3151.html) [微信开放平台文档](https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419318292&token=&lang=zh_CN);
- 明白微信接口的组成,自有服务器、微信服务器、公众号(还有其它各种号)、测试号、以及通信原理(交互过程);
- 了解基本的 HTTP 协议,Header 头、请求方式(GET\POST\PUT\PATCH\DELETE)等;
- 基本的 Debug 技能,查看 php 日志,nginx 日志等。
如果你不具备这些知识,请不要使用,因为用起来会比较痛苦。
另外你有必要看一下以下的链接:
- https://phphub.org/topics/535
- http://laravel-china.github.io/php-the-right-way/
如果你在群里问以下类似的问题,这真的是你没有做好上面的工作:
- "为啥我的不行啊,请问服务器日志怎么看啊?"
- "请问这是什么原因啊?[结果/报错截图]"
- "请问这个 SDK 怎么用啊?"
- "谁能告诉我这个 SDK 是怎么安装的啊?"
- "怎么接收用户发的消息啊?"
- "为啥我的报这个错啊:Class XXXX not found..."
- ...
我们专门针对一些容易出现的通用问题已经做了汇总: [疑难解答](troubleshooting) ,如果你在问题疑难解答没找到你出现的问题,那么可以在这里提问 [GitHub](https://github.com/overtrue/wechat/issues),提问请描述清楚你用的版本,你的做法是什么,不然别人没法帮你。
最后,请 **不要在 QQ 单独找我提问**,除非你是发现了明显的 bug。有问题先审查代码,看文档, 再 google,然后 去群里发个问题,带上你的代码,重现流程,大家有空的会帮忙你解答。谢谢合作!:pray:
### 打赏支持
这是一个开源的项目,我们没有收费服务,你如果觉得你从中获益,简化了你的开发工作,你可以 [打赏](https://github.com/sponsors/overtrue) 来支持我们。
================================================
FILE: docs/src/3.x/payment.md
================================================
# 支付
你在阅读本文之前确认你已经仔细阅读了:[微信支付 | 商户平台开发文档](https://pay.weixin.qq.com/wiki/doc/api/index.html)。
网友贡献的教程:[小能手马闯 set 发布在 Laravel-China 的文章《基于 Laravel5.1 LTS 版的微信开发》](https://laravel-china.org/topics/3146)
## 配置
配置在前面的例子中已经提到过了,支付的相关配置如下:
```php
'xxxx',
// ...
// payment
'payment' => [
'merchant_id' => 'your-mch-id',
'key' => 'key-for-signature',
'cert_path' => 'path/to/your/cert.pem', // XXX: 绝对路径!!!!
'key_path' => 'path/to/your/key', // XXX: 绝对路径!!!!
'notify_url' => '默认的订单回调地址', // 你也可以在下单时单独设置来想覆盖它
// 'device_info' => '013467007045764',
// 'sub_app_id' => '',
// 'sub_merchant_id' => '',
// ...
],
];
$app = new Application($options);
$payment = $app->payment;
```
## 创建订单
### 正常模式
```php
'JSAPI', // JSAPI,NATIVE,APP...
'body' => 'iPad mini 16G 白色',
'detail' => 'iPad mini 16G 白色',
'out_trade_no' => '1217752501201407033233368018',
'total_fee' => 5388, // 单位:分
'notify_url' => 'http://easywechat.com/order-notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
'openid' => '当前用户的 openid', // trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识,
// ...
];
$order = new Order($attributes);
```
### 子服务商模式
```php
'JSAPI', // JSAPI,NATIVE,APP...
'body' => 'iPad mini 16G 白色',
'detail' => 'iPad mini 16G 白色',
'out_trade_no' => '1217752501201407033233368018',
'total_fee' => 5388, // 单位:分
'notify_url' => 'http://easywechat.com/order-notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
'sub_openid' => '当前用户的 openid', // 如果传入sub_openid, 请在实例化Application时, 同时传入$sub_app_id, $sub_merchant_id
// ...
];
$order = new Order($attributes);
```
通知 url 必须为直接可访问的 url,不能携带参数。示例:notify_url:“https://pay.weixin.qq.com/wxpay/pay.action”
## 下单接口
### 刷卡支付
[官方文档](https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=9_10)
```php
$result = $payment->pay($order);
```
> 也许你需要生成二维码图片,参考页面底部相关的包推荐
## 统一下单
[公众号支付](https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1)、[扫码支付](https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=6_1)、[APP 支付](https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=9_1) 都统一使用此接口完成订单的创建。
```php
$result = $payment->prepare($order);
if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
$prepayId = $result->prepay_id;
}
```
## 支付结果通知
在用户成功支付后,微信服务器会向该 **订单中设置的回调 URL** 发起一个 POST 请求,请求的内容为一个 XML。里面包含了所有的详细信息,具体请参考:
[支付结果通用通知](https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7)
在本 SDK 中处理回调真的再简单不过了,请求验证你就不用管了,SDK 已经为你做好了,你只需要关注业务即可:
```php
$response = $app->payment->handleNotify(function($notify, $successful){
// 你的逻辑
return true; // 或者错误消息
});
$response->send(); // Laravel 里请使用:return $response;
```
这里需要注意的有几个点:
1. `handleNotify` 只接收一个 [`callable`](http://php.net/manual/zh/language.types.callable.php) 参数,通常用一个匿名函数即可。
2. 该匿名函数接收两个参数,这两个参数分别为:
- `$notify` 为封装了通知信息的 `EasyWeChat\Support\Collection` 对象,前面已经讲过这里就不赘述了,你可以以对象或者数组形式来读取通知内容,比如:`$notify->total_fee` 或者 `$notify['total_fee']`。
- `$successful` 这个参数其实就是判断 **用户是否付款成功了**(result_code == 'SUCCESS')
3. 该函数返回值就是告诉微信 **“我是否处理完成”**,如果你返回一个 `false` 或者一个具体的错误消息,那么微信会在稍后再次继续通知你,直到你明确的告诉它:“我已经处理完成了”,在函数里 `return true;` 代表处理完成。
4. `handleNotify` 返回值 `$response` 是一个 Response 对象,如果你要直接输出,使用 `$response->send()`, 在一些框架里不是输出而是返回:`return $response`。
通常我们的处理逻辑大概是下面这样(**以下只是伪代码**):
```php
$response = $app->payment->handleNotify(function($notify, $successful){
// 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
$order = 查询订单($notify->out_trade_no);
if (!$order) { // 如果订单不存在
return 'Order not exist.'; // 告诉微信,我已经处理完了,订单没找到,别再通知我了
}
// 如果订单存在
// 检查订单是否已经更新过支付状态
if ($order->paid_at) { // 假设订单字段“支付时间”不为空代表已经支付
return true; // 已经支付成功了就不再更新了
}
// 用户是否支付成功
if ($successful) {
// 不是已经支付状态则修改为已经支付状态
$order->paid_at = time(); // 更新支付时间为当前时间
$order->status = 'paid';
} else { // 用户支付失败
$order->status = 'paid_fail';
}
$order->save(); // 保存订单
return true; // 返回处理完成
});
return $response;
```
> 注意:请把 “支付成功与否” 与 “是否处理完成” 分开,它俩没有必然关系。
> 比如:微信通知你用户支付完成,但是支付失败了(result_code 为 'FAIL'),你应该**更新你的订单为支付失败**,但是要**告诉微信处理完成**。
## 撤销订单 API
目前只有 **刷卡支付** 有此功能。
> 调用支付接口后请勿立即调用撤销订单 API,建议支付后至少 15s 后再调用撤销订单接口。
```php
$orderNo = "商户系统内部的订单号(out_trade_no)";
$payment->reverse($orderNo);
```
或者:
```php
$orderNo = "微信的订单号(transaction_id)";
$payment->reverseByTransactionId($orderNo);
```
## 查询订单
该接口提供所有微信支付订单的查询,商户可以通过该接口主动查询订单状态,完成下一步的业务逻辑。
需要调用查询接口的情况:
- 当商户后台、网络、服务器等出现异常,商户系统最终未接收到支付通知;
- 调用支付接口后,返回系统错误或未知交易状态情况;
- 调用被扫支付 API,返回 USERPAYING 的状态;
- 调用关单或撤销接口 API 之前,需确认支付状态;
```php
$orderNo = "商户系统内部的订单号(out_trade_no)";
$payment->query($orderNo);
```
或者:
```php
$orderNo = "微信的订单号(transaction_id)";
$payment->queryByTransactionId($orderNo);
```
## 关闭订单
> 注意:订单生成后不能马上调用关单接口,最短调用时间间隔为 5 分钟。
```php
$orderNo = "商户系统内部的订单号(out_trade_no)";
$payment->close($orderNo);
```
## 申请退款
当交易发生之后一段时间内,由于买家或者卖家的原因需要退款时,卖家可以通过退款接口将支付款退还给买家,微信支付将在收到退款请求并且验证成功之后,按照退款规则将支付款按原路退到买家帐号上。
注意:
> 1、交易时间超过一年的订单无法提交退款;
> 2、微信支付退款支持单笔交易分多次退款,多次退款需要提交原支付订单的商户订单号和设置不同的退款单号。一笔退款失败后重新提交,要采用原来的退款单号。总退款金额不能超过用户实际支付金额。
```php
$payment->refund(订单号,退款单号,总金额,退款金额,操作员,退款单号类型(out_trade_no/transaction_id),退款账户(REFUND_SOURCE_UNSETTLED_FUNDS/REFUND_SOURCE_RECHARGE_FUNDS))
```
参考:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4
例子:
```php
# 1. 使用商户订单号退款
$result = $payment->refund($orderNo, $refundNo, 100); // 总金额 100 退款 100,操作员:商户号
// or
$result = $payment->refund($orderNo, $refundNo, 100, 80); // 总金额 100, 退款 80,操作员:商户号
// or
$result = $payment->refund($orderNo, $refundNo, 100, 80, 1900000109); // 总金额 100, 退款 80,操作员:1900000109
// or
$result = $payment->refund($orderNo, $refundNo, 100, 80, 1900000109, 'out_trade_no'); // 总金额 100, 退款 80,操作员:1900000109, 退款单号:使用商户订单号退款
// or
$result = $payment->refund($orderNo, $refundNo, 100, 80, 1900000109, 'out_trade_no', 'REFUND_SOURCE_RECHARGE_FUNDS'); // 总金额 100, 退款 80,操作员:1900000109, 退款单号:使用商户订单号退款, 退款账户:可用余额退款
# 2. 使用 TransactionId 退款
$result = $payment->refundByTransactionId($transactionId, $refundNo, 100); // 总金额 100 退款 100,操作员:商户号
// or
$result = $payment->refundByTransactionId($transactionId, $refundNo, 100, 80); // 总金额 100, 退款 80,操作员:商户号
// or
$result = $payment->refundByTransactionId($transactionId, $refundNo, 100, 80, 1900000109); // 总金额 100, 退款 80,操作员:1900000109
// or
$result = $payment->refundByTransactionId($transactionId, $refundNo, 100, 80, 1900000109, 'REFUND_SOURCE_RECHARGE_FUNDS'); // 总金额 100, 退款 80,操作员:1900000109,退款账户:可用余额退款
```
> $refundNo 为商户退款单号,自己生成用于自己识别即可。
## 查询退款
提交退款申请后,通过调用该接口查询退款状态。退款有一定延时,用零钱支付的退款 20 分钟内到账,银行卡支付的退款 3 个工作日后重新查询退款状态。
```php
$result = $payment->queryRefund($outTradeNo);
// or
$result = $payment->queryRefundByTransactionId($transactionId);
// or
$result = $payment->queryRefundByRefundNo($outRefundNo);
// or
$result = $payment->queryRefundByRefundId($refundId);
```
## 下载对账单
```php
$bill = $payment->downloadBill('20140603')->getContents(); // type: ALL
// or
$bill = $payment->downloadBill('20140603', 'SUCCESS')->getContents(); // type: SUCCESS
// bill 为 csv 格式的内容
// 保存为文件
file_put_contents('YOUR/PATH/TO/bill-20140603.csv', $bill);
```
第二个参数为类型:
- **ALL**:返回当日所有订单信息(默认值)
- **SUCCESS**:返回当日成功支付的订单
- **REFUND**:返回当日退款订单
- **REVOKED**:已撤销的订单
## 测速上报
```php
$payment->report($api, $timeConsuming, $resultCode, $returnCode);
// or
$payment->report($api, $timeConsuming, $resultCode, $returnCode, [
'err_code' => 'xxxx',
'err_code_des' => '...',
'out_trade_no' => '...',
'user_ip' => '...',
]);
```
## 转换短链接
```php
$shortUrl = $payment->urlShorten('http://easywechat.com');
```
## 授权码查询 OPENID 接口
```php
$response = $payment->authCodeToOpenId($authCode);
$response->openid;
```
## 生成支付 JS 配置
有两种发起支付的方式:[WeixinJSBridge](https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6), [JSSDK](https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115&token=&lang=zh_CN)
1. WeixinJSBridge:
```php
$json = $payment->configForPayment($prepayId); // 返回 json 字符串,如果想返回数组,传第二个参数 false
```
javascript:
```js
...
WeixinJSBridge.invoke(
'getBrandWCPayRequest', = $json ?>,
function(res){
if(res.err_msg == "get_brand_wcpay_request:ok" ) {
// 使用以上方式判断前端返回,微信团队郑重提示:
// res.err_msg将在用户支付成功后返回
// ok,但并不保证它绝对可靠。
}
}
);
...
```
2. JSSDK:
```php
$config = $payment->configForJSSDKPayment($prepayId); // 返回数组
```
javascript:
```js
wx.chooseWXPay({
timestamp: = $config['timestamp'] ?>,
nonceStr: '= $config['nonceStr'] ?>',
package: '= $config['package'] ?>',
signType: '= $config['signType'] ?>',
paySign: '= $config['paySign'] ?>', // 支付签名
success: function (res) {
// 支付成功后的回调函数
}
});
```
## 生成共享收货地址 JS 配置
1. 发起 OAuth 授权:
```php
use EasyWeChat\Support\Url as UrlHelper;
// 检查当前不是微信 oauth 的回调,则跳过去授权
// 注意,授权回调地址为当前页
if (empty($_GET['code'])) {
$currentUrl = UrlHelper::current(); // 获取当前页 URL
$response = $app->oauth->scopes(['snsapi_base'])->redirect($currentUrl);
return $response; // or echo $response;
}
// 授权回来
$oauthUser = $app->oauth->user();
$token = $oauthUser->getAccessToken();
$configForPickAddress = $payment->configForShareAddress($token);
// 拿着这个生成好的配置 $configForPickAddress 去订单页(或者直接显示订单页)写 js 调用了
// ...
```
## 生成 APP 支付配置
```php
$config = $payment->configForAppPayment($prepayId);
```
`$config` 为数组格式,你可以用 API 返回给客户端
# 二维码生成工具推荐
你也许需要生成二维码,那么以下这些供参考:
- https://github.com/endroid/QrCode
- https://github.com/Bacon/BaconQrCode
- https://github.com/SimpleSoftwareIO/simple-qrcode (Bacon/BaconQrCode 的 Laravel 版本)
- https://github.com/aferrandini/PHPQRCode
================================================
FILE: docs/src/3.x/poi.md
================================================
# 门店
## 获取实例
```php
poi;
```
## 创建门店
用 POI 接口新建门店时所使用的图片 url 必须为微信自己域名的 url,因此需要先用上传图片接 口上传图片并获取 url,再创建门店。上传的图片限制文件大小限制 1MB,支持 JPG 格式,图片接口请参考:[TODO](/)
```php
$poi->create($baseInfo);
```
- `$baseInfo` 为门店的基本信息数组
example:
```php
"33788392",
"business_name" => "麦当劳",
"branch_name" => "艺苑路店",
"province" => "广东省",
"city" => "广州市",
"district" => "海珠区",
"address" => "艺苑路 11 号",
"telephone" => "020-12345678",
"categories" => array("美食,快餐小吃"),
"offset_type" => 1,
"longitude" => 115.32375,
"latitude" => 25.097486,
"photo_list" => array(
array("photo_url" => "https://easywechat.com"),
array("photo_url" => "https://easywechat.com"),
),
"recommend" => "麦辣鸡腿堡套餐,麦乐鸡,全家桶",
"special" => "免费 wifi,外卖服务",
"introduction" => "麦当劳是全球大型跨国连锁餐厅,1940 年创立于美国,在世界上大约拥有 3 万间分店。主要售卖汉堡包,以及薯条、炸鸡、汽水、冰品、沙拉、水果等 快餐食品",
"open_time" => "8:00-20:00",
"avg_price" => 35,
);
$result = $poi->create($info); // true or exception
```
> 注意:新创建的门店在审核通过后,会以事件形式推送给商户填写的回调 URL
## 获取指定门店信息
```php
$poi->get($poiId);
```
- `$poiId` 为门店 ID
example:
```php
$info = $poi->get(271262077);
var_dump($info->business_name); // 麦当劳
var_dump($info->introduction); // 麦当劳是全球大型跨国连锁餐厅...
var_dump($info->toArray());// array('business_name' => '麦当劳', 'branch_name' => '艺苑路店', ...);
```
## 获取门店列表
```php
$poi->lists($begin, $limit);// begin:0, limit:10
```
- `$begin` 就是查询起点,`MySQL` 里的 `offset`;
- `$limit` 查询条数,同 `MySQL` 里的 `limit`;
> 两参数均可选
example:
```php
$pois = $poi->lists(0, 2);// 取2条记录
//
//[
// {
// "sid": "100",
// "poi_id": "271864249",
// "business_name": "麦当劳",
// "branch_name": "艺苑路店",
// "address": "艺苑路 11 号",
// "available_state": 3
// },
// {
// "sid": "101",
// "business_name": "麦当劳",
// "branch_name": "赤岗路店",
// "address": "赤岗路 102 号",
// "available_state": 4
// }
//]
```
## 修改门店信息
商户可以通过该接口,修改门店的服务信息,包括:图片列表、营业时间、推荐、特色服务、简 介、人均价格、电话 7 个字段。目前基础字段包括(名称、坐标、地址等不可修改)。
```php
$poi->update($poiId, $data);
```
- `$poiId` 为门店 ID
- `$data` 需要更新的部分数据,**若有填写内容则为覆盖更新,若无内容则视为不 修改,维持原有内容。photo_list 字段为全列表覆盖,若需要增加图片,需将之前图片同样放入 list 中,在其后增加新增图片。如:已有 A、B、C 三张图片,又要增加 D、E 两张图,则需要调 用该接口,photo_list 传入 A、B、C、D、E 五张图片的链接。**
example:
```php
$data = array(
"telephone" => "020-12345678",
"recommend" => "麦辣鸡腿堡套餐,麦乐鸡,全家桶",
//...
);
$res = $poi->update(271262077, $data); //true or exception
```
## 删除门店
```php
$poi->delete($poiId);
```
example:
```php
$poi->delete(271262077);// true or exception
```
## 错误码
- `invalid categories` 分类不合法,必须严格按照附表的分类填写
- `invalid photo url` 图片 url 不合法,必须使用接口 1 的图片上传 接口所获取的 url
- `poi audit state must be approved` 门店状态必须未审核通过
- `invalid poiid` poi_id 不正确
- `invalid args` 参数不正确,请检查 json 字段
- `system error` 系统错误,请稍后重试
================================================
FILE: docs/src/3.x/qrcode.md
================================================
# 二维码
目前有2种类型的二维码:
1. 临时二维码,是有过期时间的,最长可以设置为在二维码生成后的**30天**后过期,但能够生成较多数量。临时二维码主要用于帐号绑定等不要求二维码永久保存的业务场景
2. 永久二维码,是无过期时间的,但数量较少(目前为最多10万个)。永久二维码主要用于适用于帐号绑定、用户来源统计等场景。
## 获取实例
```php
qrcode;
```
## API
+ `Bag temporary($sceneId, $expireSeconds = null)` 创建临时二维码;
+ `Bag forever($sceneValue)` 创建永久二维码
+ `Bag card(array $card)` 创建卡券二维码
+ `string url($ticket)` 获取二维码网址,用法: `
`;
### 创建临时二维码
```php
$result = $qrcode->temporary(56, 6 * 24 * 3600);
$ticket = $result->ticket;// 或者 $result['ticket']
$expireSeconds = $result->expire_seconds; // 有效秒数
$url = $result->url; // 二维码图片解析后的地址,开发者可根据该地址自行生成需要的二维码图片
```
### 创建永久二维码
```php
$result = $qrcode->forever(56);// 或者 $qrcode->forever("foo");
$ticket = $result->ticket; // 或者 $result['ticket']
$url = $result->url;
```
### 获取二维码网址
```php
$url = $qrcode->url($ticket);
```
### 创建卡券二维码
```php
$qrcode->card($card);
```
### 获取二维码内容
```php
$url = $qrcode->url($ticket);
$content = file_get_contents($url); // 得到二进制图片内容
file_put_contents(__DIR__ . '/code.jpg', $content); // 写入文件
```
================================================
FILE: docs/src/3.x/releases.md
================================================
# 升级日志
## 3.0
- 新的架构
- 重写代码
- 更低的耦合
- 更规范的代码
- 更友好的调试支持
- 更完善的文档
================================================
FILE: docs/src/3.x/reply.md
================================================
# 自动回复
## 获取实例
```php
reply;
```
## 获取当前设置的回复规则
```php
$reply->current();
```
================================================
FILE: docs/src/3.x/roadmap.md
================================================
# 路线图
## 3.1
- 微信小店
- 新的卡券
- 设备管理
## 3.0
- 全新的架构,更清晰的模块拆分
- Debug 优化,便于快速定位问题
- 统一返回微信 API 原值,以 Collection 类装载,便于便捷操作
- 大量模块重写
- 全新的支付模块
- 多类型缓存系统
- 新的命名空间:EasyWeChat
- 专属网站与更清晰与文档:http://easywechat.com
## 2.1
- 新增支付与红包
## 2.0
- 仅问题修复,不再增加新功能;
## 1.0
- 不推荐使用。
- 已停止维护。
================================================
FILE: docs/src/3.x/semantic.md
================================================
# 语义理解
微信开放平台语义理解接口调用(http请求)简单方便,用户无需掌握语义理解及相关技术,只需根据自己的产品特点,选择相应的服务即可搭建一套智能语义服务。
## 获取实例
```php
semantic;
```
## API
+ `query($keyword, $categories, $other)` 语义理解:
+ `$keyword` 为关键字
+ `$categories` 需要使用的服务类型,数组或者多个用 “,” 隔开字符吕,不能为空;
+ `$other` 为其它属性:
+ `latitude` `float` 纬度坐标,与经度同时传入;与城市二选一传入
+ `longitude` `float` 经度坐标,与纬度同时传入;与城市二选一传入
+ `city` `string` 城市名称,与经纬度二选一传入
+ `region` `string` 区域名称,在城市存在的情况下可省;与经纬度二选一传入
+ `uid` `string` 用户唯一id(非开发者id),用户区分公众号下的不同用户(建议填入用户openid),如果为空,则无法使用上下文理解功能。appid和uid同时存在的情况下,才可以使用上下文理解功能。
> 注:单类别意图比较明确,识别的覆盖率比较大,所以如果只要使用特定某个类别,建议将category只设置为该类别。
example:
```php
$result = $semantic->query('查一下明天从北京到上海的南航机票', "flight,hotel", array('city' => '北京', 'uid' => '123456'));
// 查询参数:
// {
// "query":"查一下明天从北京到上海的南航机票",
// "city":"北京",
// "category": "flight,hotel",
// "appid":"wxaaaaaaaaaaaaaaaa",
// "uid":"123456"
// }
```
返回值示例:
```json
{
"errcode":0,
"query":"查一下明天从北京到上海的南航机票",
"type":"flight",
"semantic":{
"details":{
"start_loc":{
"type":"LOC_CITY",
"city":"北京市",
"city_simple":"北京",
"loc_ori":"北京"
},
"end_loc": {
"type":"LOC_CITY",
"city":"上海市",
"city_simple":"上海",
"loc_ori":"上海"
},
"start_date": {
"type":"DT_ORI",
"date":"2014-03-05",
"date_ori":"明天"
},
"airline":"中国南方航空公司"
},
"intent":"SEARCH"
}
```
更多详细内容与协议说明,请查看 [微信官方文档](http://mp.weixin.qq.com/wiki/)
================================================
FILE: docs/src/3.x/server.md
================================================
# 服务端
我们在入门小教程一节以服务端为例讲解了一个基本的消息的处理,这里就不再讲服务器验证的流程了,请直接参考前面的入门实例即可。
服务端的作用呢,在整个微信开发中主要是负责 **[接收用户发送过来的消息](http://mp.weixin.qq.com/wiki/10/79502792eef98d6e0c6e1739da387346.html)**,还有 **[用户触发的一系列事件](http://mp.weixin.qq.com/wiki/2/5baf56ce4947d35003b86a9805634b1e.html)**。
首先我们得厘清一下消息与事件的回复,当你收到用户消息后(消息由微信服务器推送到你的服务器),在你对消息进行一些处理后,不管是选择回复一个消息还是什么不都回给用户,你也应该给微信服务器一个 “答复”,如果是选择回复一条消息,就直接返回一个消息xml就好,如果选择不作任何回复,你也得回复一个空字符串或者字符串 `SUCCESS`(不然用户就会看到 `该公众号暂时无法提供服务`)。
## 基本使用
在 SDK 中呢,使用 `setMessageHandler(callable $callback)` 来设置消息处理函数:
```php
server;
$server->setMessageHandler(function ($message) {
// $message->FromUserName // 用户的 openid
// $message->MsgType // 消息类型:event, text....
return "您好!欢迎关注我!";
});
$response = $server->serve();
$response->send(); // Laravel 里请使用:return $response;
```
这里我们使用 `setMessageHandler` 传入了一个 **闭包([Closure](http://php.net/manual/en/class.closure.php))**,该闭包接收一个参数 `$message` 为消息对象(Collection),这里需要注意的时,与 2.0 不同,2.0 当中我们对消息与事件做了区分,还对消息进行了分类(按 MsgType)。在 3.0 后,**所有的消息包括事件都会使用 `setMessageHandler` 来处理**,也就是说你可能需要在里面进行一些判断,例如:
```php
$server->setMessageHandler(function ($message) {
switch ($message->MsgType) {
case 'event':
return '收到事件消息';
break;
case 'text':
return '收到文字消息';
break;
case 'image':
return '收到图片消息';
break;
case 'voice':
return '收到语音消息';
break;
case 'video':
return '收到视频消息';
break;
case 'location':
return '收到坐标消息';
break;
case 'link':
return '收到链接消息';
break;
// ... 其它消息
default:
return '收到其它消息';
break;
}
// ...
});
```
当然,因为这里 `setMessageHandler` 接收一个 [`callable`](http://php.net/manual/zh/language.types.callable.php) 的参数,所以你不一定要传入一个 Closure 闭包,你可以选择传入一个函数名,一个 `[$class, $method]` 或者 `Foo::bar` 这样的类型。
> :heart: 注意,默认没有验证是否为微信的请求,部署上线建议关掉 debug 模式。
某些情况,我们需要直接使用 `$message` 参数,那么怎么在 `setMessageHandler` 闭包外调用呢?
```php
$message = $server->getMessage();
```
> 注意:`$message` 是一个数组类型的数据,使用的时候这样使用:`$message['ToUserName']`
## 请求消息的属性
当你接收到用户发来的消息时,可能会提取消息中的相关属性,那么请参考:
请求消息基本属性(以下所有消息都有的基本属性):
$message->ToUserName 接收方帐号(该公众号 ID)
$message->FromUserName 发送方帐号(OpenID, 代表用户的唯一标识)
$message->CreateTime 消息创建时间(时间戳)
$message->MsgId 消息 ID(64位整型)
### 文本:
$message->MsgType text
$message->Content 文本消息内容
### 图片:
$message->MsgType image
$message->PicUrl 图片链接
### 语音:
$message->MsgType voice
$message->MediaId 语音消息媒体id,可以调用多媒体文件下载接口拉取数据。
$message->Format 语音格式,如 amr,speex 等
$message->Recognition * 开通语音识别后才有
> 请注意,开通语音识别后,用户每次发送语音给公众号时,微信会在推送的语音消息XML数据包中,增加一个 `Recongnition` 字段
### 视频:
$message->MsgType video
$message->MediaId 视频消息媒体id,可以调用多媒体文件下载接口拉取数据。
$message->ThumbMediaId 视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。
### 小视频:
$message->MsgType shortvideo
$message->MediaId 视频消息媒体id,可以调用多媒体文件下载接口拉取数据。
$message->ThumbMediaId 视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。
### 事件:
$message->MsgType event
$message->Event 事件类型 (如:subscribe(订阅)、unsubscribe(取消订阅) ..., CLICK 等)
# 扫描带参数二维码事件
$message->EventKey 事件KEY值,比如:qrscene_123123,qrscene_为前缀,后面为二维码的参数值
$message->Ticket 二维码的 ticket,可用来换取二维码图片
# 上报地理位置事件
$message->Latitude 23.137466 地理位置纬度
$message->Longitude 113.352425 地理位置经度
$message->Precision 119.385040 地理位置精度
# 自定义菜单事件
$message->EventKey 事件KEY值,与自定义菜单接口中KEY值对应,如:CUSTOM_KEY_001, www.qq.com
### 地理位置:
$message->MsgType location
$message->Location_X 地理位置纬度
$message->Location_Y 地理位置经度
$message->Scale 地图缩放大小
$message->Label 地理位置信息
### 链接:
$message->MsgType link
$message->Title 消息标题
$message->Description 消息描述
$message->Url 消息链接
## 回复消息
回复的消息可以为 `null`,此时 SDK 会返回给微信一个 "SUCCESS",你也可以回复一个普通字符串,比如:`欢迎关注 overtrue.`,此时 SDK 会对它进行一个封装,产生一个 [`EasyWeChat\Message\Text`](https://github.com/EasyWeChat/message/blob/master/src/Text.php) 类型的消息并在最后的 `$server->serve();` 时生成对应的消息 XML 格式。
如果你想返回一个自己手动拼的原生 XML 格式消息,请返回一个 [`EasyWeChat\Message\Raw`](https://github.com/EasyWeChat/message/blob/master/src/Raw.php) 实例即可。
## 消息转发给客服系统
参见:[多客服消息转发](message-transfer.html)
关于消息的使用,请参考 [`消息`](messages.html) 章节。
================================================
FILE: docs/src/3.x/shake-around.md
================================================
# 摇一摇周边
摇一摇周边是微信在线下的全新功能, 为线下商户提供近距离连接用户的能力, 并支持线下商户向周边用户提供个性化营销、互动及信息推荐等服务。
## 获取实例
```php
shakearound;
```
## API
> 特别提醒:
1、下述所有的接口调用的方法参数都要严格按照方法参数前的类型传入相应类型的实参,否则可能会得到非预期的结果。
2、涉及需要传入设备id($deviceIdentifier)的参数时,该参数是一个以 `device_id` 或包含 `uuid` `major` `minor` 为key的关联数组。
3、涉及需要传入设备id列表($deviceIdentifiers)的参数时,该参数是一个二维数组,第一层为索引类型,第二层为关联类型($deviceIdentifier)。
```php
// 参数$deviceIdentifier的实参形式:
['device_id' => 10097]
// 或
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12102,
]
// 参数$deviceIdentifiers的实参形式:
[
['device_id' => 10097],
['device_id' => 10098],
]
// 或
[
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12102,
],
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12103,
]
]
```
### 开通摇一摇周边
> 提示:
若不是做 [公众号第三方平台](https://open.weixin.qq.com/cgi-bin/frame?t=home/wx_plugin_tmpl&lang=zh_CN) 开发,建议直接在微信管理后台申请开通摇一摇周边功能。
#### 申请开通
申请开通摇一摇周边功能。成功提交申请请求后,工作人员会在三个工作日内完成审核。若审核不通过,可以重新提交申请请求。若是审核中,请耐心等待工作人员审核,在审核中状态不能再提交申请请求。
方法
> $shakearound->register(string $name, string $tel, string $email, string $industryId, array $certUrls [, $reason = ''])
参数
> $name 联系人姓名,不超过20汉字或40个英文字母
$tel 联系人电话
$email 联系人邮箱
$industryId 平台定义的行业代号,具体请查看链接 [行业代号](http://3gimg.qq.com/shake_nearby/Qualificationdocuments.html)
$certUrls 相关资质文件的图片url,图片需先上传至微信侧服务器,用“素材管理-上传图片素材”接口上传图片,返回的图片URL再配置在此处;当不需要资质文件时,请传入空数组
$reason 可选,申请理由,不超过250汉字或500个英文字母
> 注意:
1、相关资质文件的图片是使用本页面下方的素材管理的接口上传的,切勿和另一个 [素材管理](material.html) 接口混淆。
2、行业代码请务必传入**字符串**类型的实参,否则以数字0开头的行业代码将会被当成八进制数处理(将转换为十进制数),这可能不是期望的。
示例
```php
$result = $shakearound->register('zhang_san', '13512345678', 'weixin123@qq.com', '0118', [], 'test');
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->data) // 空数组
var_dump($result->errcode) // 0
var_dump($result->errmsg) // success.
```
#### 查询审核状态
查询已经提交的开通摇一摇周边功能申请的审核状态。在申请提交后,工作人员会在三个工作日内完成审核。
方法
> $shakearound->getStatus()
参数
> 无
示例
```php
$result = $shakearound->getStatus();
/* 返回结果
{
"data": {
"apply_time": 1432026025,
"audit_comment": "test",
"audit_status": 1,
"audit_time": 0
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->data['audit_comment']) // test
```
#### 获取摇一摇的设备及用户信息
获取设备信息,包括UUID、major、minor,以及距离、openID等信息。
方法
> $shakearound->getShakeInfo(string $ticket [, int $needPoi = null])
参数
> $ticket 摇周边业务的ticket,可在摇到的URL中得到,ticket生效时间为30分钟,每一次摇都会重新生成新的ticket
$needPoi 可选,是否需要返回门店poi_id,传1则返回,否则不返回
示例
```php
$result = $shakearound->getShakeInfo('6ab3d8465166598a5f4e8c1b44f44645', 1);
/* 返回结果
{
"data": {
"page_id ": 14211,
"beacon_info": {
"distance": 55.00620700469034,
"major": 10001,
"minor": 19007,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
},
"openid": "oVDmXjp7y8aG2AlBuRpMZTb1-cmA",
"poi_id":1234
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->data['page_id']) // 14211
var_dump($result->data['beacon_info']['distance']) // 55.00620700469034
```
### 设备管理
#### 申请设备ID
申请配置设备所需的UUID、Major、Minor。申请成功后返回批次ID,可用返回的批次ID通过“查询设备ID申请状态”接口查询目前申请的审核状态。
一个公众账号最多可申请100000个设备ID,如需申请的设备ID数超过最大限额,请邮件至zhoubian@tencent.com,邮件格式如下:
> 标题:申请提升设备ID额度
内容:
1、公众账号名称及appid(wx开头的字符串,在mp平台可查看)
2、用途
3、预估需要多少设备ID
方法
> $shakearound->device()->apply(int $quantity, string $reason [, string $comment = '' [, int $poiId = null]])
参数
> $quantity 申请的设备ID的数量,单次新增设备超过500个,需走人工审核流程
$reason 申请理由,不超过100个汉字或200个英文字母
$comment 可选,备注,不超过15个汉字或30个英文字母
$poiId 可选,设备关联的门店ID,关联门店后,在门店1KM的范围内有优先摇出信息的机会
示例
```php
$result = $shakearound->device()->apply(3, '测试', '测试专用', 1234);
/* 返回结果
{
"data": {
"apply_id": 123,
"audit_status": 1,
"audit_comment": "审核中"
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->data['apply_id']) // 123
```
#### 查询设备ID申请审核状态
查询设备ID申请的审核状态。若单次申请的设备ID数量小于等于500个,系统会进行快速审核;若单次申请的设备ID数量大于500个,则在三个工作日内完成审核。
方法
> $shakearound->device()->getStatus(int $applyId)
参数
> $applyId 批次ID,申请设备ID时所返回的批次ID
示例
```php
$result = $shakearound->device()->getStatus(123);
/* 返回结果
{
"data": {
"apply_time": 1432026025,
"audit_comment": "test",
"audit_status": 1,
"audit_time": 0
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->data['audit_status']) // 1
```
#### 编辑设备信息
> 仅能修改设备的备注信息。
方法
> $shakearound->device()->update(array $deviceIdentifier, string $comment)
参数
> $deviceIdentifier 设备id,设备编号device_id或UUID、major、minor的关联数组,若二者都填,则以设备编号为优先
$comment 设备的备注信息,不超过15个汉字或30个英文字母
示例
```php
$result = $shakearound->device()->update(['device_id' => 10011], 'test');
// 或
$result = $shakearound->device()->update(['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
], 'test');
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->errcode) // 0
```
#### 配置设备与门店/其他公众账号门店的关联关系
关联本公众账号门店时,支持创建门店后直接关联在设备上,无需为审核通过状态,摇周边后台自动更新门店的最新信息和状态。
关联其他公众账号门店时,支持设备关联其他公众账号的门店,门店需为审核通过状态。
> 因为第三方门店不归属本公众账号,所以未保存到设备详情中,查询设备列表接口与获取摇周边的设备及用户信息接口不会返回第三方门店。
方法
> $shakearound->device()->bindLocation(array $deviceIdentifier, $poiId [, $type = 1 [, $poiAppid = null]])
参数
> $deviceIdentifier 设备id,设备编号device_id或UUID、major、minor的关联数组,若二者都填,则以设备编号为优先
$poiId 设备关联的门店ID,关联门店后,在门店1KM的范围内有优先摇出信息的机会。当值为0时,将清除设备已关联的门店ID
$type 可选,为1时,关联的门店和设备归属于同一公众账号;为2时,关联的门店为其他公众账号的门店
$poiAppid 可选,当$type为1时该参数为必填
示例
```php
// 关联本公众账号门店
$result = $shakearound->device()->bindLocation(['device_id' => 10011], 1231);
// 或
$result = $shakearound->device()->bindLocation(['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
], 1231);
// 关联其他公众账号门店
// wxappid为关联门店所归属的公众账号的APPID
$result = $shakearound->device()->bindLocation(['device_id' => 10011], 1231, 2, 'wxappid');
// 或
$result = $shakearound->device()->bindLocation(['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
], 1231, 2, 'wxappid');
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->errcode) // 0
```
#### 查询设备列表
查询已有的设备ID、UUID、Major、Minor、激活状态、备注信息、关联门店、关联页面等信息。
##### 根据设备id批量取回设备数据
方法
> $shakearound->device()->fetchByIds(array $deviceIdentifiers)
参数
> $deviceIdentifiers 设备id列表
示例
```php
$result = $shakearound->device()->fetchByIds([
['device_id' => 10097],
['device_id' => 10098],
]);
// 或
$result = $shakearound->device()->fetchByIds([
['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12102,],
['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12103,]
]);
/* 返回结果
{
"data": {
"devices": [
{
"comment": "",
"device_id": 10097,
"major": 10001,
"minor": 12102,
"status": 1,
"last_active_time":1437276018,
"poi_id": 0,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
},
{
"comment": "",
"device_id": 10098,
"major": 10001,
"minor": 12103,
"status": 1,
"last_active_time":1437276018,
"poi_appid":"wxe3813f5d8c546fc7"
"poi_id": 123,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
}
],
"total_count": 151
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->data['devices'][0][device_id]) // 10097
var_dump($result->data['total_count']) // 151
```
##### 分页批量取回设备数据
方法
> $shakearound->device()->pagination(int $lastSeen, int $count)
参数
> $lastSeen 前一次查询列表末尾的设备编号device_id,第一次查询last_seen为0
$count 待查询的设备数量,不能超过50个
示例
```php
$result = $shakearound->device()->pagination(10097, 3);
// 返回结果同上
```
##### 根据申请时的批次ID分页批量取回设备数据
方法
> $shakearound->device()->fetchByApplyId(int $applyId, int $lastSeen, int $count)
参数
> $applyId 批次ID,申请设备ID时所返回的批次ID
$lastSeen 前一次查询列表末尾的设备编号device_id,第一次查询lastSeen为0
$count 待查询的设备数量,不能超过50个
示例
```php
$result = $shakearound->device()->fetchByApplyId(1231, 10097, 3);
// 返回结果同上
```
### 页面管理
#### 新增页面
新增摇一摇出来的页面信息,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。其中,图片必须为用素材管理接口上传至微信侧服务器后返回的链接。
> 注意:
图片是使用本页面下方的素材管理的接口上传的,切勿和另一个 [素材管理](material.html) 接口混淆。
方法
> $shakearound->page()->add(string $title, string $description, strig $pageUrl, string $iconUrl [, string $comment = ''])
参数
> $title 在摇一摇页面展示的主标题,不超过6个汉字或12个英文字母
$description 在摇一摇页面展示的副标题,不超过7个汉字或14个英文字母
$pageUrl 点击进去的超链接
$iconUrl 在摇一摇页面展示的图片。图片需先上传至微信侧服务器,用“素材管理-上传图片素材”接口上传图片,返回的图片URL再配置在此处
$comment 可选,页面的备注信息,不超过15个汉字或30个英文字母
示例
```php
$result = $shakearound->page()->add('主标题', '副标题', 'https://zb.weixin.qq.com', 'http://3gimg.qq.com/shake_nearby/dy/icon', 'test');
/* 返回结果
{
"data": {
"page_id": 28840
}
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->data['page_id']) // 28840
```
#### 编辑页面信息
编辑摇一摇出来的页面信息,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。
方法
> $shakearound->page()->update(int $pageId, string $title, string $description, string $pageUrl, string $iconUrl [, string $comment = ''])
参数
> $pageId 摇周边页面唯一ID
$title 在摇一摇页面展示的主标题,不超过6个汉字或12个英文字母
$description 在摇一摇页面展示的副标题,不超过7个汉字或14个英文字母
$pageUrl 点击进去的超链接
$iconUrl 在摇一摇页面展示的图片。图片需先上传至微信侧服务器,用“素材管理-上传图片素材”接口上传图片,返回的图片URL再配置在此处
$comment 可选,页面的备注信息,不超过15个汉字或30个英文字母
示例
```php
$result = $shakearound->page()->add(28840, '主标题', '副标题', 'https://zb.weixin.qq.com', 'http://3gimg.qq.com/shake_nearby/dy/icon', 'test');
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->errcode) // 0
```
#### 查询页面列表
查询已有的页面,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。
##### 根据页面id批量取回页面数据
方法
> $shakearound->page()->fetchByIds(array $pageIds)
参数
> $pageIds 页面的id列表,索引数组
示例
```php
$result = $shakearound->page()->fetchByIds([28840, 28842]);
/* 返回结果
{
"data": {
"pages": [
{
"comment": "just for test",
"description": "test",
"icon_url": "https://www.baidu.com/img/bd_logo1",
"page_id": 28840,
"page_url": "http://xw.qq.com/testapi1",
"title": "测试1"
},
{
"comment": "just for test",
"description": "test",
"icon_url": "https://www.baidu.com/img/bd_logo1",
"page_id": 28842,
"page_url": "http://xw.qq.com/testapi2",
"title": "测试2"
}
],
"total_count": 2
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->data['pages'][0]['title']) // 测试1
var_dump($result->data['total_count']) // 2
```
##### 分页批量取回页面数据
方法
> $shakearound->page()->pagination(int $begin, int $count)
参数
> $begin 页面列表的起始索引值
$count 待查询的页面数量,不能超过50个
示例
```php
$result = $shakearound->page()->pagination(0,2);
// 返回结果同上
```
#### 删除页面
删除已有的页面,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。
> 注意:
只有页面与设备没有关联关系时,才可被删除。
方法
> $shakearound->page()->delete(int $pageId)
参数
> $pageId 页面的id
示例
```php
$result = $shakearound->page()->delete(34567);
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->errcode) // 0
```
### 素材管理
上传在摇一摇功能中需使用到的图片素材,素材保存在微信侧服务器上。图片格式限定为:jpg,jpeg,png,gif。
若图片为在摇一摇页面展示的图片,则其素材为 `icon` 类型的图片,图片大小建议 `120px*120 px` ,限制不超过 `200 px *200 px` ,图片需为 `正方形` 。
若图片为申请开通摇一摇周边功能需要上传的资质文件图片,则其素材为 `license` 类型的图片,图片的文件大小不超过 `2MB` ,尺寸不限,形状不限。
方法
> $shakearound->material()->uploadImage(string $path [, string $type = 'icon'])
参数
> $path 图片所在路径
$type 可选,值为icon或license
示例
```php
$result = $shakearound->material()->uploadImage(__DIR__ . '/stubs/image.jpg');
/* 返回结果
{
"data": {
"pic_url": http://shp.qpic.cn/wechat_shakearound_pic/0/1428377032e9dd2797018cad79186e03e8c5aec8dc/120"
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->data['pic_url']) // http://shp.qpic.cn/wechat_shakearound_pic/0/1428377032e9dd2797018cad79186e03e8c5aec8dc/120
```
### 管理设备与页面的关系
通过接口申请的设备ID,需先配置页面,若未配置页面,则摇不出页面信息。
#### 配置设备与页面的关联关系
配置完成后,在此设备的信号范围内,即可摇出关联的页面信息。
若设备配置多个页面,则随机出现页面信息。一个设备最多可配置30个关联页面。
> 注意:
1、配置时传入该设备需要关联的页面的id列表,该设备原有的关联关系将被直接清除。
2、页面的id列表允许为空(**传入空数组**),当页面的id列表为空时则会清除该设备的所有关联关系。
方法
> $shakearound->relation()->bindPage(array $deviceIdentifier, array $pageIds)
参数
> $deviceIdentifier 设备id,设备编号device_id或UUID、major、minor的关联数组,若二者都填,则以设备编号为优先
$pageIds 页面的id列表,索引数组
示例
```php
$result = $shakearound->relation()->bindPage(['device_id' => 10011], [12345, 23456, 334567]);
// 或
$result = $shakearound->relation()->bindPage(['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
], [12345, 23456, 334567]);
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->errcode) // 0
```
#### 查询设备与页面的关联关系
##### 查询指定设备所关联的页面
根据设备ID或完整的UUID、Major、Minor查询该设备所关联的所有页面信息
方法
> $shakearound->relation()->getPageByDeviceId(array $deviceIdentifier [, boolean $raw = false])
> 注意:
该方法默认对返回的数据进行处理后返回一个包含页面id的索引数组。若要返回和 `getDeviceByPageId` 方法类似的数据,请传入 `true` 作为第二个参数。
参数
> $deviceIdentifier 设备id,设备编号device_id或UUID、major、minor的关联数组,若二者都填,则以设备编号为优先
$raw 可选,当为true时,返回值和getDeviceByPageId方法类似,否则返回页面的id列表(索引数组,无关联时为空数组)
示例
```php
$result = $shakearound->relation()->getPageByDeviceId(['device_id' => 10011]);
// 或
$result = $shakearound->relation()->getPageByDeviceId(['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
]);
// 返回结果
var_dump($result) // [50054,50055]
```
##### 查询指定页面所关联的设备
指定页面ID分页查询该页面所关联的所有的设备信息
方法
> $shakearound->relation()->getDeviceByPageId(int $pageId, int $begin, int $count)
参数
> $pageId 指定的页面id
$begin 关联关系列表的起始索引值
$count 待查询的关联关系数量,不能超过50个
示例
```php
$result = $shakearound->relation()->getDeviceByPageId(50054, 0, 3);
/* 返回结果
{
"data": {
"relations": [
{
"device_id": 797994,
"major": 10001,
"minor": 10023,
"page_id": 50054,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
},
{
"device_id": 797995,
"major": 10001,
"minor": 10024,
"page_id": 50054,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
}
],
"total_count": 2
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->data['relations'][0]['device_id']) // 797994
var_dump($result->data['total_count']) // 2
```
### 摇一摇数据统计
> 此接口无法获取当天的数据,最早只能获取前一天的数据。
由于系统在凌晨处理前一天的数据,太早调用此接口可能获取不到数据,建议在早上8:00之后调用此接口。
#### 以设备为维度的数据统计
查询单个设备进行摇周边操作的人数、次数,点击摇周边消息的人数、次数。
> 注意:
查询的最长时间跨度为30天。只能查询最近90天的数据。
方法
> $shakearound->stats()->deviceSummary(array $deviceIdentifier, int $beginDate, int $endDate)
参数
> $deviceIdentifier 设备id,设备编号device_id或UUID、major、minor的关联数组,若二者都填,则以设备编号为优先
$beginDate 起始日期时间戳,最长时间跨度为30天,单位为秒
$endDate 结束日期时间戳,最长时间跨度为30天,单位为秒
示例
```php
$result = $shakearound->stats()->deviceSummary(['device_id' => 10011], 1425052800, 1425139200);
// 或
$result = $shakearound->stats()->deviceSummary(['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
], 1425052800, 1425139200);
/* 返回结果
{
"data": [
{
"click_pv": 0,
"click_uv": 0,
"ftime": 1425052800,
"shake_pv": 0,
"shake_uv": 0
},
{
"click_pv": 0,
"click_uv": 0,
"ftime": 1425139200,
"shake_pv": 0,
"shake_uv": 0
}
],
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->data[0]['ftime']) // 1425052800
```
#### 批量查询设备统计数据
查询指定时间商家帐号下的每个设备进行摇周边操作的人数、次数,点击摇周边消息的人数、次数。
> 只能查询最近90天内的数据,且一次只能查询一天。
> 注意:
对于摇周边人数、摇周边次数、点击摇周边消息的人数、点击摇周边消息的次数都为0的设备,不在结果列表中返回。
方法
> $shakearound->stats()->batchDeviceSummary(int $timestamp, int $pageIndex)
参数
> $timestamp 指定查询日期时间戳,单位为秒
$pageIndex 指定查询的结果页序号,返回结果按摇周边人数降序排序,每50条记录为一页
示例
```php
$result = $shakearound->stats()->batchDeviceSummary(1435075200, 1);
/* 返回结果
{
"data": {
"devices": [
{
"device_id": 10097,
"major": 10001,
"minor": 12102,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
"shake_pv": 1
"shake_uv": 2
"click_pv": 3
"click_uv": 4
},
{
"device_id": 10098,
"major": 10001,
"minor": 12103,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
"shake_pv": 1
"shake_uv": 2
"click_pv": 3
"click_uv": 4
}
],
},
"date":1435075200
"total_count": 151
"page_index":1
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->data['devices'][0]['device_id']) // 10097
var_dump($result->total_count) // 151
```
#### 以页面为维度的数据统计
查询单个页面通过摇周边摇出来的人数、次数,点击摇周边页面的人数、次数
> 注意:
查询的最长时间跨度为30天。只能查询最近90天的数据。
方法
> $shakearound->stats()->pageSummary(int $pageId, int $beginDate, int $endDate);
参数
> $pageId 指定页面的页面ID
$beginDate 起始日期时间戳,最长时间跨度为30天,单位为秒
$endDate 结束日期时间戳,最长时间跨度为30天,单位为秒
示例
```php
$result = $shakearound->stats()->pageSummary(12345, 1425052800, 1425139200);
/* 返回结果
{
"data": [
{
"click_pv": 0,
"click_uv": 0,
"ftime": 1425052800,
"shake_pv": 0,
"shake_uv": 0
},
{
"click_pv": 0,
"click_uv": 0,
"ftime": 1425139200,
"shake_pv": 0,
"shake_uv": 0
}
],
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->data[1]['ftime']) // 1425139200
```
#### 批量查询页面统计数据
查询指定时间商家帐号下的每个页面进行摇周边操作的人数、次数,点击摇周边消息的人数、次数。
> 注意:
对于摇周边人数、摇周边次数、点击摇周边消息的人数、点击摇周边消息的次数都为0的页面,不在结果列表中返回。
方法
> $shakearound->stats()->batchPageSummary(int $timestamp, int $pageIndex);
参数
> $timestamp 指定查询日期时间戳,单位为秒
$pageIndex 指定查询的结果页序号,返回结果按摇周边人数降序排序,每50条记录为一页
示例
```php
$result = $shakearound->stats()->batchPageSummary(1435075200, 1);
/* 返回结果
{
"data": {
"pages": [
{
"page_id":1234
"click_pv": 1,
"click_uv": 3,
"shake_pv": 0,
"shake_uv": 0
},
{
"page_id":5678
"click_pv": 1,
"click_uv": 2,
"shake_pv": 0,
"shake_uv": 0
},
],
},
"date":1435075200
"total_count": 151
"page_index":1
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->data['pages'][0]['click_uv']) // 3
var_dump($result->total_count) // 151
```
### 设备分组管理
调用H5页面获取设备信息 JS API接口,需要先把设备分组,微信客户端只会返回已在分组中的设备信息。
#### 新增分组
新建设备分组,每个帐号下最多只有1000个分组。
方法
> $shakearound->group()->add(string $name)
参数
> $name 分组名称,不超过100汉字或200个英文字母
示例
```php
$result = $shakearound->group()->add('test');
/* 返回结果
{
"data": {
"group_id" : 123,
"group_name" : "test"
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->data['group_id']) // 123
var_dump($result->data['group_name']) // test
```
#### 编辑分组信息
编辑设备分组信息,目前只能修改分组名。
方法
> $shakearound->group()->update(int $groupId, string $name)
参数
> $groupId 分组唯一标识,全局唯一
$name 分组名称,不超过100汉字或200个英文字母
示例
```php
$result = $shakearound->group()->update(123, 'newName');
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->errcode) // 0
```
#### 删除分组
删除设备分组,若分组中还存在设备,则不能删除成功。需把设备移除以后,才能删除。
> 在执行删除前,最好先使用 `getDetails` 方法查询分组详情,若分组内有设备,先使用 `removeDevice` 方法移除。
方法
> $shakearound->group()->delete(int $groupId)
参数
> $groupId 分组唯一标识,全局唯一
示例
```php
$result = $shakearound->group()->delete(123);
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->errcode) // 0
```
#### 查询分组列表
查询账号下所有的分组。
方法
> $shakearound->group()->lists(int $begin, int $count)
参数
> $begin 分组列表的起始索引值
$count 待查询的分组数量,不能超过1000个
示例
```php
$result = $shakearound->group()->lists(0, 2);
/* 返回结果
{
"data": {
"groups":[
{
"group_id" : 123,
"group_name" : "test1"
},
{
"group_id" : 124,
"group_name" : "test2"
}
],
"total_count": 100
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->data['groups'][1]['group_name']) // test2
var_dump($result->data['total_count']) // 100
```
#### 查询分组详情
查询分组详情,包括分组名,分组id,分组里的设备列表。
方法
> $shakearound->group()->getDetails(int $groupId, int $begin, int $count)
参数
> $groupId 分组唯一标识,全局唯一
$begin 分组里设备的起始索引值
$count 待查询的分组里设备的数量,不能超过1000个
示例
```php
$result = $shakearound->group()->getDetails(123, 0, 2);
/* 返回结果
{
"data": {
"group_id" : 123,
"group_name" : "test",
"total_count": 100,
"devices" :[
{
"device_id" : 123456,
"uuid" : "FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
"major" : 10001,
"minor" : 10001,
"comment" : "test device1",
"poi_id" : 12345,
},
{
"device_id" : 123457,
"uuid" : "FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
"major" : 10001,
"minor" : 10002,
"comment" : "test device2",
"poi_id" : 12345,
}
]
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->data['devices'][0]['comment']) // test device1
var_dump($result->data['total_count']) // 100
```
#### 添加设备到分组
添加设备到分组,每个分组能够持有的设备上限为10000,并且每次添加操作的添加上限为1000。
> 只有在摇周边申请的设备才能添加到分组。
方法
> $shakearound->group()->addDevice(int $groupId, array $deviceIdentifiers)
参数
> $groupId 分组唯一标识,全局唯一
$deviceIdentifiers 设备id列表
示例
```php
$result = $shakearound->group()->addDevice(123, [
['device_id' => 10097],
['device_id' => 10098],
]);
// 或
$result = $shakearound->group()->addDevice(123, [
['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12102,],
['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12103,]
]);
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->errcode) // 0
```
#### 从分组中移除设备
从分组中移除设备,每次删除操作的上限为1000。
方法
> $shakearound->group()->removeDevice(int $groupId, array $deviceIdentifiers)
参数
> $groupId 分组唯一标识,全局唯一
$deviceIdentifiers 设备id列表
示例
```php
$result = $shakearound->group()->removeDevice(123, [
['device_id' => 10097],
['device_id' => 10098],
]);
// 或
$result = $shakearound->group()->removeDevice(123, [
['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12102,],
['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12103,]
]);
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->errcode) // 0
```
### 摇一摇红包
微信官方目前暂停了摇红包接口,该接口可能会有所调整,故而暂时不提供该接口的封装。
> 官方公告详情请至: [关于摇红包接口暂停的公告](https://zb.weixin.qq.com/nearby/announce.xhtml?announceId=10047)
### 摇一摇事件通知
用户进入摇一摇界面,在“周边”页卡下摇一摇时,微信会把这个事件推送到开发者填写的URL(登录公众平台进入开发者中心设置)。推送内容包含摇一摇时“周边”页卡展示出来的页面所对应的设备信息,以及附近最多五个属于该公众账号的设备的信息。当摇出列表时,此事件不推送。
> 摇一摇事件的事件类型:ShakearoundUserShake
关于事件的处理请移步: [事件](events.html)
### 摇一摇周边错误码
> 摇周边错误码请移步: [错误码](https://mp.weixin.qq.com/wiki?action=doc&id=mp1443448163&t=0.17525333335674986)
有关摇一摇周边接口信息的更多细节请参考微信官方文档相应条目: [微信官方文档](http://mp.weixin.qq.com/wiki/)
================================================
FILE: docs/src/3.x/short-url.md
================================================
# 短网址服务
主要使用场景: 开发者用于生成二维码的原链接(商品、支付二维码等)太长导致扫码速度和成功率下降,将原长链接通过此接口转成短链接再生成二维码将大大提升扫码速度和成功率。
## 获取实例
```php
url;
```
## API
+ `shorten($url)` 长链接转短链接
example:
```php
$shortUrl = $url->shorten('http://overtrue.me/open-source');
//
```
微信官方文档:http://mp.weixin.qq.com/wiki/
================================================
FILE: docs/src/3.x/sidebar.js
================================================
exports = module.exports = [
{
text: '开始使用',
items: [
{ text: '概述', link: '/3.x/overview.html' },
{ text: '安装', link: '/3.x/installation.html' },
{ text: '小教程', link: '/3.x/tutorial.html' },
{ text: '配置', link: '/3.x/configuration.html' },
{ text: '在框架中使用', link: '/3.x/integration.html' },
{ text: '常见问题汇总', link: '/3.x/troubleshooting.html' }
]
},
{
text: '基本使用',
items: [
{ text: '服务端', link: '/3.x/server.html' },
{ text: '消息', link: '/3.x/messages.html' },
{ text: '多客服消息转发', link: '/3.x/message-transfer.html' },
{ text: '事件', link: '/3.x/events.html' },
{ text: '群发消息', link: '/3.x/broadcast.html' },
{ text: '模板消息', link: '/3.x/notice.html' },
{ text: '用户', link: '/3.x/user.html' },
{ text: '用户标签', link: '/3.x/user-tag.html' },
{ text: '用户组', link: '/3.x/user-group.html' },
{ text: '网页授权', link: '/3.x/oauth.html' },
{ text: '素材管理', link: '/3.x/material.html' },
{ text: '菜单', link: '/3.x/menu.html' },
{ text: 'JSSDK', link: '/3.x/js.html' },
{ text: '支付', link: '/3.x/payment.html' },
{ text: '企业支付', link: '/3.x/merchant_payment.html' },
{ text: '红包', link: '/3.x/lucky-money.html' },
{ text: '卡券', link: '/3.x/card.html' },
{ text: '小店', link: '/3.x/store.html' },
{ text: '门店', link: '/3.x/poi.html' },
{ text: '客服', link: '/3.x/staff.html' },
{ text: '数据统计与分析', link: '/3.x/anaylsis.html' },
{ text: '二维码', link: '/3.x/qrcode.html' },
{ text: '短网址', link: '/3.x/short-url.html' },
{ text: '小程序', link: '/3.x/mini_program.html' },
{ text: '语义理解', link: '/3.x/semantic.html' },
{ text: '自动回复', link: '/3.x/reply.html' },
{ text: '开放平台', link: '/3.x/open_platform.html' }
]
},
{
text: '自定义',
items: [
{ text: 'Access Token', link: '/3.x/access_token.html' },
{ text: '缓存', link: '/3.x/cache.html' }
]
},
{
text: '其他',
items: [
{ text: '问题解答', link: '/3.x/troubleshooting.html' },
{ text: '贡献', link: '/3.x/contributing.html' },
{ text: '更新日志', link: '/3.x/releases.html' },
{ text: '路线图', link: '/3.x/roadmap.html' }
]
}
]
================================================
FILE: docs/src/3.x/staff.md
================================================
# 客服
> 2016.06.28 已经更新为新版多客服 API
> 请更新到 3.1 版本: composer require "overtrue/wechat:~3.1"
微信的客服才能发送消息或者群发消息,而且还有时效限制,真恶心的说。。。
## 客服管理
```php
staff; // 客服管理
```
## API
### 获取所有客服账号列表
```php
$staff->lists();
```
### 获取所有在线的客服账号列表
```php
$staff->onlines();
```
### 添加客服帐号
```php
$staff->create('foo@test', '客服1');
```
### 修改客服帐号
```php
$staff->update('foo@test', '客服1');
```
### 删除客服帐号
```php
$staff->delete('foo@test');
```
### 设置客服帐号的头像
```php
$staff->avatar('foo@test', $avatarPath); // $avatarPath 为本地图片路径,非 URL
```
### 获取客服聊天记录 `NEW`
```php
$staff->records($startTime, $endTime, $pageIndex, $pageSize);
// example: $records = $staff->records('2015-06-07', '2015-06-21', 1, 20);
```
### 主动发送消息给用户
```php
$staff->message($message)->to($openId)->send();
```
> `$message` 为消息对象,请参考:[消息](messages.html)
### 指定客服发送消息
```php
$staff->message($message)->by('account@test')->to($openId)->send();
```
> `$message` 为消息对象,请参考:[消息](messages.html)
## 客服会话控制
> 客服会话为新版 API 功能
```php
staff_session; // 客服会话管理
```
## 创建会话
```php
$session->create('test1@test', 'OPENID');
```
### 关闭会话
```php
$session->close('test1@test', 'OPENID');
```
### 获取客户会话状态
```php
$session->get('OPENID');
```
### 获取客服会话列表
```php
$session->lists('test1@test');
```
### 获取未接入会话列表
```php
$session->waiters();
```
关于更多客服接口信息请参考微信官方文档:http://mp.weixin.qq.com/wiki
================================================
FILE: docs/src/3.x/store.md
================================================
# 门店
TODO
================================================
FILE: docs/src/3.x/troubleshooting.md
================================================
# 疑难解答
在微信公众平台开发的道路上,遍布着各种大大小小的坑,有的人掉坑里,几经折腾又爬出来了,然后拍拍屁股走人。然而坑还在那里,还会继续有后来人掉进去……
这,是我们不愿看到的。
所以在这里,我们将陆续将微信开发中可能遇到的各种疑难问题进行汇总,并给出对应的解决办法。一般情况下,这些问题都可以对号入座,轻松地解决。但也不排除特殊情况,这时候你遇到的问题与文中某一个症状一致,但文中所给的解决方案并不凑效,这种情况下就需要发挥你自己的智慧,去……折腾了……
我们期待这一版块为各位的开发带来便利,同时也希望各位本着开源、分享的精神对其进行补充和完善,将各种坑一一填小、填平,让微信开发变得不那么痛苦,甚至,变成一件快乐的事……
# 一些服务器基本设施问题:
- 时区不对, 使用命令 `date` 可以在服务器上查看当前时间,如果发现时区不对则需要修改时区:[Setting The Correct Timezone In CentOS And Ubuntu Servers With NTP](https://www.liberiangeek.net/2013/02/setting-the-correct-timezone-in-centos-and-ubuntu-servers-with-ntp/)
- ...
## curl: (60) SSL certificate problem: unable to get local issuer certificate
这是 SSL 证书问题所致,在使用 SDK 调用微信支付等相关的操作时可能会遇到报 “SSL certificate problem: unable to get local issuer certificate” 的错误。
微信公众平台提供的文档中建议对部分较敏感的操作接口使用 https 协议进行访问,例如微信支付和红包等接口中涉及到操作商户资金的一些操作。
wechat SDK 遵循了官方建议,所以在调用这些接口时,除了按照官方文档设置操作证书文件外,还需要保证服务器正确安装了 CA 证书。
1. 下载 CA 证书
你可以从 http://curl.haxx.se/ca/cacert.pem 下载 或者 使用[微信官方提供的证书](https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=4_3)中的 CA 证书 `rootca.pem` 也是同样的效果。
2. 在 `php.ini` 中配置 CA 证书
只需要将上面下载好的 CA 证书放置到您的服务器上某个位置,然后修改 `php.ini` 的 `curl.cainfo` 为该路径(**绝对路径!**),重启 `php-fpm` 服务即可。
```
curl.cainfo = /path/to/downloaded/cacert.pem
```
> 注意证书文件**路径为绝对路径**!以自己实际情况为准。
其它修改 HTTP 类源文件的方式是不允许的。
## cURL error 56: SSLRead() return error -9806
目前在 OSX 下,发现使用 HomeBrew 装的 PHP 7.0 有这个问题,解决方案是重新 brew 安装 PHP:
```shell
$ brew install homebrew/php/php70 --with-homebrew-openssl --with-homebrew-curl --without-snmp -vvv
```
验证:
```shell
$ php -i | grep 'OpenSSL support'
OpenSSL support => enabled
OpenSSL support => enabled
```
## 支付失败!当前页面的 URL 未注册
这是由于微信支付授权目录未正确配置引起的。此时开发者应该登录微信公众平台,进入**【微信支付】->【开发设置】**进行设置。
1. 公众号可添加3个支付授权目录,满足不同应用使用同一个公众号进行支付的业务需求。
2. 正确的**【支付授权目录】**应以 `http://` 或 `https://` 开头,并以正斜杠 `/` 结尾,授权目录所包含的域名**必须经过 ICP 备案**。
3. 支付授权目录需**细化至二级或三级目录**。
4. 所有**实际调起微信支付请求的页面都必须要所配置的支付授权目录之下**。
5. 在开发过程中,也可以使用测试授权目录进行开发测试,此时还**应该将参与测试的个人微信号添加到测试白名单中**,否则将出现对应的错误提示……
> 配置前请先理解**页面**、**目录**、**URL **以及**域名**等几个基本概念,并对自己所使用的框架的路由机制有一个大致了解。这样你才会知道自己正在配置的参数是个啥玩意儿,有什么卵用…… :smile:
## redirect_url 参数错误
这是由于程序使用了**网页授权**而公众号没有正确配置**【网页授权域名】**所致。此时你需要登录[微信公众平台](https://mp.weixin.qq.com/),在【开发】->【接口权限】页面找到**网页授权获取用户基本信息**进行配置并保存。
1. 网页授权域名应该为通过 ICP 备案的有效域名,否则保存时无法通过安全监测。
2. 网页授权域名即程序完成授权获得授权 code 后跳转到的页面的域名,一般情况下为你的业务域名。
3. 网页授权域名配置成功后会立即生效。
4. 公众号的网页授权域名只可配置一个,请合理规划你的业务,否则你会发现……授权域名不够用哈。
## [JSAPI] config: invalid url domain
在使用 JS-SDK 进行开发时,每个页面都需要调用 wx.config() 方法配置 JSPAI 参数。如果没有正确配置 **JSAPI 安全域名**并且开启了调试模式,此时就报此错误。遇到这个问题时,开发者需要登录微信公众平台,进入【公众号设置】->【功能设置】页面,将项目所使用的域名添加至 **【JSAPI 安全域名】**列表中。
1. 一个公众号同时最多可绑定**三个**安全域名,并且这些域名必须为通过 **ICP 备案**的**一级或一级以上**的有效域名。
2. JSAPI 安全域名每个月**限修改三次**,修改任何一个都算,所以,请谨慎操作。
3. 如果需要使用 JSAPI 调起支付功能,则支付目录必须也在所配置的**安全域名之下**,并且需要将支付目录添加至**支付授权目录**。
## token验证失败、向公众号发送消息无任何反应
相信对接公众号一般是微信开发者进行开发过程中最先进行的工作,而在这看似简单的配置操作中,也可能会掉坑里。
最常见的两种情况就如下:
1. 确认你 “**启用**” 了开发模式, token 验证通过不代表启用,保存后也不代表启用。看到红色 “**停用**” 才真正的是启用了。
2. 配置好URL(服务器地址)以及Token(令牌)后,点击保存时提示**token验证失败**,出现这种情况的原因有多种,其中之一便是网络不稳定,所以**可尝试多次保存**,若始终无法通过再排查其它可能因素。
3. 配置保存成功之后,向公众号发送消息无任何反应,自己的消息处理程序也没有被调用的记录(无对应日志)。这种情况下如果你尝试**反复停用和启用服务器配置**,可能突然间惊奇地了现,问题莫名其妙的解决了。
4. 使用在线调试工具的消息接口,http://mp.weixin.qq.com/debug/, 只要返回绿色的“**请求成功**”,就代表你的代码没有问题,请**重复上面第3项**再测试。
5. **如果你在用什么本地开发工具,或者什么 ngrok 代理到本机这样的开发方式,那么失败就很正常了,微信服务器到你机器的网络延迟太大(还是用服务器开发吧)。**
> 请开发者理解服务器 TOKEN 验证原理(官方文档有说明)并谨记服务器验证时使用 GET 方式访问,而公众平台向你的服务器发送消息/数据则使用 POST 方式,所以服务器验证成功之后,在某些启用了 CSRF 验证的框架里,接收消息时可能还会遇到 CSRF 相关的问题,请根据自己项目实际情况进行排查。
> 另外有的朋友的 Laravel 里使用了 laravel-debugbar,这个组件的原理是在页面输出时在后面添加 HTML 来实现的,所以它会改变我们返回给微信的内容,此时要么卸载,要么禁用掉它。
## Maximum function nesting level of '100' reached, aborting!
在使用了 Xdebug 的环境下可能出现这个问题。这是由于 Xdebug 限制函数嵌套的最大层级数(默认为100),当嵌套次数达到该值便会触发 Xdebug 跳出嵌套并报此错误。
为避免这个问题,**可以将 Xdebug 的 max_nesting_level 参数适当设置大一些**,通常设置为200就可以了(当然可根据自己实际情况设置为更大的值)。
如下,修改 php.ini 配置文件后,重启 Apache 或 php-fpm 服务即可。
```
xdebug.max_nesting_level=200
```
================================================
FILE: docs/src/3.x/tutorial.md
================================================
# 快速开始
在我们已经安装完成后,即可很快的开始使用它了,当然你还是有必要明白 PHP 基本知识,如命名空间等,我这里就不赘述了。
我们以完成服务器端验证与接收响应用户发送的消息为例来演示,首先你有必要了解一下微信交互的运行流程:
```
+-----------------+ +---------------+
+----------+ | | POST/GET/PUT | |
| | ------------------> | | -------------------> | |
| user | | wechat server | | your server |
| | < - - - - - - - - - | | | |
+----------+ | | <- - - - - - - - - - | |
+-----------------+ +---------------+
```
那么我们要做的就是图中 **微信服务器把用户消息转到我们的自有服务器(虚线返回部分)** 后的处理过程。
## 服务端验证
在微信接入开始有一个 “服务器验证” 的过程,这一步呢,其实就是微信服务器向我们服务器发起一个请求(上图实线部分),传了一个名称为 `echostr` 的字符串过来,我们只需要原样返回就好了。
你也知道,微信后台只能填写一个服务器地址,所以 **服务器验证** 与 **消息的接收与回复**,都在这一个链接内完成交互。
考虑到这些,我已经把验证这一步给封装到 SDK 里了,你可以完全忽略这一步。
下面我们来配置一个基本的服务端,这里假设我们自己的服务器域名叫 `easywechat.com`,我们在服务器上准备这么一个文件`server.php`:
// server.php
```php
true,
'app_id' => 'your-app-id',
'secret' => 'you-secret',
'token' => 'easywechat',
// 'aes_key' => null, // 可选
'log' => [
'level' => 'debug',
'file' => '/tmp/easywechat.log', // XXX: 绝对路径!!!!
],
//...
];
$app = new Application($options);
$response = $app->server->serve();
// 将响应输出
$response->send(); // Laravel 里请使用:return $response;
```
> :heart: 安全模式下请一定要填写 `aes_key`
一个服务端带验证功能的代码已经完成,当然没有对消息做处理,别着急,后面我们再讲。
我们先来分析上面的代码:
```php
server->serve();
// 将响应输出
$response->send(); // Laravel 里请使用:return $response;
```
最后这一行我有必要详细讲一下:
> 1. 我们的 `$app->server->serve()` 就是执行服务端业务了,那么它的返回值呢,是一个 `Symfony\Component\HttpFoundation\Response` 实例。
> 2. 我这里是直接调用了它的 `send()` 方法,它就是直接输出了,我们在一些框架就不能直接输出了,那你就直接拿到 Response 实例后做相应的操作即可,比如 Laravel 里你就可以直接 `return $app->server->serve();`
OK, 有了上面的代码,那么请你按 **[微信官方的接入指引](http://mp.weixin.qq.com/wiki/17/2d4265491f12608cd170a95559800f2d.html)** 操作,并相应修改上面的 `$options` 的配置。
> URL 就是我们的 `http://easywechat.com/server.php`,这里我是举例哦,你可不要填写我的域名。
这样,点击提交验证就 OK 了。
> :heart: 请一定要将微信后台的开发者模式 “**启用**” !!!!!!看到红色 “**停用**” 才真正的是启用了。
## 接收 & 回复用户消息
那服务端验证通过了,我们就来试一下接收消息吧。
> 在刚刚上面代码最后一行 `$app->server->serve()->send();` 前面,我们调用 `$app->server` 的 `setMessageHandler()` 方法来注册一个消息处理函数,这里用到了 **[PHP 闭包](http://php.net/manual/zh/functions.anonymous.php)** 的知识,如果你不熟悉赶紧补课去。
```php
// ...
$server->setMessageHandler(function ($message) {
return "您好!欢迎关注我!";
});
$response = $app->server->serve();
// 将响应输出
$response->send(); // Laravel 里请使用:return $response;
```
> 注意:send() 方法里已经包含 echo 了,请不要再加 echo 在前面。
好吧,打开你的微信客户端,向你的公众号发送任意一条消息,你应该会收到回复:`您好!欢迎关注我!`。
> 没有收到回复?看到了“你的公众号暂时无法提供服务” ?, 好,那检查一下你的日志吧,日志在哪儿?我们的配置里写了日志路径了(`'/tmp/easywechat.log'`)。 没有这个文件?看看权限哦。
一个基本的服务端验证就完成了。
## 总结
1. 所有的服务都通过主入口 `EasyWeChat\Foundation\Application` 类来获取:
```php
$app = new Application($options);
// services...
$server = $app->server;
$user = $app->user;
$oauth = $app->oauth;
// ... js/menu/staff/material/qrcode/notice/stats...
```
2. 所有的 API 返回值均为 [`EasyWeChat\Support\Collection`](https://github.com/EasyWeChat/support/blob/master/src/Collection.php) 类,这个类是个什么东西呢?
它实现了一些 **[PHP 预定义接口](http://php.net/manual/zh/reserved.interfaces.php)**,比如:[`ArrayAccess`](http://php.net/manual/zh/class.arrayaccess.php)、[`Serializable`](http://php.net/manual/zh/class.serializable.php) 等。
有啥好处呢?它让我们操作起返回值来更方便,比如:
```php
$userService = $app->user; // 用户API
$user = $userService->get($openId);
// $user 便是一个 EasyWeChat\Support\Collection 实例
$user['nickname'];
$user->nickname;
$user->get('nickname');
//...
```
还有这些方便的操作:检查是否存在某个属性 `$user->has('email')`、元素个数 `$user->count()`,还有返回数组 `$user->toArray()` ,生成 JSON `$user->toJSON()` 等。
## 最后
希望你在使用本 SDK 的时候能忘记微信官方给你的痛苦,同时如果你发现 SDK 的不足,欢迎提交 PR 或者给我[提建议 & 报告问题](https://github.com/overtrue/wechat/issues)。
祝你生活愉快!
================================================
FILE: docs/src/3.x/user-group.md
================================================
# 用户组
用户组的使用就非常简单了,基本的增删改查。
## 获取实例
```php
user_group; // $user['user_group']
```
## API
### 获取所有分组
```php
$group->lists();
```
example:
```php
$groups = $group->lists();
// {
// "groups": [
// {
// "id": 0,
// "name": "未分组",
// "count": 72596
// },
// {
// "id": 1,
// "name": "黑名单",
// "count": 36
// },
// ...
// ]
// }
var_dump($groups->groups[0]['name']) // “未分组”
```
### 创建分组
```php
$group->create($name);
```
example:
```php
$group->create($name);
```
### 修改分组信息
```php
$group->update($groupId, $name);
```
example:
```php
$group->update($groupId, "新的组名");
```
### 删除分组
```php
$group->delete($groupId);
```
example:
```php
$group->delete($groupId);
```
### 移动单个用户到指定分组
```php
$group->moveUser($openId, $groupId);
```
example:
```php
$group->moveUser($openId, $groupId);
```
### 批量移动用户到指定分组
```php
$group->moveUsers(array $openIds, $groupId);
```
example:
```php
$openIds = [$openId1, $openId2, $openId3 ...];
$group->moveUsers($openIds, $groupId);
```
关于用户管理请参考微信官方文档:http://mp.weixin.qq.com/wiki/ `用户管理` 章节。
================================================
FILE: docs/src/3.x/user-tag.md
================================================
# 用户标签
用户标签的使用就非常简单了,基本的增删改查。
## 获取实例
```php
user_tag; // $user['user_tag']
```
## API
### 获取所有标签
```php
$tag->lists();
```
example:
```php
$tags = $tag->lists();
// {
// "tags": [
// {
// "id": 0,
// "name": "标签1",
// "count": 72596
// },
// {
// "id": 1,
// "name": "标签2",
// "count": 36
// },
// ...
// ]
// }
var_dump($tags->tags[0]['name']) // “标签1”
```
### 创建标签
```php
$tag->create($name);
```
example:
```php
$tag->create('测试标签');
```
### 修改标签信息
```php
$tag->update($tagId, $name);
```
example:
```php
$tag->update(12, "新的名称");
```
### 删除标签
```php
$tag->delete($tagId);
```
example:
```php
$tag->delete($tagId);
```
### 获取指定 openid 用户身上的标签
```php
$userTags = $tag->userTags($openId);
//
// {
// "tagid_list":["标签1","标签2"]
// }
```
### 获取标签下粉丝列表
```php
$tag->usersOfTag($tagId, $nextOpenId = '');
// $nextOpenId:第一个拉取的OPENID,不填默认从头开始拉取
// {
// "count":2,//这次获取的粉丝数量
// "data":{//粉丝列表
// "openid":[
// "ocYxcuAEy30bX0NXmGn4ypqx3tI0",
// "ocYxcuBt0mRugKZ7tGAHPnUaOW7Y"
// ]
// },
// "next_openid":"ocYxcuBt0mRugKZ7tGAHPnUaOW7Y"//拉取列表最后一个用户的openid
// }
```
### 批量为用户打标签
```php
$openIds = [$openId1, $openId2, ...];
$tag->batchTagUsers($openIds, $tagId);
```
### 批量为用户取消标签
```php
$openIds = [$openId1, $openId2, ...];
$tag->batchUntagUsers($openIds, $tagId);
```
关于用户管理请参考微信官方文档:http://mp.weixin.qq.com/wiki/ `用户管理` 章节。
================================================
FILE: docs/src/3.x/user.md
================================================
# 用户
用户信息的获取是微信开发中比较常用的一个功能了,以下所有的用户信息的获取与更新,都是**基于微信的 `openid` 的,并且是已关注当前账号的**,其它情况可能无法正常使用。
## 获取实例
```php
user;
```
## API 列表
### 获取用户信息
```php
$userService->get($openId);
$userService->batchGet($openIds);
```
获取单个:
```php
$user = $userService->get($openId);
echo $user->nickname; // or $user['nickname']
```
获取多个:
```php
$users = $userService->batchGet([$openId1, $openId2, ...]);
```
### 获取用户列表
```php
$userService->lists($nextOpenId = null); // $nextOpenId 可选
```
example:
```php
$users = $userService->lists();
// result
{
"total": 2,
"count": 2,
"data": {
"openid": [
"",
"OPENID1",
"OPENID2"
]
},
"next_openid": "NEXT_OPENID"
}
$users->total; // 2
```
### 修改用户备注
```php
$userService->remark($openId, $remark); // 成功返回boolean
```
example:
```php
$userService->remark($openId, "僵尸粉");
```
### 获取用户所属用户组ID
```php
$userService->group($openId);
```
example:
```php
$userGroupId = $userService->group($openId);
```
## 其它
- [用户标签](user-tag.html)
- [用户分组](user-group.html)
关于用户管理请参考微信官方文档:http://mp.weixin.qq.com/wiki/ `用户管理` 章节。
================================================
FILE: docs/src/4.x/basic-services/content_security.md
================================================
# 内容安全接口
## 文本安全内容检测
用于校验一段文本是否含有违法内容。
### 频率限制
单个appid调用上限为2000次/分钟,1,000,000次/天
### 调用示例
```php
// 传入要检测的文本内容,长度不超过500K字节
$content = '你好';
$result = $app->content_security->checkText($content);
// 正常返回 0
{
"errcode": "0",
"errmsg": "ok"
}
//当 $content 内含有敏感信息,则返回 87014
{
"errcode": 87014,
"errmsg": "risky content"
}
```
## 图片安全内容检测
用于校验一张图片是否含有敏感信息。如涉黄、涉及敏感人脸(通常是政治人物)。
### 频率限制
单个appid调用上限为1000次/分钟,100,000次/天
### 调用示例
```php
// 所传参数为要检测的图片文件的绝对路径,图片格式支持PNG、JPEG、JPG、GIF, 像素不超过 750 x 1334,同时文件大小以不超过 300K 为宜,否则可能报错
$result = $app->content_security->checkImage('/path/to/the/image');
// 正常返回 0
{
"errcode": "0",
"errmsg": "ok"
}
// 当图片文件内含有敏感内容,则返回 87014
{
"errcode": 87014,
"errmsg": "risky content"
}
```
## 重要说明
目前上述两个接口仅支持在小程序中使用,示例中的 `$app` 表示小程序实例,即:
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'wx3cf0f39249eb0exx',
'secret' => 'f1c242f4f28f735d4687abb469072axx',
// 下面为可选项
// 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
'response_type' => 'array',
'log' => [
'level' => 'debug',
'file' => __DIR__.'/wechat.log',
],
];
$app = Factory::miniProgram($config);
```
================================================
FILE: docs/src/4.x/basic-services/jssdk.md
================================================
# JSSDK
微信 JSSDK 官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
## API
#### 获取JSSDK的配置数组
```php
$app->jssdk->buildConfig(array $APIs, $debug = false, $beta = false, $json = true);
```
默认返回 JSON 字符串,当 `$json` 为 `false` 时返回数组,你可以直接使用到网页中。
#### 设置当前URL
```php
$app->jssdk->setUrl($url)
```
如果不想用默认读取的URL,可以使用此方法手动设置,通常不需要。
#### 示例
我们可以生成js配置文件:
```js
```
结果如下:
```js
```
================================================
FILE: docs/src/4.x/basic-services/media.md
================================================
# 临时素材
上传的临时多媒体文件有格式和大小限制,如下:
> - 图片(image): 2M,支持 `JPG` 格式
> - 语音(voice):2M,播放长度不超过 `60s`,支持 `AMR\MP3` 格式
> - 视频(video):10MB,支持 `MP4` 格式
> - 缩略图(thumb):64KB,支持 `JPG` 格式
## 上传图片
> 注意:微信图片上传服务有敏感检测系统,图片内容如果含有敏感内容,如色情,商品推广,虚假信息等,上传可能失败。
```php
$app->media->uploadImage($path);
```
## 上传声音
```php
$app->media->uploadVoice($path);
```
## 上传视频
```php
$app->media->uploadVideo($path, $title, $description);
```
## 上传缩略图
用于视频封面或者音乐封面。
```php
$app->media->uploadThumb($path);
```
## 上传群发视频
上传视频获取 `media_id` 用以创建群发消息用。
```php
$app->media->uploadVideoForBroadcasting($path, $title, $description);
//{
// "media_id": "rF4UdIMfYK3efUfyoddYRMU50zMiRmmt_l0kszupYh_SzrcW5Gaheq05p_lHuOTQ",
// "title": "TITLE",
// "description": "Description"
//}
```
## 创建群发消息
不要与上面 **上传群发视频** 搞混了,上面一个是上传视频得到 `media_id`,这个是使用该 `media_id` 加标题描述 **创建一条消息素材** 用来发送给用户。详情参见:[消息群发](../official-account/broadcasting.md)
```php
$app->media->createVideoForBroadcasting($mediaId, $title, $description);
//{
// "type":"video",
// "media_id":"IhdaAQXuvJtGzwwc0abfXnzeezfO0NgPK6AQYShD8RQYMTtfzbLdBIQkQziv2XJc",
// "created_at":1398848981
//}
```
## 获取临时素材内容
比如图片、语音等二进制流内容,响应为 `EasyWeChat\Kernel\Http\StreamResponse` 实例。
```php
$stream = $app->media->get($mediaId);
if ($stream instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
// 以内容 md5 为文件名存到本地
$stream->save('保存目录');
// 自定义文件名,不需要带后缀
$stream->saveAs('保存目录', '文件名');
}
```
## 获取 JSSDK 上传的高清语音
```php
$stream = $app->media->getJssdkMedia($mediaId);
$stream->saveAs('保存目录', 'custom-name.speex');
```
================================================
FILE: docs/src/4.x/basic-services/qrcode.md
================================================
# 二维码
目前有 2 种类型的二维码:
1. 临时二维码,是有过期时间的,最长可以设置为在二维码生成后的 **30天**后过期,但能够生成较多数量。临时二维码主要用于帐号绑定等不要求二维码永久保存的业务场景
2. 永久二维码,是无过期时间的,但数量较少(目前为最多10万个)。永久二维码主要用于适用于帐号绑定、用户来源统计等场景。
## 创建临时二维码
```php
$result = $app->qrcode->temporary('foo', 6 * 24 * 3600);
// Array
// (
// [ticket] => gQFD8TwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyTmFjVTRWU3ViUE8xR1N4ajFwMWsAAgS2uItZAwQA6QcA
// [expire_seconds] => 518400
// [url] => http://weixin.qq.com/q/02NacU4VSubPO1GSxj1p1k
// )
```
## 创建永久二维码
```php
$result = $app->qrcode->forever(56);// 或者 $app->qrcode->forever("foo");
// Array
// (
// [ticket] => gQFD8TwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyTmFjVTRWU3ViUE8xR1N4ajFwMWsAAgS2uItZAwQA6QcA
// [url] => http://weixin.qq.com/q/02NacU4VSubPO1GSxj1p1k
// )
```
## 获取二维码网址
```php
$url = $app->qrcode->url($ticket);
// https://api.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET
```
## 获取二维码内容
```php
$url = $app->qrcode->url($ticket);
$content = file_get_contents($url); // 得到二进制图片内容
file_put_contents(__DIR__ . '/code.jpg', $content); // 写入文件
```
================================================
FILE: docs/src/4.x/basic-services/url.md
================================================
# 短网址服务
主要使用场景: 开发者用于生成二维码的原链接(商品、支付二维码等)太长导致扫码速度和成功率下降,将原长链接通过此接口转成短链接再生成二维码将大大提升扫码速度和成功率。
## 长链接转短链接
```php
$shortUrl = $app->url->shorten('https://easywechat.com');
//
(
[errcode] => 0
[errmsg] => ok
[short_url] => https://w.url.cn/s/Aq7jWrd
)
```
================================================
FILE: docs/src/4.x/client.md
================================================
# API 调用
该方法将 API 交由开发者自行调用,微信有部分新的接口4.x并未全部兼容支持,可以使用该方案去自行封装接口:
例如URL Link接口
```php
$response = $app->httpPostJson('wxa/generate_urllink',[
'path' => 'pages/index/index',
'is_expire' => true,
'expire_type' => 1,
'expire_interval' => 1
]);
```
## 语法说明
```php
httpGet(string $uri, array $query = [])
httpPostJson(string $uri, array $data = [], array $query = [])
```
### GET
```php
$response = $app->httpGet('/cgi-bin/user/list', [
'next_openid' => 'OPENID1',
]);
```
### POST
```php
$response = $app->httpPostJson('/cgi-bin/user/info/updateremark', [
"openid" => "oDF3iY9ffA-hqb2vVvbr7qxf6A0Q",
"remark" => "pangzi"
]);
```
================================================
FILE: docs/src/4.x/contributing.md
================================================
# 贡献代码
## 开发
我们欢迎广大开发者贡献大家的智慧,让我们共同让它变得更完美.
### 开始之前
请严格遵循以下代码标准:
> - [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md).
> - 使用 4 个空格作为缩进。
### 流程
1. Fork [overtrue/wechat](https://github.com/overtrue/wechat) 到本地.
2. 创建新的分支:
```shell
$ git checkout -b new_feature
```
3. 编写代码。
4. Push 到你的分支:
```shell
$ git push origin new_feature
```
5. 创建 Pull Request 并描述你完成的功能或者做出的修改。
> 注意:注释请使用英文
## 更新文档
我们的文档也是开源的,源代码在 [w7corp/EasyWeChat/docs](https://github.com/w7corp/easywechat/tree/master/docs)。
### 流程
1. Fork [w7corp/EasyWeChat](https://github.com/w7corp/easywechat)
2. Clone 到你的电脑:
```shell
$ git clone https://github.com//site.git
$ cd docs
```
3. 创建新的分支,编辑文档
4. Push 到你的分支。
5. 创建 Pull Request 并描述你完成的功能或者做出的修改。
## 报告 Bug
当你在使用过程中遇到问题,请查阅 [疑难解答](troubleshooting.html) 或者在这里提问 [GitHub](https://github.com/overtrue/wechat/issues). 如果还是不能解决你的问题,请到 GitHub 联系我们。
[overtrue/wechat]: https://github.com/overtrue/wechat
================================================
FILE: docs/src/4.x/customize/access_token.md
================================================
# Access Token
我们一个 SDK 应用在初始化以后,你可以在任何时机从应用中拿到该配置下的 Access Token 实例:
```php
use EasyWeChat\Factory;
$config = [
//...
];
$app = Factory::officialAccount($config);
// 获取 access token 实例
$accessToken = $app->access_token;
$token = $accessToken->getToken(); // token 数组 token['access_token'] 字符串
$token = $accessToken->getToken(true); // 强制重新从微信服务器获取 token.
```
## 修改 `$app` 的 Access Token
```php
$app['access_token']->setToken($newAccessToken, 7200);
```
例如:
```php
$app['access_token']->setToken('ccfdec35bd7ba359f6101c2da321d675');
// 或者指定过期时间
$app['access_token']->setToken('ccfdec35bd7ba359f6101c2da321d675', 3600); // 单位:秒
```
================================================
FILE: docs/src/4.x/customize/cache.md
================================================
# 缓存
本项目使用 [symfony/cache](https://github.com/symfony/cache) 来完成缓存工作,它支持基本目前所有的缓存引擎。
在我们的 SDK 中的所有缓存默认使用文件缓存,缓存路径取决于 PHP 的临时目录,如果你需要自定义缓存,那么你需要做如下的事情:
你可以参考[symfony/cache官方文档](https://symfony.com/doc/current/components/cache.html) 来替换掉应用中默认的缓存配置:
## 以 redis 为例
### Symfony 4.3 +
> 请先安装 redis 拓展:`composer require predis/predis`
```php
use Symfony\Component\Cache\Adapter\RedisAdapter;
// 创建 redis 实例
$client = new \Predis\Client('tcp://10.0.0.1:6379');
// 创建缓存实例
$cache = new RedisAdapter($client);
// 替换应用中的缓存
$app->rebind('cache', $cache);
```
### Symfony 3.4 +
> 请先安装 redis 拓展:https://github.com/phpredis/phpredis
```php
use Symfony\Component\Cache\Simple\RedisCache;
// 创建 redis 实例
$redis = new Redis();
$redis->connect('redis_host', 6379);
// 创建缓存实例
$cache = new RedisCache($redis);
// 替换应用中的缓存
$app->rebind('cache', $cache);
```
### Laravel 中使用
在 Laravel 中框架使用 [predis/predis](https://github.com/nrk/predis):
### Symfony 4.3 +
> 请先安装 redis 拓展:`composer require predis/predis`
```php
use Symfony\Component\Cache\Adapter\RedisAdapter;
// 创建缓存实例
$cache = new RedisAdapter(app('redis')->connection()->client());
$app->rebind('cache', $cache);
```
### Symfony 3.4 +
```php
use Symfony\Component\Cache\Simple\RedisCache;
$predis = app('redis')->connection()->client(); // connection($name), $name 默认为 `default`
$cache = new RedisCache($predis);
$app->rebind('cache', $cache);
```
> 上面提到的 `app('redis')->connection($name)`, 这里的 `$name` 是 laravel 项目中配置文件 `database.php` 中 `redis` 配置名 `default`:https://github.com/laravel/laravel/blob/master/config/database.php#L118
> 如果你使用的其它连接,对应传名称就好了。
## 使用自定义的缓存方式
如果你发现 symfony 提供的十几种缓存方式都满足不了你的需求的话,那么你可以自己建立一个类来完成缓存操作,前提这个类得实现接口:[PSR-16](http://www.php-fig.org/psr/psr-16/)
该接口有以下方法需要实现:
```php
public function get($key, $default = null);
public function set($key, $value, $ttl = null);
public function delete($key);
public function clear();
public function getMultiple($keys, $default = null);
public function setMultiple($values, $ttl = null);
public function deleteMultiple($keys);
public function has($key);
```
下面为一个示例:
```php
rebind('cache', new MyCustomCache());
```
OK,这样就完成了自定义缓存的操作。
================================================
FILE: docs/src/4.x/customize/replace-service.md
================================================
# 自定义服务模块
由于使用了容器模式来组织各模块的实例,意味着你可以比较容易的替换掉已经有的服务,以公众号服务为例:
```php
<...>
$app = Factory::officialAccount($config);
$app->rebind('request', new MyCustomRequest(...));
```
这里的 `request` 为 SDK 内部服务名称。
================================================
FILE: docs/src/4.x/index.md
================================================
> 👋🏼 您当前浏览的文档为 4.x,其它版本的文档请参考:[6.x](/6.x/)、[5.x](/5.x/)、[3.x](/3.x/)
# EasyWeChat
EasyWeChat 是一个开源的 [微信](http://www.wechat.com) 非官方 SDK。安装非常简单,因为它是一个标准的 [Composer](https://getcomposer.org/) 包,这意味着任何满足下列安装条件的 PHP 项目支持 Composer 都可以使用它。
## 环境要求
> - PHP >= 7.0
> - [PHP cURL 扩展](http://php.net/manual/en/book.curl.php)
> - [PHP OpenSSL 扩展](http://php.net/manual/en/book.openssl.php)
> - [PHP SimpleXML 扩展](http://php.net/manual/en/book.simplexml.php)
> - [PHP fileinfo 拓展](http://php.net/manual/en/book.fileinfo.php)
Laravel 5 拓展包: [overtrue/laravel-wechat](https://github.com/overtrue/laravel-wechat)
# 参与贡献
1. fork 当前库到你的名下
2. 选择你想要修改的语言版本,`zh-CN` 或者 `en`
3. 在你的本地修改完成审阅过后提交到你的仓库
4. 提交 PR 并描述你的修改,等待合并
# License
MIT
================================================
FILE: docs/src/4.x/installation.md
================================================
# 安装
## 环境要求
> - PHP >= 7.0
> - [PHP cURL 扩展](http://php.net/manual/en/book.curl.php)
> - [PHP OpenSSL 扩展](http://php.net/manual/en/book.openssl.php)
> - [PHP SimpleXML 扩展](http://php.net/manual/en/book.simplexml.php)
> - [PHP fileinfo 拓展](http://php.net/manual/en/book.fileinfo.php)
Laravel 5 拓展包: [overtrue/laravel-wechat](https://github.com/overtrue/laravel-wechat)
## 安装
使用 [composer](http://getcomposer.org/):
```shell
$ composer require overtrue/wechat:~4.0 -vvv
```
================================================
FILE: docs/src/4.x/integration.md
================================================
# 在框架中使用
EasyWeChat 是一个通用的 Composer 包,所以不需要对框架单独做修改,只要支持 Composer 就能直接使用,当然了,为了更方便的使用,我们收集了以下框架单独提供的拓展包:
## Laravel
> - [overtrue/laravel-wechat](https://github.com/overtrue/laravel-wechat)
## Symfony
> - [lilocon/WechatBundle](https://github.com/lilocon/WechatBundle)
## Yii
> - [jianyan74/yii2-easy-wechat](https://github.com/jianyan74/yii2-easy-wechat) 适用于 EasyWeChat 4.x
> - [max-wen/yii2-easy-wechat](https://github.com/max-wen/yii2-easy-wechat) 适用于 EasyWeChat 3.x
## ThinkPHP
> - [naixiaoxin/think-wechat](https://github.com/qiqizjl/think-wechat) 适用于 EasyWeChat 4.x
> - [zyan/think-wechat](https://github.com/aa24615/think-wechat) 适用于 EasyWeChat 4.x/5.x
## CI
TODO
## Phalcon
TODO
... more
================================================
FILE: docs/src/4.x/micro-merchant/certficates.md
================================================
# 获取平台证书
调用获取平台证书接口之前,请前往微信支付商户平台升级API证书,升级后才可成功调用本接口。
```php
// 获取到证书后可以做缓存处理,无需每次重新获取
$response = $app->certficates->get(bool $returnRaw = false);
// 获取到平台证书后,可以直接使用 setCertificate 方法把证书配置追加到配置项里面去
$app->setCertificate(string $certificate, string $serialNo);
```
> $returnRaw 不填默认为false时,请确保你的PHP已安装了sodium扩展
> 返回值:固定array格式的解密后的证书信息
> $returnRaw 传入true时
> 返回值:Response对象`$response->getBody()->getContents();`获取到微信返回xml原始数据
================================================
FILE: docs/src/4.x/micro-merchant/index.md
================================================
# 小微商户
你在阅读本文之前确认你已经仔细阅读了:[微信小微商户专属接口文档](https://pay.weixin.qq.com/wiki/doc/api/xiaowei.php?chapter=19_2)。
PS: ⚠️ 因系统升级,腾讯暂时关闭了小微商户接口,恢复时间未定。调用提交申请接口会提示「PARAM_ERROR」,详细说明可参见[微信开放平台相关帖子](https://developers.weixin.qq.com/community/develop/doc/0000a0ffc9ce28bd4bc9999ba5b800)
## 配置
小微商户整体接口调用方式相对于其他微信接口略有不同,配置时请勿填错,相关配置如下:
```php
use EasyWeChat\Factory;
$config = [
// 必要配置
'mch_id' => 'your-mch-id', // 服务商的商户号
'key' => 'key-for-signature', // API 密钥
'apiv3_key' => 'APIv3-key-for-signature', // APIv3 密钥
// API 证书路径(登录商户平台下载 API 证书)
'cert_path' => 'path/to/your/cert.pem', // XXX: 绝对路径!!!!
'key_path' => 'path/to/your/key', // XXX: 绝对路径!!!!
// 以下两项配置在获取证书接口时可为空,在调用入驻接口前请先调用获取证书接口获取以下两项配置,如果获取过证书可以直接在这里配置,也可参照本文档获取平台证书章节中示例
// 'serial_no' => '获取证书接口获取到的平台证书序列号',
// 'certificate' => '获取证书接口获取到的证书内容'
// 以下为可选项
// 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
'response_type' => 'array'
'appid' => 'wx931386123456789e' // 服务商的公众账号 ID
];
$app = Factory::microMerchant($config);
```
`$app` 在所有相关小微商户的文档都是指 `Factory::microMerchant` 得到的实例,就不在每个页面单独写了。
## 使用时值得注意的地方:
1、小微商户所有接口中以下列出参数 `version`, `mch_id`, `nonce_str`, `sign`, `sign_type`, `cert_sn` 可不用传入。
2、所有敏感信息无需手动加密,sdk会在调用接口前自动完成加密
3、在调用入驻等需要敏感信息加密的接口前请先调用获取证书接口然后把配置填入配置项
4、入驻成功获取到子商户号后需帮助子商户调用配置修改等接口可以先调用以下方法,方便调用修改等接口时无需再次传入子商户号
```php
// $subMchId 为子商户号
// $appid 服务商的公众账号 ID
$app->setSubMchId(string $subMchId, string $appId = '');
```
================================================
FILE: docs/src/4.x/micro-merchant/material.md
================================================
# 商户信息修改
## 修改结算银行卡
```php
$response = $app->material->setSettlementCard([
// 'sub_mch_id' => '1230000109',
'account_number' => '银行卡号',
'bank_name' => '开户银行全称(含支行)',
'account_bank' => '开户银行',
'bank_address_code' => '开户银行省市编码',
]);
```
## 修改联系信息
```php
$response = $app->material->updateContact([
// 'sub_mch_id' => '1230000109',
'mobile_phone' => '手机号',
'email' => '邮箱',
'merchant_name' => '商户简称',
]);
```
> 以上接口调用过 `setSubMchId` 方法则无需传入 `sub_mch_id` 参数
================================================
FILE: docs/src/4.x/micro-merchant/media.md
================================================
# 图片上传
上传证件照片。支持 jpeg、jpg、bmp、png 格式,图片大小不超过2M。
```php
// $path string 图片路径
$response = $app->media->upload($path);
```
================================================
FILE: docs/src/4.x/micro-merchant/merchant-config.md
================================================
# 小微商户配置
## 关注功能配置
```php
$response = $app->merchantConfig->setFollowConfig(string $subAppId, string $subscribeAppId, string $receiptAppId = '', string $subMchId = '');
```
> 注意:`subscribe_appid`,`receipt_appid` 两个参数二选一,两个都填的话SDK默认选第一个,具体请参考小微商户专属文档
## 开发配置新增支付目录
```php
$response = $app->merchantConfig->addPath(string $jsapiPath, string $appId = '', string $subMchId = '');
```
## 新增对应APPID关联
```php
$response = $app->merchantConfig->bindAppId(string $subAppId, string $appId = '', string $subMchId = '');
```
## 开发配置查询
```php
$response = $app->merchantConfig->getConfig(string $subMchId = '', string $appId = '');
```
> 以上接口调用过 `setSubMchId` 方法并且两个参数都传入过 则无需传入 `sub_mch_id` 和 `appid` 参数
================================================
FILE: docs/src/4.x/micro-merchant/submit-application.md
================================================
# 商户入驻
## 申请入驻
使用申请入驻接口提交你的小微商户资料。
```php
$result = $app->submitApplication([
'business_code' => '123456', // 业务申请编号
'id_card_copy' => 'media_id', // 身份证人像面照片
// ...
// 参数太多就不一一列出,自行根据 (小微商户专属文档 -> 申请入驻api) 填写
]);
```
## 查询申请状态
使用申请入驻接口提交小微商户资料后,一般5分钟左右可以通过该查询接口查询具体的申请结果。
```php
$applymentId = '商户申请单号(applyment_id 申请入驻接口返回)';
$businessCode = '业务申请编号(business_code)';
$app->getStatus(string $applymentId, string $businessCode = '');
```
> 商户申请单号和业务申请编号填写一个就行了,当 `applyment_id` 已填写时,`business_code` 字段无效。
当查询申请状态为待签约,接口会一并返回签约二维码,服务商需引导商户使用本人微信扫码完成协议签署。
================================================
FILE: docs/src/4.x/micro-merchant/upgrade.md
================================================
# 商户升级
## 提交升级申请单
使用“提交升级申请单”接口为小微商户发起升级流程,根据商户实际情况可升级为个体户、企业、党政、机关及事业单位、其他组织。。
```php
$result = $app->upgrade([
'organization_type' => '2', // 主体类型
'business_license_copy' => 'media_id', // 营业执照扫描件
// ...
// 参数太多就不一一列出,自行根据 (小微商户专属文档 -> 提交升级申请单API) 填写
]);
```
## 查询升级申请单状态
使用“提交升级申请单”接口后,可不定期调用此接口查询申请单状态(建议提交申请后1分钟查询),直至申请单为“完成”状态。
1)若申请状态为待账户验证,请按接口中的指引完成账户验证
2)若申请状态为审核中,微信支付会在2个工作日内完成资料审核
3)若申请状态为待签约,接口会返回签约二维码
```php
$app->getUpgradeStatus(string $subMchId = '');
```
> 调用该接口前调用过 `setSubMchId` 方法则无需传入 `$subMchId` 参数
================================================
FILE: docs/src/4.x/micro-merchant/withdraw.md
================================================
# 提现相关
## 查询提现状态
```php
$response = $app->withdraw->queryWithdrawalStatus($date, $subMchId = '');
```
## 重新发起提现
```php
$response = $app->withdraw->requestWithdraw($date, $subMchId = '');
```
> 以上接口调用过 `setSubMchId` 方法则无需传入 `sub_mch_id` 参数
================================================
FILE: docs/src/4.x/mini-program/app_code.md
================================================
# 小程序码
## 获取小程序码
### 接口A: 适用于需要的码数量较少的业务场景
API:
```
$app->app_code->get(string $path, array $optional = []);
```
其中 `$optional` 为以下可选参数:
> - **width** Int - 默认 430 二维码的宽度
> - **auto_color** 默认 false 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调
> - **line_color** 数组,`auto_color` 为 `false` 时生效,使用 rgb 设置颜色 例如 ,示例:`["r" => 0,"g" => 0,"b" => 0]`。
示例代码:
```php
$response = $app->app_code->get('path/to/page');
// 或者
$response = $app->app_code->get('path/to/page', [
'width' => 600,
//...
]);
// 或者指定颜色
$response = $app->app_code->get('path/to/page', [
'width' => 600,
'line_color' => [
'r' => 105,
'g' => 166,
'b' => 134,
],
]);
// $response 成功时为 EasyWeChat\Kernel\Http\StreamResponse 实例,失败时为数组或者你指定的 API 返回格式
// 保存小程序码到文件
if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
$filename = $response->save('/path/to/directory');
}
// 或
if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
$filename = $response->saveAs('/path/to/directory', 'appcode.png');
}
```
### 接口B:适用于需要的码数量极多,或仅临时使用的业务场景
API:
```
$app->app_code->getUnlimit(string $scene, array $optional = []);
```
> 其中 $scene 必填,$optinal 与 get 方法一致,多一个 page 参数。
示例代码:
```php
$response = $app->app_code->getUnlimit('scene-value', [
'page' => 'path/to/page',
'width' => 600,
]);
// $response 成功时为 EasyWeChat\Kernel\Http\StreamResponse 实例,失败为数组或你指定的 API 返回类型
// 保存小程序码到文件
if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
$filename = $response->save('/path/to/directory');
}
// 或
if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
$filename = $response->saveAs('/path/to/directory', 'appcode.png');
}
```
## 获取小程序二维码
API:
```
$app->app_code->getQrCode(string $path, int $width = null);
```
> 其中 $path 必填,其余参数可留空。
示例代码:
```php
$response = $app->app_code->getQrCode('/path/to/page');
// $response 成功时为 EasyWeChat\Kernel\Http\StreamResponse 实例,失败为数组或你指定的 API 返回类型
// 保存小程序码到文件
if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
$filename = $response->save('/path/to/directory');
}
// 或
if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
$filename = $response->saveAs('/path/to/directory', 'appcode.png');
}
```
##
================================================
FILE: docs/src/4.x/mini-program/auth.md
================================================
# 微信登录
## 根据 jsCode 获取用户 session 信息
API:
```php
$app->auth->session(string $code);
```
================================================
FILE: docs/src/4.x/mini-program/customer_service.md
================================================
# 客服消息
## 获取实例
```php
$service = $app->customer_service;
```
> 使用方法详看公众号-客服消息章节。
================================================
FILE: docs/src/4.x/mini-program/data_cube.md
================================================
# 数据统计与分析
获取小程序概况趋势:
```php
$app->data_cube->summaryTrend('20170313', '20170313')
```
开始日期与结束日期的格式为 yyyymmdd。
## API
> - `summaryTrend(string $from, string $to);` 概况趋势
> - `dailyVisitTrend(string $from, string $to);` 访问日趋势
> - `weeklyVisitTrend(string $from, string $to);` 访问周趋势
> - `monthlyVisitTrend(string $from, string $to);` 访问月趋势
> - `visitDistribution(string $from, string $to);` 访问分布
> - `dailyRetainInfo(string $from, string $to);` 访问日留存
> - `weeklyRetainInfo(string $from, string $to);` 访问周留存
> - `monthlyRetainInfo(string $from, string $to);` 访问月留存
> - `visitPage(string $from, string $to);` 访问页面
> - `userPortrait(string $from, string $to);` 用户画像分布数据
================================================
FILE: docs/src/4.x/mini-program/decrypt.md
================================================
# 微信小程序消息解密
## 比如获取电话等功能,信息是加密的,需要解密。
API:
```php
$decryptedData = $app->encryptor->decryptData($session, $iv, $encryptedData);
```
================================================
FILE: docs/src/4.x/mini-program/express.md
================================================
# 物流助手 电子面单
## 获取支持的快递公司列表
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/express/by-business/logistics.getAllDelivery.html
```php
$app->express->listProviders();
{
"count": 8,
"data": [
{
"delivery_id": "BEST",
"delivery_name": "百世快递"
},
...
]
}
```
## 生成运单
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/express/by-business/logistics.addOrder.html
```php
$app->express->createWaybill($data);
// 成功返回
{
"order_id": "01234567890123456789",
"waybill_id": "123456789",
"waybill_data": [
{
"key": "SF_bagAddr",
"value": "广州"
},
{
"key": "SF_mark",
"value": "101- 07-03 509"
}
]
}
// 失败返回
{
"errcode": 9300501,
"errmsg": "delivery logic fail",
"delivery_resultcode": 10002,
"delivery_resultmsg": "客户密码不正确"
}
```
## 取消运单
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/express/by-business/logistics.cancelOrder.html
```php
$app->express->deleteWaybill($data);
```
## 获取运单数据
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/express/by-business/logistics.getOrder.html
```php
$app->express->getWaybill($data);
```
## 查询运单轨迹
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/express/by-business/logistics.getPath.html
```php
$app->express->getWaybillTrack($data);
```
## 获取电子面单余额。
仅在使用加盟类快递公司时,才可以调用。
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/express/by-business/logistics.getQuota.html
```php
$app->express->getBalance($deliveryId, $bizId);
// 例如:
$app->express->getBalance('YTO', 'xyz');
```
## 绑定打印员
若需要使用微信打单 PC 软件,才需要调用。
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/express/by-business/logistics.updatePrinter.html
```php
$app->express->bindPrinter($openid);
```
## 解绑打印员
若需要使用微信打单 PC 软件,才需要调用。
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/express/by-business/logistics.updatePrinter.html
```php
$app->express->unbindPrinter($openid);
```
================================================
FILE: docs/src/4.x/mini-program/index.md
================================================
# 小程序
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'wx3cf0f39249eb0exx',
'secret' => 'f1c242f4f28f735d4687abb469072axx',
// 下面为可选项
// 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
'response_type' => 'array',
'log' => [
'level' => 'debug',
'file' => __DIR__.'/wechat.log',
],
];
$app = Factory::miniProgram($config);
```
`$app` 在所有相关小程序的文档都是指 `Factory::miniProgram` 得到的实例,就不在每个页面单独写了。
================================================
FILE: docs/src/4.x/mini-program/nearby_poi.md
================================================
# 附近的小程序
> 微信文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/nearby-poi/nearbyPoi.add.html
## 添加地点
```php
$params = [
'kf_info' => '{"open_kf":true,"kf_headimg":"http://mmbiz.qpic.cn/mmbiz_jpg/kKMgNtnEfQzDKpLXYhgo3W3Gndl34gITqmP914zSwhajIEJzUPpx40P7R8fRe1QmicneQMhFzpZNhSLjrvU1pIA/0?wx_fmt=jpeg","kf_name":"Harden"}',
'pic_list' => '{"list":["http://mmbiz.qpic.cn/mmbiz_jpg/kKMgNtnEfQzDKpLXYhgo3W3Gndl34gITqmP914zSwhajIEJzUPpx40P7R8fRe1QmicneQMhFzpZNhSLjrvU1pIA/0?wx_fmt=jpeg","http://mmbiz.qpic.cn/mmbiz_jpg/kKMgNtnEfQzDKpLXYhgo3W3Gndl34gITRneE5FS9uYruXGMmrtmhsBySwddEWUGOibG8Ze2NT5E3Dyt79I0htNg/0?wx_fmt=jpeg"]}',
'service_infos' => '{"service_infos":[{"id":2,"type":1,"name":"快递","appid":"wx1373169e494e0c39","path":"index"},{"id":0,"type":2,"name":"自定义","appid":"wx1373169e494e0c39","path":"index"}]}',
'store_name' => '羊村小马烧烤',
'contract_phone' => '111111111',
'hour' => '00:00-11:11',
'company_name' => '深圳市腾讯计算机系统有限公司',
'credential' => '156718193518281',
'address' => '新疆维吾尔自治区克拉玛依市克拉玛依区碧水路15-1-8号(碧水云天广场)',
'qualification_list' => '3LaLzqiTrQcD20DlX_o-OV1-nlYMu7sdVAL7SV2PrxVyjZFZZmB3O6LPGaYXlZWq',
];
$app->nearby_poi->add($params);
```
## 更新地点
```php
$poiId = 'xxxxxxxx';
$params = [
'kf_info' => '{"open_kf":true,"kf_headimg":"http://mmbiz.qpic.cn/mmbiz_jpg/kKMgNtnEfQzDKpLXYhgo3W3Gndl34gITqmP914zSwhajIEJzUPpx40P7R8fRe1QmicneQMhFzpZNhSLjrvU1pIA/0?wx_fmt=jpeg","kf_name":"Harden"}',
'pic_list' => '{"list":["http://mmbiz.qpic.cn/mmbiz_jpg/kKMgNtnEfQzDKpLXYhgo3W3Gndl34gITqmP914zSwhajIEJzUPpx40P7R8fRe1QmicneQMhFzpZNhSLjrvU1pIA/0?wx_fmt=jpeg","http://mmbiz.qpic.cn/mmbiz_jpg/kKMgNtnEfQzDKpLXYhgo3W3Gndl34gITRneE5FS9uYruXGMmrtmhsBySwddEWUGOibG8Ze2NT5E3Dyt79I0htNg/0?wx_fmt=jpeg"]}',
'service_infos' => '{"service_infos":[{"id":2,"type":1,"name":"快递","appid":"wx1373169e494e0c39","path":"index"},{"id":0,"type":2,"name":"自定义","appid":"wx1373169e494e0c39","path":"index"}]}',
'contract_phone' => '111111111',
'hour' => '00:00-11:11',
'company_name' => '深圳市腾讯计算机系统有限公司',
'credential' => '156718193518281',
'address' => '新疆维吾尔自治区克拉玛依市克拉玛依区碧水路15-1-8号(碧水云天广场)',
'qualification_list' => '3LaLzqiTrQcD20DlX_o-OV1-nlYMu7sdVAL7SV2PrxVyjZFZZmB3O6LPGaYXlZWq',
];
$app->nearby_poi->update($poiId, $params);
```
## 删除地点
```php
$poiId = 'xxxxxxxx';
$app->nearby_poi->delete($poiId);
```
## 地点列表
```php
$page = 1;
$pageRows = 10;
$app->nearby_poi->list($page, $pageRows);
```
## 设置地点展示状态
```php
$poiId = 'xxxxxxxx';
$status = 0; // 0: 不展示,1:展示
$app->nearby_poi->setVisibility($poiId, $status);
```
================================================
FILE: docs/src/4.x/mini-program/plugin.md
================================================
# 插件管理
> 微信文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/plugin-management/pluginManager.applyPlugin.html
## 申请使用插件
```php
$pluginAppId = 'xxxxxxxxx';
$app->plugin->apply($pluginAppId);
```
## 删除已添加的插件
```php
$pluginAppId = 'xxxxxxxxx';
$app->plugin->unbind($pluginAppId);
```
## 查询已添加的插件
```php
$app->plugin->list();
```
## 获取当前所有插件使用方
```php
$page = 1;
$size = 10;
$app->plugin_dev->getUsers($page, $size);
```
## 同意插件使用申请
```php
$appId = 'wxxxxxxxxxxxxxx';
$app->plugin_dev->agree($appId);
```
## 拒绝插件使用申请
```php
$app->plugin_dev->refuse('拒绝理由');
```
## 删除已拒绝的申请者
```php
$app->plugin_dev->delete();
```
================================================
FILE: docs/src/4.x/mini-program/soter.md
================================================
# 生物认证
## 生物认证秘钥签名验证
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/soter/soter.verifySignature.html
```php
$app->soter->verifySignature($openid, $json, $signature);
```
返回值示例:
```json
{
"is_ok": true
}
```
参数说明:
> - string $openid - 用户 openid
> - string $json - 通过 [wx.startSoterAuthentication](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/soter/wx.startSoterAuthentication.html) 成功回调获得的 resultJSON 字段
> - string $signature - 通过 [wx.startSoterAuthentication](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/soter/wx.startSoterAuthentication.html) 成功回调获得的 resultJSONSignature 字段
================================================
FILE: docs/src/4.x/mini-program/subscribe_message.md
================================================
# 订阅消息
> 微信文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.addTemplate.html
## 组合模板并添加至帐号下的个人模板库
```php
$tid = 563; // 模板标题 id,可通过接口获取,也可登录小程序后台查看获取
$kidList = [1, 2]; // 开发者自行组合好的模板关键词列表,可以通过 `getTemplateKeywords` 方法获取
$sceneDesc = '提示用户图书到期'; // 服务场景描述,非必填
$app->subscribe_message->addTemplate($tid, $kidList, $sceneDesc);
```
## 删除帐号下的个人模板
```php
$templateId = 'bDmywsp2oEHjwAadTGKkUHpC0RgBVPvfAM7Cu1s03z8';
$app->subscribe_message->deleteTemplate($templateId);
```
## 获取小程序账号的类目
```php
$app->subscribe_message->getCategory();
```
## 获取模板标题的关键词列表
```php
$tid = 563; // 模板标题 id,可通过接口获取,也可登录小程序后台查看获取
$app->subscribe_message->getTemplateKeywords($tid);
```
## 获取帐号所属类目下的公共模板标题
```php
$ids = [612, 613]; // 类目 id
$start = 0; // 用于分页,表示从 start 开始。从 0 开始计数。
$limit = 30; // 用于分页,表示拉取 limit 条记录。最大为 30。
$app->subscribe_message->getTemplateTitles($ids, $start, $limit);
```
## 获取当前帐号下的个人模板列表
```php
$app->subscribe_message->getTemplates();
```
## 发送订阅消息
```php
$data = [
'template_id' => 'bDmywsp2oEHjwAadTGKkUJ-eJEiMiOf7H-dZ7wjdw80', // 所需下发的订阅模板id
'touser' => 'oSyZp5OBNPBRhG-7BVgWxbiNZm', // 接收者(用户)的 openid
'page' => '', // 点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。
'data' => [ // 模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } }
'date01' => [
'value' => '2019-12-01',
],
'number01' => [
'value' => 10,
],
],
];
$app->subscribe_message->send($data);
```
================================================
FILE: docs/src/4.x/mini-program/template_message.md
================================================
# 模板消息
## 获取小程序模板库标题列表
```
$app->template_message->list($offset, $count);
```
## 获取模板库某个模板标题下关键词库
```
$app->template_message->get($id);
```
## 组合模板并添加至帐号下的个人模板库
```
$app->template_message->add($id, $keywordIdList);
```
## 获取帐号下已存在的模板列表
```
$app->template_message->getTemplates($offset, $count);
```
## 删除帐号下的某个模板
```
$app->template_message->delete($templateId);
```
## 发送模板消息
```php
$app->template_message->send([
'touser' => 'user-openid',
'template_id' => 'template-id',
'page' => 'index',
'form_id' => 'form-id',
'data' => [
'keyword1' => 'VALUE',
'keyword2' => 'VALUE2',
// ...
],
]);
```
================================================
FILE: docs/src/4.x/miscellaneous.md
================================================
# 其它
### 其它
================================================
FILE: docs/src/4.x/official-account/accounts.md
================================================
# 多账号接入
如果你想使用本项目接入多个公众号,在本程序中,您可以为每个帐号都设置一个 id,此 id 对应了该帐号的 appid、token 等信息。
如下表
| id | appId | secret | 其它... |
| ---- | -------------------- | ---------------------------------- | ----- |
| 1 | `wx3cf0f39249eb0e60` | `f28f735d4f1c242f4687abb469072a29` | ... |
| 2 | `wx49eb0e63cf0f39s2` | `8f735d4687abb469f1c2422a29f4f207` | ... |
| N | `wx5cfeb0e60f392490` | `35f8f27d46f1c242f487a9072a29bb46` | ... |
在微信公众平台的设置中,您可以将您帐号中平台的 `url` 设置为 `您的网址/?id=xxx`,如:
```
http://easywechat.com/wechat?id=1
```
而在程序入口处,根据 `id` 查找对应帐号的 `appid` 和 其它信息来创建配置数组创建实例即可。
================================================
FILE: docs/src/4.x/official-account/base.md
================================================
# 基础接口
## 清理接口调用次数
> 此接口官方有每月调用限制,不可随意调用
```php
$app->base->clearQuota();
```
## 获取微信服务器 IP (或IP段)
```php
$app->base->getValidIps();
```
================================================
FILE: docs/src/4.x/official-account/broadcasting.md
================================================
# 群发
微信的群发消息接口有各种乱七八糟的注意事项及限制,具体请阅读微信官方文档。
## 发送消息
以下所有方法均有第二个参数 `$to` 用于指定接收对象:
> - 当 `$to` 为整型时为标签 id
> - 当 `$to` 为数组时为用户的 openid 列表(至少两个用户的 openid)
> - 当 `$to` 为 `null` 时表示全部用户
```php
$app->broadcasting->sendMessage(Message $message, array | int $to = null);
```
下面的别名方法 `sendXXX` 都是基于上面 `sendMessage` 方法的封装。
### 文本消息
```php
$app->broadcasting->sendText("大家好!欢迎使用 EasyWeChat。");
// 指定目标用户
// 至少两个用户的 openid,必须是数组。
$app->broadcasting->sendText("大家好!欢迎使用 EasyWeChat。", [$openid1, $openid2]);
// 指定标签组用户
$app->broadcasting->sendText("大家好!欢迎使用 EasyWeChat。", $tagId); // $tagId 必须是整型数字
```
### 图文消息
```php
$app->broadcasting->sendNews($mediaId);
$app->broadcasting->sendNews($mediaId, [$openid1, $openid2]);
$app->broadcasting->sendNews($mediaId, $tagId);
```
### 图片消息
```php
$app->broadcasting->sendImage($mediaId);
$app->broadcasting->sendImage($mediaId, [$openid1, $openid2]);
$app->broadcasting->sendImage($mediaId, $tagId);
```
### 语音消息
```php
$app->broadcasting->sendVoice($mediaId);
$app->broadcasting->sendVoice($mediaId, [$openid1, $openid2]);
$app->broadcasting->sendVoice($mediaId, $tagId);
```
### 视频消息
用于群发的视频消息,需要先创建消息对象,
```php
// 1. 先上传视频素材用于群发:
$video = '/path/to/video.mp4';
$videoMedia = $app->media->uploadVideoForBroadcasting($video, '视频标题', '视频描述');
// 结果如下:
//{
// "type":"video",
// "media_id":"IhdaAQXuvJtGzwwc0abfXnzeezfO0NgPK6AQYShD8RQYMTtfzbLdBIQkQziv2XJc",
// "created_at":1398848981
//}
// 2. 使用上面得到的 media_id 群发视频消息
$app->broadcasting->sendVideo($videoMedia['media_id']);
```
### 卡券消息
```php
$app->broadcasting->sendCard($cardId);
$app->broadcasting->sendCard($cardId, [$openid1, $openid2]);
$app->broadcasting->sendCard($cardId, $tagId);
```
### 发送预览群发消息给指定的 `openId` 用户
```php
$app->broadcasting->previewText($text, $openId);
$app->broadcasting->previewNews($mediaId, $openId);
$app->broadcasting->previewVoice($mediaId, $openId);
$app->broadcasting->previewImage($mediaId, $openId);
$app->broadcasting->previewVideo($message, $openId);
$app->broadcasting->previewCard($cardId, $openId);
```
### 发送预览群发消息给指定的微信号用户
> $wxanme 是用户的微信号,比如:notovertrue
```php
$app->broadcasting->previewTextByName($text, $wxname);
$app->broadcasting->previewNewsByName($mediaId, $wxname);
$app->broadcasting->previewVoiceByName($mediaId, $wxname);
$app->broadcasting->previewImageByName($mediaId, $wxname);
$app->broadcasting->previewVideoByName($message, $wxname);
$app->broadcasting->previewCardByName($cardId, $wxname);
```
### 删除群发消息
```php
$app->broadcasting->delete($msgId);
```
### 查询群发消息发送状态
```php
$app->broadcasting->status($msgId);
```
================================================
FILE: docs/src/4.x/official-account/card.md
================================================
# 卡券
-
## 获取实例
```php
$card = $app->card;
```
## 通用功能
### 获取卡券颜色
```php
$card->colors();
```
### 卡券开放类目查询
```php
$card->categories();
```
### 创建卡券
创建卡券接口是微信卡券的基础接口,用于创建一类新的卡券,获取 card_id,创建成功并通过审核后,商家可以通过文档提供的其他接口将卡券下发给用户,每次成功领取,库存数量相应扣除。
```php
$card->create($cardType = 'member_card', array $attributes);
```
> - `attributes` array 卡券信息
示例:
```php
[
'brand_name' => '微信餐厅',
'code_type' => 'CODE_TYPE_TEXT',
'title' => '132元双人火锅套餐',
//...
],
'advanced_info' => [
'use_condition' => [
'accept_category' => '鞋类',
'reject_category' => '阿迪达斯',
'can_use_with_other_discount' => true,
],
//...
],
];
$result = $card->create($cardType, $attributes);
```
### 获取卡券详情
```php
$cardInfo = $card->get($cardId);
```
### 批量查询卡列表
```php
$card->list($offset = 0, $count = 10, $statusList = 'CARD_STATUS_VERIFY_OK');
```
> - `offset` int - 查询卡列表的起始偏移量,从 0 开始
> - `count` int - 需要查询的卡片的数量
> - `statusList` - 支持开发者拉出指定状态的卡券列表,详见 example
示例:
```php
// CARD_STATUS_NOT_VERIFY, 待审核;
// CARD_STATUS_VERIFY_FAIL, 审核失败;
// CARD_STATUS_VERIFY_OK, 通过审核;
// CARD_STATUS_USER_DELETE,卡券被商户删除;
// CARD_STATUS_DISPATCH,在公众平台投放过的卡券;
$result = $card->list($offset, $count, 'CARD_STATUS_NOT_VERIFY');
```
### 更改卡券信息接口
支持更新所有卡券类型的部分通用字段及特殊卡券中特定字段的信息。
```php
$card->update($cardId, $type, $attributes = []);
```
> - `type` string - 卡券类型
示例:
```php
$cardId = 'pdkJ9uCzKWebwgNjxosee0ZuO3Os';
$type = 'groupon';
$attributes = [
'base_info' => [
'logo_url' => 'http://mmbiz.qpic.cn/mmbiz/2aJY6aCPatSeibYAyy7yct9zJXL9WsNVL4JdkTbBr184gNWS6nibcA75Hia9CqxicsqjYiaw2xuxYZiaibkmORS2oovdg/0',
'center_title' => '顶部居中按钮',
'center_sub_title' => '按钮下方的wording',
'center_url' => 'http://easywechat.com',
'custom_url_name' => '立即使用',
'custom_url' => 'http://www.qq.com',
'custom_url_sub_title' => '6个汉字tips',
'promotion_url_name' => '更多优惠',
'promotion_url' => 'http://www.qq.com',
],
//...
];
$result = $card->update($cardId, $type, $attributes);
```
### 删除卡券
```php
$card->delete($cardId);
```
### 创建二维码
开发者可调用该接口生成一张卡券二维码供用户扫码后添加卡券到卡包。
自定义 Code 码的卡券调用接口时,POST 数据中需指定 code,非自定义 code 不需指定,指定 openid 同理。指定后的二维码只能被用户扫描领取一次。
```php
$card->createQrCode($cards);
```
> - `cards` array - 卡券相关信息
示例:
```php
// 领取单张卡券
$cards = [
'action_name' => 'QR_CARD',
'expire_seconds' => 1800,
'action_info' => [
'card' => [
'card_id' => 'pdkJ9uFS2WWCFfbbEfsAzrzizVyY',
'is_unique_code' => false,
'outer_id' => 1,
],
],
];
$result = $card->createQrCode($cards);
```
```php
// 领取多张卡券
$cards = [
'action_name' => 'QR_MULTIPLE_CARD',
'action_info' => [
'multiple_card' => [
'card_list' => [
['card_id' => 'pdkJ9uFS2WWCFfbbEfsAzrzizVyY'],
],
],
],
];
$result = $card->createQrCode($cards);
```
请求成功返回值示例:
```json
{
"errcode": 0,
"errmsg": "ok",
"ticket": "gQHB8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL0JIV3lhX3psZmlvSDZmWGVMMTZvAAIEsNnKVQMEIAMAAA==", //获取ticket后需调用换取二维码接口获取二维码图片,详情见字段说明。
"expire_seconds": 1800,
"url": "http://weixin.qq.com/q/BHWya_zlfioH6fXeL16o ",
"show_qrcode_url": "https://mp.weixin.qq.com/cgi-bin/showqrcode? ticket=gQH98DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL0czVzRlSWpsamlyM2plWTNKVktvAAIE6SfgVQMEgDPhAQ%3D%3D"
}
```
### ticket 换取二维码图片
获取二维码 ticket 后,开发者可用 ticket 换取二维码图片。
```php
$card->getQrCode($ticket);
```
> - `ticket` string> - 获取的二维码 ticket,凭借此 ticket 可以在有效时间内换取二维码。
示例:
```php
$ticket = 'gQFF8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL01VTzN0T0hsS1BwUlBBYUszbVN5AAIEughxVwMEAKd2AA==';
$result = $card->getQrCode($ticket);
```
### ticket 换取二维码链接
```php
$card->getQrCodeUrl($ticket);
```
示例:
```php
$ticket = 'gQFF8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL01VTzN0T0hsS1BwUlBBYUszbVN5AAIEughxVwMEAKd2AA==';
$card->getQrCodeUrl($ticket);
```
### 创建货架接口
开发者需调用该接口创建货架链接,用于卡券投放。创建货架时需填写投放路径的场景字段。
```php
$card->createLandingPage($banner, $pageTitle, $canShare, $scene, $cards);
```
> - `banner` string -页面的 banner 图;
> - `pageTitle` string - 页面的 title
> - `canShare` bool - 页面是不是可以分享,true 或 false
> - `scene` string - 投放页面的场景值,具体值请参考下面的 example
> - `cards` array - 卡券列表,每个元素有两个字段
示例:
```php
$banner = 'http://mmbiz.qpic.cn/mmbiz/iaL1LJM1mF9aRKPZJkmG8xXhiaHqkKSVMMWeN3hLut7X7hicFN';
$pageTitle = '惠城优惠大派送';
$canShare = true;
//SCENE_NEAR_BY 附近
//SCENE_MENU 自定义菜单
//SCENE_QRCODE 二维码
//SCENE_ARTICLE 公众号文章
//SCENE_H5 h5页面
//SCENE_IVR 自动回复
//SCENE_CARD_CUSTOM_CELL 卡券自定义cell
$scene = 'SCENE_NEAR_BY';
$cardList = [
['card_id' => 'pdkJ9uLRSbnB3UFEjZAgUxAJrjeY', 'thumb_url' => 'http://test.digilinx.cn/wxApi/Uploads/test.png'],
['card_id' => 'pdkJ9uJ37aU-tyRj4_grs8S45k1c', 'thumb_url' => 'http://test.digilinx.cn/wxApi/Uploads/aa.jpg'],
];
$result = $card->createLandingPage($banner, $pageTitle, $canShare, $scene, $cardList);
```
### 图文消息群发卡券
> 特别注意:目前该接口仅支持填入非自定义 code 的卡券,自定义 code 的卡券需先进行 code 导入后调用。
```php
$card->getHtml($cardId);
```
示例:
```php
$cardId = 'pdkJ9uLCEF_HSKO7JdQOUcZ-PUzo';
$result = $card->getHtml($cardId);
```
### 设置测试白名单
同时支持“openid”、“username”两种字段设置白名单,总数上限为 10 个。
```php
$card->setTestWhitelist($openids); // 使用 openid
$card->setTestWhitelistByName($usernames); // 使用 username
```
> - `openids` array - 测试的 openid 列表
> - `usernames` array> - 测试的微信号列表
示例:
```php
// by openid
$openids = [$openId, $openId2, $openid3...];
$result = $card->setTestWhitelist($openids);
// by username
$usernames = ['tianye0327', 'iovertrue'];
$result = $card->setTestWhitelistByName($usernames);
```
### 获取用户已领取卡券接口
用于获取用户卡包里的,属于该 appid 下所有**可用卡券,包括正常状态和未生效状态**。
```php
$card->getUserCards($openid, $cardId);
```
示例:
```php
$openid = 'odkJ9uDUz26RY-7DN1mxkznfo9xU';
$cardId = ''; // 卡券ID。不填写时默认查询当前 appid 下的卡券。
$result = $card->getUserCards($openid, $cardId);
```
### 设置微信买单接口
```php
$card->setPayCell($cardId, $isOpen = true);
```
> - `isOpen` string - 是否开启买单功能,填 true/false,不填默认 true
示例:
```php
$cardId = 'pdkJ9uH7u11R-Tu1kilbaW_zDFow';
$result = $card->setPayCell($cardId); // isOpen = true
$result = $card->setPayCell($cardId, $isOpen);
```
### 修改库存接口
```php
$card->increaseStock($cardId, $amount); // 增加库存
$card->reductStock($cardId, $amount); // 减少库存
```
> - `cardId` string - 卡券 ID
> - `amount` int - 修改多少库存
示例:
```php
$cardId = 'pdkJ9uLRSbnB3UFEjZAgUxAJrjeY';
$result = $card->increaseStock($cardId, 100);
```
## 卡券 Code
### 导入 code 接口
在自定义 code 卡券成功创建并且通过审核后,必须将自定义 code 按照与发券方的约定数量调用导入 code 接口导入微信后台。
```php
$card->code->deposit($cardId, $codes);
```
> - `cardId` string - 要导入 code 的卡券 ID
> - `codes` array - 要导入微信卡券后台的自定义 code,最多 100 个
示例:
```php
$cardId = 'pdkJ9uLCEF_HSKO7JdQOUcZ-PUzo';
$codes = ['11111', '22222', '33333'];
$result = $card->code->deposit($cardId, $codes);
```
### 查询导入 code 数目
```php
$card->code->getDepositedCount($cardId); // 要导入 code 的卡券 ID
```
示例:
```php
$cardId = 'pdkJ9uLCEF_HSKO7JdQOUcZ-PUzo';
$result = $card->code->getDepositedCount($cardId);
```
### 核查 code 接口
为了避免出现导入差错,强烈建议开发者在查询完 code 数目的时候核查 code 接口校验 code 导入微信后台的情况。
```php
$card->code->check($cardId, $codes);
```
示例:
```php
$cardId = 'pdkJ9uLCEF_HSKO7JdQOUcZ-PUzo';
$codes = ['807732265476', '22222', '33333'];
$result = $card->code->check($cardId, $codes);
```
### 查询 Code 接口
```php
$card->code->get($code, $cardId, $checkConsume = true);
```
> - checkConsume 是否校验 code 核销状态,true 和 false
示例:
```php
$code = '736052543512';
$cardId = 'pdkJ9uDgnm0pKfrTb1yV0dFMO_Gk';
$result = $card->code->get($code, $cardId);
$result = $card->code->get($code, $cardId, false); // check_consume = false
```
### 核销 Code 接口
```php
$card->code->consume($code);
// 或者指定 cardId
$card->code->consume($code, $cardId);
```
示例:
```php
$code = '789248558333';
$cardId = 'pdkJ9uDmhkLj6l5bm3cq9iteQBck';
$result = $card->code->consume($code);
// 或
$result = $card->code->consume($code, $cardId);
```
### Code 解码接口
```php
$card->code->decrypt($encryptedCode);
```
示例:
```php
$encryptedCode = 'XXIzTtMqCxwOaawoE91+VJdsFmv7b8g0VZIZkqf4GWA60Fzpc8ksZ/5ZZ0DVkXdE';
$result = $card->code->decrypt($encryptedCode);
```
### 更改 Code 接口
```php
$card->code->update($code, $newCode, $cardId);
```
> - `newCode` string - 变更后的有效 Code 码
示例:
```php
$code = '148246271394';
$newCode = '659266965266';
$cardId = '';
$result = $card->code->update($code, $newCode, $cardId);
```
### 设置卡券失效
```php
$card->code->disable($code, $cardId);
```
示例:
```php
$code = '736052543512';
$cardId = '';
$result = $card->code->disable($code, $cardId);
```
## 通用卡券
## 卡券激活
```php
$result = $card->general_card->activate($info);
```
## 撤销激活
```php
$result = $card->general_card->deactivate(string $cardId, string $code);
```
## 更新用户信息
```php
$result = $card->general_card->updateUser(array $info);
```
## 会员卡
### 会员卡激活
```php
$result = $card->member_card->activate($info);
```
> - `info` - 需要激活的会员卡信息
示例:
```php
$info = [
'membership_number' => '357898858', //会员卡编号,由开发者填入,作为序列号显示在用户的卡包里。可与Code码保持等值。
'code' => '916679873278', //创建会员卡时获取的初始code。
'activate_begin_time' => '1397577600', //激活后的有效起始时间。若不填写默认以创建时的 data_info 为准。Unix时间戳格式
'activate_end_time' => '1422724261', //激活后的有效截至时间。若不填写默认以创建时的 data_info 为准。Unix时间戳格式。
'init_bonus' => '持白金会员卡到店消费,可享8折优惠。', //初始积分,不填为0。
'init_balance' => '持白金会员卡到店消费,可享8折优惠。', //初始余额,不填为0。
'init_custom_field_value1' => '白银', //创建时字段custom_field1定义类型的初始值,限制为4个汉字,12字节。
'init_custom_field_value2' => '9折', //创建时字段custom_field2定义类型的初始值,限制为4个汉字,12字节。
'init_custom_field_value3' => '200', //创建时字段custom_field3定义类型的初始值,限制为4个汉字,12字节。
];
$result = $card->member_card->activate($info);
```
### 设置开卡字段
```php
$card->member_card->setActivationForm($cardId, $settings);
```
> - `settings` array - 会员卡激活时的选项
示例:
```php
$cardId = 'pdkJ9uJYAyfLXsUCwI2LdH2Pn1AU';
$settings = [
'required_form' => [
'common_field_id_list' => [
'USER_FORM_INFO_FLAG_MOBILE',
'USER_FORM_INFO_FLAG_LOCATION',
'USER_FORM_INFO_FLAG_BIRTHDAY',
],
'custom_field_list' => [
'喜欢的食物',
],
],
'optional_form' => [
'common_field_id_list' => [
'USER_FORM_INFO_FLAG_EMAIL',
],
'custom_field_list' => [
'喜欢的食物',
],
],
];
$result = $card->member_card->setActivationForm($cardId, $settings);
```
### 拉取会员信息
```php
$card->member_card->getUser($cardId, $code);
```
示例:
```php
$cardId = 'pbLatjtZ7v1BG_ZnTjbW85GYc_E8';
$code = '916679873278';
$result = $card->member_card->getUser($cardId, $code);
```
### 更新会员信息
```php
$card->member_card->updateUser($info);
```
> - `info` array - 可以更新的会员信息
示例:
```php
$info = [
'code' => '916679873278', //卡券Code码。
'card_id' => 'pbLatjtZ7v1BG_ZnTjbW85GYc_E8', //卡券ID。
'record_bonus' => '消费30元,获得3积分', //商家自定义积分消耗记录,不超过14个汉字。
'bonus' => '100', //需要设置的积分全量值,传入的数值会直接显示,如果同时传入add_bonus和bonus,则前者无效。
'balance' => '持白金会员卡到店消费,可享8折优惠。', //需要设置的余额全量值,传入的数值会直接显示,如果同时传入add_balance和balance,则前者无效。
'record_balance' => '持白金会员卡到店消费,可享8折优惠。', //商家自定义金额消耗记录,不超过14个汉字。
'custom_field_value1' => '100', //创建时字段custom_field1定义类型的最新数值,限制为4个汉字,12字节。
'custom_field_value2' => '200', //创建时字段custom_field2定义类型的最新数值,限制为4个汉字,12字节。
'custom_field_value3' => '300', //创建时字段custom_field3定义类型的最新数值,限制为4个汉字,12字节。
];
$result = $card->member_card->updateUser($info);
```
## 子商户
### 添加子商户
```php
$card->sub_merchant->create(array $attributes);
```
示例:
```php
$attributes = [
'brand_name' => 'overtrue',
'logo_url' => 'http://mmbiz.qpic.cn/mmbiz/iaL1LJM1mF9aRKPZJkmG8xXhiaHqkKSVMMWeN3hLut7X7hicFNjakmxibMLGWpXrEXB33367o7zHN0CwngnQY7zb7g/0',
'protocol' => 'qIqwTfzAdJ_1-VJFT0fIV53DSY4sZY2WyhkzZzbV498Qgdp-K5HJtZihbHLS0Ys0',
'end_time' => '1438990559',
'primary_category_id' => 1,
'secondary_category_id' => 101,
'agreement_media_id' => '',
'operator_media_id' => '',
'app_id' => '',
];
$result = $card->sub_merchant->create($attributes);
```
### 更新子商户
```php
$card->sub_merchant->update(int $merchantId, array $info);
```
> - `$merchantId` int - 子商户 ID
> - `$info` array - 参数与创建子商户参数一样
示例:
```php
$info = [
//...
];
$result = $card->sub_merchant->update('12', $info);
```
## 特殊票券
### 机票值机
```php
$card->boarding_pass->checkin(array $params);
```
### 更新会议门票 - 更新用户
```php
$card->meeting_ticket->updateUser(array $params);
```
### 更新电影门票 - 更新用户
```php
$card->movie_ticket->updateUser(array $params);
```
## JSAPI
### 卡券批量下发到用户
```php
$cards = [
['card_id' => 'pdkJ9uLRSbnB3UFEjZAgUxAJrjeY', 'outer_id' => 2],
['card_id' => 'pdkJ9uJ37aU-tyRj4_grs8S45k1c', 'outer_id' => 3],
];
$json = $card->jssdk->assign($cards); // 返回 json 格式
```
返回 json,在模板里的用法:
```html
wx.addCard({ cardList:
= $json ?>, // 需要打开的卡券列表 success: function (res) { var cardList = res.cardList; // 添加的卡券列表信息 } });
```
### 获取 Ticket
```php
$card->jssdk->getTicket();
// 强制刷新
$card->jssdk->getTicket(true);
```
================================================
FILE: docs/src/4.x/official-account/comment.md
================================================
# 评论数据管理
## 打开已群发文章评论
```php
$app->comment->open($msgId, $index = null);
```
## 关闭已群发文章评论
```php
$app->comment->close($msgId, $index = null);
```
## 查看指定文章的评论数据
```php
$app->comment->list(string $msgId, int $index, int $begin, int $count, int $type = 0);
```
## 将评论标记精选
```php
$app->comment->markElect(string $msgId, int $index, int $commentId);
```
## 将评论取消精选
```php
$app->comment->unmarkElect(string $msgId, int $index, int $commentId);
```
## 删除评论
```php
$app->comment->delete(string $msgId, int $index, int $commentId);
```
## 回复评论
```php
$app->comment->reply(string $msgId, int $index, int $commentId, string $content);
```
## 删除回复
```php
$app->comment->deleteReply(string $msgId, int $index, int $commentId);
```
================================================
FILE: docs/src/4.x/official-account/configuration.md
================================================
# 配置
常用的配置参数会比较少,因为除非你有特别的定制,否则基本上默认值就可以了:
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'wx3cf0f39249eb0exx',
'secret' => 'f1c242f4f28f735d4687abb469072axx',
// 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
'response_type' => 'array',
//...
];
$app = Factory::officialAccount($config);
```
下面是一个完整的配置样例:
> 不建议你在配置的时候弄这么多,用到啥就配置啥才是最好的,因为大部分用默认值即可。
```php
'your-app-id', // AppID
'secret' => 'your-app-secret', // AppSecret
'token' => 'your-token', // Token
'aes_key' => '', // EncodingAESKey,兼容与安全模式下请一定要填写!!!
/**
* 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
* 使用自定义类名时,构造函数将会接收一个 `EasyWeChat\Kernel\Http\Response` 实例
*/
'response_type' => 'array',
/**
* 日志配置
*
* level: 日志级别, 可选为:
* debug/info/notice/warning/error/critical/alert/emergency
* path:日志文件位置(绝对路径!!!),要求可写权限
*/
'log' => [
'default' => 'dev', // 默认使用的 channel,生产环境可以改为下面的 prod
'channels' => [
// 测试环境
'dev' => [
'driver' => 'single',
'path' => '/tmp/easywechat.log',
'level' => 'debug',
],
// 生产环境
'prod' => [
'driver' => 'daily',
'path' => '/tmp/easywechat.log',
'level' => 'info',
],
],
],
/**
* 接口请求相关配置,超时时间等,具体可用参数请参考:
* http://docs.guzzlephp.org/en/stable/request-config.html
*
* - retries: 重试次数,默认 1,指定当 http 请求失败时重试的次数。
* - retry_delay: 重试延迟间隔(单位:ms),默认 500
* - log_template: 指定 HTTP 日志模板,请参考:https://github.com/guzzle/guzzle/blob/master/src/MessageFormatter.php
*/
'http' => [
'max_retries' => 1,
'retry_delay' => 500,
'timeout' => 5.0,
// 'base_uri' => 'https://api.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用,根据不同的模块配置不同的 uri
],
/**
* OAuth 配置
*
* scopes:公众平台(snsapi_userinfo / snsapi_base),开放平台:snsapi_login
* callback:OAuth授权完成后的回调页地址
*/
'oauth' => [
'scopes' => ['snsapi_userinfo'],
'callback' => '/examples/oauth_callback.php',
],
];
```
> :heart: 安全模式下请一定要填写 `aes_key`
## 日志配置
你可以配置多个日志的 channel,每个 channel 里的 `driver` 对应不同的日志驱动,内置可用的 `driver` 如下表:
名称 | 描述
------------- | -------------
`stack` | 复合型,可以包含下面多种驱动的混合模式
`single` | 基于 `StreamHandler` 的单一文件日志,参数有 `path`,`level`
`daily` | 基于 `RotatingFileHandler` 按日期生成日志文件,参数有 `path`,`level`,`days`(默认 7 天)
`slack` | 基于 `SlackWebhookHandler` 的 Slack 组件,参数请参考源码:[LogManager.php](https://github.com/overtrue/wechat/blob/master/src/Kernel/Log/LogManager.php#L247)
`syslog` | 基于 `SyslogHandler` Monolog 驱动,参数有 `facility` 默认为 `LOG_USER`,`level`
`errorlog` | 记录日志到系统错误日志,基于 `ErrorLogHandler`,参数有 `type`,默认为 `ErrorLogHandler::OPERATING_SYSTEM`
### 自定义日志驱动
由于日志使用的是 [Monolog](https://github.com/Seldaek/monolog),所以,除了默认的文件式日志外,你可以自定义日志处理器:
```php
use Monolog\Logger;
use Monolog\Handler\RotatingFileHandler;
// 注册自定义日志
$app->logger->extend('mylog', function($app, $config){
return new Logger($this->parseChannel($config), [
$this->prepareHandler(new RotatingFileHandler(
$config['path'], $config['days'], $this->level($config)
)),
]);
});
```
> 在你自定义的闭包函数中,可以使用 `EasyWeChat\Kernel\Log\LogManager` 中的方法,具体请查看 SDK 源代码。
配置文件中在 `driver` 部分即可使用你自定义的驱动了:
```php
'log' => [
'default' => 'dev', // 默认使用的 channel,生产环境可以改为下面的 prod
'channels' => [
// 测试环境
'dev' => [
'driver' => 'mylog',
'path' => '/tmp/easywechat.log',
'level' => 'debug',
'days' => 5,
],
//...
],
],
```
================================================
FILE: docs/src/4.x/official-account/customer_service.md
================================================
# 客服
使用客服系统可以向用户发送消息以及群发消息,客服的管理等功能。
## 客服管理
### 获取所有客服
```php
$app->customer_service->list();
```
### 获取所有在线的客服
```php
$app->customer_service->online();
```
### 添加客服
```php
$app->customer_service->create('foo@test', '客服1');
```
### 修改客服
```php
$app->customer_service->update('foo@test', '客服1');
```
### 删除账号
```php
$app->customer_service->delete('foo@test');
```
### 设置客服头像
```php
$app->customer_service->setAvatar('foo@test', $avatarPath); // $avatarPath 为本地图片路径,非 URL
```
### 获取客服与客户聊天记录
```php
$app->customer_service->messages($startTime, $endTime, $msgId = 1, $number = 10000);
```
示例:
```php
$records = $app->customer_service->messages('2015-06-07', '2015-06-21', 1, 20000);
```
### 主动发送消息给用户
```php
$app->customer_service->message($message)->to($openId)->send();
```
> `$message` 为消息对象或文本,请参考:[消息](messages)
示例:
```php
$app->customer_service->message('hello')
> ->to('oV-gpwdOIwSI958m9osAhGBFxxxx')
> ->send();
```
### 指定客服发送消息
```php
$app->customer_service->message($message)
> ->from('account@test')
> ->to($openId)
> ->send();
```
> `$message` 为消息对象或文本,请参考:[消息](messages.html)
示例:
```php
$app->customer_service->message('hello')
> ->from('kf2001@gh_176331xxxx')
> ->to('oV-gpwdOIwSI958m9osAhGBFxxxx')
> ->send();
```
### 邀请微信用户加入客服
以账号 `foo@test` 邀请 微信号 为 `xxxx` 的微信用户加入客服。
```php
$app->customer_service->invite('foo@test', 'xxxx');
```
## 客服会话控制
## 创建会话
```php
$app->customer_service_session->create('test1@test', 'OPENID');
```
### 关闭会话
```php
$app->customer_service_session->close('test1@test', 'OPENID');
```
### 获取客户会话状态
```php
$app->customer_service_session->get('OPENID');
```
### 获取客服会话列表
```php
$app->customer_service_session->list('test1@test');
```
### 获取未接入会话列表
```php
$app->customer_service_session->waiting();
```
================================================
FILE: docs/src/4.x/official-account/data_cube.md
================================================
# 数据统计与分析
通过数据接口,开发者可以获取与公众平台官网统计模块类似但更灵活的数据,还可根据需要进行高级处理。
>
> 1. 接口侧的公众号数据的数据库中仅存储了 **2014年12月1日之后**的数据,将查询不到在此之前的日期,即使有查到,也是不可信的脏数据;
> 2. 请开发者在调用接口获取数据后,将数据保存在自身数据库中,即加快下次用户的访问速度,也降低了微信侧接口调用的不必要损耗。
> 3. 额外注意,获取图文群发每日数据接口的结果中,只有**中间页阅读人数+原文页阅读人数+分享转发人数+分享转发次数+收藏次数 >=3** 的结果才会得到统计,过小的阅读量的图文消息无法统计。
## 示例
```php
$userSummary = $app->data_cube->userSummary('2014-12-07', '2014-12-08');
var_dump($userSummary);
//
//[
// {
// "ref_date": "2014-12-07",
// "user_source": 0,
// "new_user": 0,
// "cancel_user": 0
// }
// //后续还有ref_date在begin_date和end_date之间的数据
// ]
```
## API
$from 示例: `2014-02-13` 获取数据的起始日期
$to 示例: `2014-02-18` 获取数据的结束日期,`$to`允许设置的最大值为昨日
`$from` 和 `$to` 的差值需小于 “最大时间跨度”(比如最大时间跨度为 1 时,`$from` 和 `$to` 的差值只能为 0,才能小于 1 ),否则会报错
+ `array userSummary(string $from, string $to)` 获取用户增减数据, 最大时间跨度:**7**;
+ `array userCumulate(string $from, string $to)` 获取累计用户数据, 最大时间跨度:**7**;
+ `array articleSummary(string $from, string $to)` 获取图文群发每日数据, 最大时间跨度:**1**;
+ `array articleTotal(string $from, string $to)` 获取图文群发总数据, 最大时间跨度:**1**;
+ `array userReadSummary(string $from, string $to)` 获取图文统计数据, 最大时间跨度:**3**;
+ `array userReadHourly(string $from, string $to)` 获取图文统计分时数据, 最大时间跨度:**1**;
+ `array userShareSummary(string $from, string $to)` 获取图文分享转发数据, 最大时间跨度:**7**;
+ `array userShareHourly(string $from, string $to)` 获取图文分享转发分时数据, 最大时间跨度:**1**;
+ `array upstreamMessageSummary(string $from, string $to)` 获取消息发送概况数据, 最大时间跨度:**7**;
+ `array upstreamMessageHourly(string $from, string $to)` 获取消息发送分时数据, 最大时间跨度:**1**;
+ `array upstreamMessageWeekly(string $from, string $to)` 获取消息发送周数据, 最大时间跨度:**30**;
+ `array upstreamMessageMonthly(string $from, string $to)` 获取消息发送月数据, 最大时间跨度:**30**;
+ `array upstreamMessageDistSummary(string $from, string $to)` 获取消息发送分布数据, 最大时间跨度:**15**;
+ `array upstreamMessageDistWeekly(string $from, string $to)` 获取消息发送分布周数据, 最大时间跨度:**30**;
+ `array upstreamMessageDistMonthly(string $from, string $to)` 获取消息发送分布月数据, 最大时间跨度:**30**;
+ `array interfaceSummary(string $from, string $to)` 获取接口分析数据, 最大时间跨度:**30**;
+ `array interfaceSummaryHourly(string $from, string $to)` 获取接口分析分时数据, 最大时间跨度:**1**;
+ `array cardSummary(string $from, string $to, int $condSource = 0)` 获取普通卡券分析分时数据, 最大时间跨度:**1**;
+ `array freeCardSummary(string $from, string $to, int $condSource = 0, string $cardId = '')` 获取免费券分析分时数据, 最大时间跨度:**1**;
+ `array memberCardSummary(string $from, string $to, int $condSource = 0)` 获取会员卡分析分时数据, 最大时间跨度:**1**;
================================================
FILE: docs/src/4.x/official-account/events.md
================================================
# 事件
更多请参考:[服务端](server.html)
关于事件类型请参考微信官方文档:http://mp.weixin.qq.com/wiki/
================================================
FILE: docs/src/4.x/official-account/goods.md
================================================
# 返佣商品
> 微信文档:https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&key=11533749572M9ODP&version=1&lang=zh_CN&platform=2
## 导入商品
每次调用支持批量导入不超过1000条的商品信息。每分钟单个商户全局调用次数不得超过200次。每天调用次数不得超过100万次。每次请求包大小不超过2M。
```php
$data = [
[
'pid' => 'pid001',
'image_info' => [
'main_image_list' => [
[
'url' => 'http://www.google.com/a.jpg',
],
[
'url' => 'http://www.google.com/b.jpg',
],
],
],
//...
],
//...
];
$result = $app->goods->add($data);
// $result:
//{
// "errcode": 0,
// "errmsg": "ok",
// "status_ticket": "115141102647330200"
//}
```
`status_ticket` 用于获取此次导入的详细结果。
## 更新商品
更新时,字段不填代表不更新该字段(此处的字段不填,代表无此字段,而不是把字段的值设为空,设为空即代表更新该字段为空)。
对于字符串类型的选填字段,如副标题,若清空不展示,则可设置为空;对于数字类型的选填字段,如原价,若清空不展示,则需设置为0。
> 基本字段更新中 `pid` 为必填字段,且无法修改
```php
$data = [
[
'pid' => 'pid001',
'image_info' => [
'main_image_list' => [
[
'url' => 'http://www.baidu.com/c.jpg',
],
[
'url' => 'http://www.baidu.com/d.jpg',
],
],
],
//...
],
//...
];
$result = $app->goods->update($data);
// $result:
//{
// "errcode": 0,
// "errmsg": "ok",
// "status_ticket": "115141102647330200"
//}
```
> 说明:导入商品和更新商品使用的是同一个接口。
## 查询导入/更新商品状态
用于查询导入或更新商品的结果,当导入或更新商品失败时,若为系统错误可进行重试;若为其他错误,请排查解决后进行重试。
```php
$status_ticket = '115141102647330200';
$result = $app->goods->status($status_ticket);
// $result:
//{
// "errcode": 0,
// "errmsg": "ok",
// "result": {
// "succ_cnt": 2,
// "fail_cnt": 0,
// "total_cnt": 2,
// "progress": "100.00%",
// "statuses": [
// {
// "pid": "pid001",
// "ret": 0,
// "err_msg": "success",
// "err_msg_zh_cn": "成功"
// },
// {
// "pid": "pid002",
// "ret": 0,
// "err_msg": "success",
// "err_msg_zh_cn": "成功"
// }
// ]
// }
//}
```
## 获取单个商品信息
使用该接口获取已导入的商品信息,供验证信息及抽查导入情况使用。
```php
$pid = 'pid001';
$app->goods->get($pid);
```
> 返回结果中的 `product` 字段内容与 `导入商品接口` 字段一致,导入时未设置的值有可能获取时仍会返回,但显示为空
## 分页获取商品信息
使用该接口可获取已导入的全量商品信息,供全量验证信息使用。
```php
$context = ''; // page 为 1 时传空即可。当 page 大于 1 时必填,填入上一次访问本接口返回的 page_context。
$page = 1; // 页码
$size = 10; // 每页数据大小,目前限制为100以内,注意一次全量验证过程中该参数的值需保持不变
$app->goods->list($context, $page, $size);
```
> 返回结果中的 `product` 字段内容与 `导入商品接口` 字段一致,导入时未设置的值有可能获取时仍会返回,但显示为空。
> `page_context` 字段用于获取下一页数据时使用。
================================================
FILE: docs/src/4.x/official-account/index.md
================================================
## 公众号
公众号的各模块相对比较统一,用法如下:
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'wx3cf0f39249eb0exx',
'secret' => 'f1c242f4f28f735d4687abb469072axx',
// 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
'response_type' => 'array',
//...
];
$app = Factory::officialAccount($config);
```
`$app` 在所有相关公众号的文档都是指 `Factory::officialAccount` 得到的实例,就不在每个页面单独写了。
================================================
FILE: docs/src/4.x/official-account/material.md
================================================
# 素材管理
在微信里的图片,音乐,视频等等都需要先上传到微信服务器作为素材才可以在消息中使用。
### 上传图片
> 注意:微信图片上传服务有敏感检测系统,图片内容如果含有敏感内容,如色情,商品推广,虚假信息等,上传可能失败。
```php
$result = $app->material->uploadImage("/path/to/your/image.jpg");
// {
// "media_id":MEDIA_ID,
// "url":URL
// }
```
> `url` 只有上传图片素材有返回值。
### 上传语音
语音 **大小不超过 5M**,**长度不超过 60 秒**,支持 `mp3/wma/wav/amr` 格式。
```php
$result = $app->material->uploadVoice("/path/to/your/voice.mp3");
// {
// "media_id":MEDIA_ID,
// }
```
### 上传视频
```php
$result = $app->material->uploadVideo("/path/to/your/video.mp4", "视频标题", "视频描述");
// {
// "media_id":MEDIA_ID,
// }
```
### 上传缩略图
用于视频封面或者音乐封面。
```php
$result = $app->material->uploadThumb("/path/to/your/thumb.jpg");
// {
// "media_id":MEDIA_ID,
// }
```
### 上传图文消息
```php
use EasyWeChat\Kernel\Messages\Article;
// 上传单篇图文
$article = new Article([
'title' => 'xxx',
'thumb_media_id' => $mediaId,
//...
]);
$app->material->uploadArticle($article);
// 或者多篇图文
$app->material->uploadArticle([$article, $article2, ...]);
```
### 修改图文消息
有三个参数:
> - `$mediaId` 要更新的文章的 `mediaId`
> - `$article` 文章内容,`Article` 实例或者 全字段数组
> - `$index` 要更新的文章在图文消息中的位置(多图文消息时,此字段才有意义,单图片忽略此参数),第一篇为 0;
```php
$result = $app->material->updateArticle($mediaId, new Article(...));
// or
$result = $app->material->updateArticle($mediaId, [
'title' => 'EasyWeChat 4.0 发布了!',
'thumb_media_id' => 'qQFxUQGO21Li4YrSn3MhnrqtRp9Zi3cbM9uBsepvDmE', // 封面图片 mediaId
'author' => 'overtrue', // 作者
'show_cover' => 1, // 是否在文章内容显示封面图片
'digest' => '这里是文章摘要',
'content' => '这里是文章内容,你可以放很长的内容',
'source_url' => 'https://easywechat.com',
]);
// 指定更新多图文中的第 2 篇
$result = $app->material->updateArticle($mediaId, new Article(...), 1); // 第 2 篇
```
### 上传图文消息图片
返回值中 url 就是上传图片的 URL,可用于后续群发中,放置到图文消息中。
```php
$result = $app->material->uploadArticleImage($path);
//{
// "url": "http://mmbiz.qpic.cn/mmbiz/gLO17UPS6FS2xsypf378iaNhWacZ1G1UplZYWEYfwvuU6Ont96b1roYsCNFwaRrSaKTPCUdBK9DgEHicsKwWCBRQ/0"
//}
```
### 获取永久素材
```php
$resource = $app->material->get($mediaId);
```
如果请求的素材为图文消息,则响应如下:
```json
{
"news_item": [
{
"title":TITLE,
"thumb_media_id"::THUMB_MEDIA_ID,
"show_cover_pic":SHOW_COVER_PIC(0/1),
"author":AUTHOR,
"digest":DIGEST,
"content":CONTENT,
"url":URL,
"content_source_url":CONTENT_SOURCE_URL
},
//多图文消息有多篇文章
]
}
```
如果返回的是视频消息素材,则内容如下:
```json
{
"title": TITLE,
"description": DESCRIPTION,
"down_url": DOWN_URL
}
```
其他类型的素材消息,则响应为 `EasyWeChat\Kernel\Http\StreamResponse` 实例,开发者可以自行保存为文件。例如
```php
$stream = $app->material->get($mediaId);
if ($stream instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
// 以内容 md5 为文件名
$stream->save('保存目录');
// 自定义文件名,不需要带后缀
$stream->saveAs('保存目录', '文件名');
}
```
### 获取永久素材列表
> - `$type` 素材的类型,图片(`image`)、视频(`video`)、语音 (`voice`)、图文(`news`)
> - `$offset` 从全部素材的该偏移位置开始返回,可选,默认 `0`,0 表示从第一个素材 返回
> - `$count` 返回素材的数量,可选,默认 `20`, 取值在 1 到 20 之间
```php
$app->material->list($type, $offset, $count);
```
示例:
```php
$list = $app->material->list('image', 0, 10);
```
图片、语音、视频 等类型的返回如下
```json
{
"total_count": TOTAL_COUNT,
"item_count": ITEM_COUNT,
"item": [
{
"media_id": MEDIA_ID,
"name": NAME,
"update_time": UPDATE_TIME,
"url": URL
}
//可能会有多个素材
]
}
```
永久图文消息素材列表的响应如下:
```json
{
"total_count": TOTAL_COUNT,
"item_count": ITEM_COUNT,
"item": [
{
"media_id": MEDIA_ID,
"content": {
"news_item": [
{
"title": TITLE,
"thumb_media_id": THUMB_MEDIA_ID,
"show_cover_pic": SHOW_COVER_PIC(0 / 1),
"author": AUTHOR,
"digest": DIGEST,
"content": CONTENT,
"url": URL,
"content_source_url": CONTETN_SOURCE_URL
}
//多图文消息会在此处有多篇文章
]
},
"update_time": UPDATE_TIME
}
//可能有多个图文消息item结构
]
}
```
### 获取素材计数
```php
$stats = $app->material->stats();
// {
// "voice_count":COUNT,
// "video_count":COUNT,
// "image_count":COUNT,
// "news_count":COUNT
// }
```
### 删除永久素材
```php
$app->material->delete($mediaId);
```
### 文章预览
文章预览请参阅 “消息群发” 章节。
================================================
FILE: docs/src/4.x/official-account/menu.md
================================================
# 自定义菜单
## 读取(查询)已设置菜单
```php
$list = $app->menu->list();
```
## 获取当前菜单
```php
$current = $app->menu->current();
```
## 添加菜单
### 添加普通菜单
```php
$buttons = [
[
"type" => "click",
"name" => "今日歌曲",
"key" => "V1001_TODAY_MUSIC"
],
[
"name" => "菜单",
"sub_button" => [
[
"type" => "view",
"name" => "搜索",
"url" => "http://www.soso.com/"
],
[
"type" => "view",
"name" => "视频",
"url" => "http://v.qq.com/"
],
[
"type" => "click",
"name" => "赞一下我们",
"key" => "V1001_GOOD"
],
],
],
];
$app->menu->create($buttons);
```
以上将会创建一个普通菜单。
### 添加个性化菜单
与创建普通菜单不同的是,需要在 `create()` 方法中将个性化匹配规则作为第二个参数传进去:
```php
$buttons = [
// ...
];
$matchRule = [
"tag_id" => "2",
"sex" => "1",
"country" => "中国",
"province" => "广东",
"city" => "广州",
"client_platform_type" => "2",
"language" => "zh_CN"
];
$app->menu->create($buttons, $matchRule);
```
## 删除菜单
有两种删除方式,一种是**全部删除**,另外一种是**根据菜单 ID 来删除**(删除个性化菜单时用,ID 从查询接口获取):
```php
$app->menu->delete(); // 全部
$app->menu->delete($menuId);
```
## 测试个性化菜单
```php
$app->menu->match($userId);
```
> `$userId` 可以是粉丝的 OpenID,也可以是粉丝的微信号。
返回 `$menu` 与指定的 `$userId` 匹配的菜单项。
================================================
FILE: docs/src/4.x/official-account/message-transfer.md
================================================
# 多客服消息转发
多客服的消息转发绝对是超级的简单,转发的消息类型为 `transfer`:
```php
use EasyWeChat\Kernel\Messages\Transfer;
// 转发收到的消息给客服
$app->server->push(function($message) {
return new Transfer();
});
$response = $app->server->serve();
```
当然,你也可以指定转发给某一个客服:
```php
use EasyWeChat\Kernel\Messages\Transfer;
$app->server->push(function($message) {
return new Transfer($account);
});
```
================================================
FILE: docs/src/4.x/official-account/messages.md
================================================
# 消息
我把微信的 API 里的所有“消息”都按类型抽象出来了,也就是说,你不用区分它是回复消息还是主动推送消息,免去了你去手动拼装微信的 XML 以及乱七八糟命名不统一的 JSON 了。
在阅读以下内容时请忽略是 **接收消息** 还是 **回复消息**,后面我会给你讲它们的区别。
## 消息类型
消息分为以下几种:`文本`、`图片`、`视频`、`声音`、`链接`、`坐标`、`图文`、`文章` 和一种特殊的 `原始消息`。
另外还有一种特殊的消息类型:**素材消息**,用于群发或者客服时发送已有素材用。
> 注意:回复消息与客服消息里的图文类型为:**图文**,群发与素材中的图文为**文章**
所有的消息类都在 `EasyWeChat\Kernel\Messages` 这个命名空间下, 下面我们来分开讲解:
### 文本消息
属性列表:
> - `content` 文本内容
```php
use EasyWeChat\Kernel\Messages\Text;
$text = new Text('您好!overtrue。');
// or
$text = new Text();
$text->content = '您好!overtrue。';
// or
$text = new Text();
$text->setAttribute('content', '您好!overtrue。');
```
### 图片消息
属性列表:
```
- media_id 媒体资源 ID
```
```php
use EasyWeChat\Kernel\Messages\Image;
$image = new Image($mediaId);
```
### 视频消息
属性列表:
> - `title` 标题
> - `description` 描述
> - `media_id` 媒体资源 ID
> - `thumb_media_id` 封面资源 ID
```php
use EasyWeChat\Kernel\Messages\Video;
$video = new Video($mediaId, [
'title' => $title,
'description' => '...',
]);
```
### 声音消息
属性列表:
> - `media_id` 媒体资源 ID
```php
use EasyWeChat\Kernel\Messages\Voice;
$voice = new Voice($mediaId);
```
### 链接消息
> 复链接消息
### 坐标消息
> 复坐标消息
### 图文消息
图文消息分为 `NewsItem` 与 `News`,`NewsItem` 为图文内容条目。
> ,被动回复消息与客服消息接口的图文消息类型中图文数目只能为一条](https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&announce_id=115383153198yAvN&version=&lang=zh_CN&token=)
`NewsItem` 属性:
> - `title` 标题
> - `description` 描述
> - `image` 图片链接
> - `url` 链接 URL
```php
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
$items = [
new NewsItem([
'title' => $title,
'description' => '...',
'url' => $url,
'image' => $image,
// ...
]),
];
$news = new News($items);
```
### 文章
属性列表:
> - `title` 标题
> - `author` 作者
> - `content` 具体内容
> - `thumb_media_id` 图文消息的封面图片素材 id(必须是永久 mediaID)
> - `digest` 图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空
> - `source_url` 来源 URL
> - `show_cover` 是否显示封面,0 为 false,即不显示,1 为 true,即显示
```php
use EasyWeChat\Kernel\Messages\Article;
$article = new Article([
'title' => 'EasyWeChat',
'author' => 'overtrue',
'content' => 'EasyWeChat 是一个开源的微信 SDK,它... ...',
// ...
]);
// or
$article = new Article();
$article->title = 'EasyWeChat';
$article->author = 'overtrue';
$article->content = '微信 SDK ...';
// ...
```
### 素材消息
素材消息用于群发与客服消息时使用。
> 素材消息不支持被动回复,如需被动回复素材消息,首先组装后,再 News 方法返回。
属性就一个:`media_id`。
在构造时有两个参数:
> - `$type` 素材类型,目前只支持:`mpnews`、 `mpvideo`、`voice`、`image` 等。
> - `$mediaId` 素材 ID,从接口查询或者上传后得到。
```php
use EasyWeChat\Kernel\Messages\Media;
$media = new Media($mediaId, 'mpnews');
```
以上呢,是所有微信支持的基本消息类型。
> 需要注意的是,你不需要关心微信的消息字段叫啥,因为这里我们使用了更标准的命名,然后最终在中间做了转换,所以你不需要关注。
### 原始消息
原始消息是一种特殊的消息,它的场景是:**你不想使用其它消息类型,你想自己手动拼消息**。比如,回复消息时,你想自己拼 XML,那么你就直接用它就可以了:
```php
use EasyWeChat\Kernel\Messages\Raw;
$message = new Raw('
12345678
');
```
比如,你要用于客服消息(客服消息是 JSON 结构):
```php
use EasyWeChat\Kernel\Messages\Raw;
$message = new Raw('{
"touser":"OPENID",
"msgtype":"text",
"text":
{
"content":"Hello World"
}
}');
```
总之,就是直接写微信接口要求的格式内容就好,此类型消息在 SDK 中不存在转换行为,所以请注意不要写错格式。
## 在 SDK 中使用消息
### 在服务端回复消息
在 [服务端](server) 一节中,我们讲了回复消息的写法:
```php
// ... 前面部分省略
$app->server->push(function ($message) {
return "您好!欢迎关注我!";
});
$response = $server->serve();
```
上面 `return` 了一句普通的文本内容,这里只是为了方便大家,实际上最后会有一个隐式转换为 `Text` 类型的动作。
如果你要回复其它类型的消息,就需要返回一个具体的实例了,比如回复一个图片类型的消息:
```php
use EasyWeChat\Kernel\Messages\Image;
// ...
$app->server->push(function ($message) {
return new Image('media-id');
});
// ...
```
#### 回复多图文消息
> ,被动回复消息与客服消息接口的图文消息类型中图文数目只能为一条](https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&announce_id=115383153198yAvN&version=&lang=zh_CN&token=)
多图文消息其实就是单图文消息的一个数组而已了:
```php
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
// ...
$app->server->push(function ($message) {
$news = new NewsItem(...);
return new News([$news]);
});
// ...
```
### 作为客服消息发送
在客服消息里的使用也一样,都是直接传入消息实例即可:
```php
use EasyWeChat\Kernel\Messages\Text;
$message = new Text('Hello world!');
$result = $app->customer_service->message($message)->to($openId)->send();
//...
```
#### 发送多图文消息
> ,被动回复消息与客服消息接口的图文消息类型中图文数目只能为一条](https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&announce_id=115383153198yAvN&version=&lang=zh_CN&token=)
多图文消息其实就是单图文消息组成的一个 News 对象而已:
```php
$news1 = new NewsItem(...);
$news = new News([$news1]);
$app->customer_service->message($news)->to($openId)->send();
```
### 群发消息
请参考:[群发消息](broadcasting)
## 消息转发给客服系统
参见:[多客服消息转发](message-transfer)
================================================
FILE: docs/src/4.x/official-account/oauth.md
================================================
# 网页授权
## 关于 OAuth2.0
OAuth 是一个关于授权(authorization)的开放网络标准,在全世界得到广泛应用,目前的版本是 2.0 版。
> 摘自:[RFC 6749](https://datatracker.ietf.org/doc/rfc6749/?include_text=1)
步骤解释:
(A)用户打开客户端以后,客户端要求用户给予授权。
(B)用户同意给予客户端授权。
(C)客户端使用上一步获得的授权,向认证服务器申请令牌。
(D)认证服务器对客户端进行认证以后,确认无误,同意发放令牌。
(E)客户端使用令牌,向资源服务器申请获取资源。
(F)资源服务器确认令牌无误,同意向客户端开放资源。
关于 OAuth 协议我们就简单了解到这里,如果还有不熟悉的同学,请 [Google 相关资料](https://www.google.com.hk/?gws_rd=ssl#safe=strict&q=OAuth2)
## 微信 OAuth
在微信里的 OAuth 其实有两种:[公众平台网页授权获取用户信息](http://mp.weixin.qq.com/wiki/9/01f711493b5a02f24b04365ac5d8fd95.html)、[开放平台网页登录](https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN)。
它们的区别有两处,授权地址不同,`scope` 不同。
> - **公众平台网页授权获取用户信息**
**授权 URL**: `https://open.weixin.qq.com/connect/oauth2/authorize`
**Scopes**: `snsapi_base` 与 `snsapi_userinfo`
> - **开放平台网页登录**
**授权 URL**: `https://open.weixin.qq.com/connect/qrconnect`
**Scopes**: `snsapi_login`
他们的逻辑都一样:
1. 用户尝试访问一个我们的业务页面,例如: `/user/profile`
2. 如果用户已经登录,则正常显示该页面
3. 系统检查当前访问的用户并未登录(从 session 或者其它方式检查),则跳转到**跳转到微信授权服务器**(上面的两种中一种**授权 URL** ),并告知微信授权服务器我的**回调 URL(redirect_uri=callback.php)**,此时用户看到蓝色的授权确认页面(`scope` 为 `snsapi_base` 时不显示)
4. 用户点击确定完成授权,浏览器跳转到**回调 URL**: `callback.php` 并带上 `code`: `?code=CODE&state=STATE`。
5. 在 `callback.php` 中得到 `code` 后,通过 `code` 再次向微信服务器请求得到 **网页授权 access_token** 与 `openid`
6. 你可以选择拿 `openid` 去请求 API 得到用户信息(可选)
7. 将用户信息写入 SESSION。
8. 跳转到第 3 步写入的 `target_url` 页面(`/user/profile`)。
> 看懵了?没事,使用 SDK,你不用管这么多。:smile:
>
> 注意,上面的第 3 步:redirect_uri=callback.php 实际上我们会在 `callback.php` 后面还会带上授权目标页面 `user/profile`,所以完整的 `redirect_uri` 应该是下面的这样的 PHP 去拼出来:`'redirect_uri='.urlencode('callback.php?target=user/profile')`
> 结果:redirect_uri=callback.php%3Ftarget%3Duser%2Fprofile
## 逻辑组成
从上面我们所描述的授权流程来看,我们至少有 3 个页面:
1. **业务页面**,也就是需要授权才能访问的页面。
2. **发起授权页**,此页面其实可以省略,可以做成一个中间件,全局检查未登录就发起授权。
3. **授权回调页**,接收用户授权后的状态,并获取用户信息,写入用户会话状态(SESSION)。
## 开始之前
在开始之前请一定要记住,先登录公众号后台,找到**边栏 “开发”** 模块下的 **“接口权限”**,点击 **“网页授权获取用户基本信息”** 后面的修改,添加你的网页授权域名。
> 如果你的授权地址为:`http://www.abc.com/xxxxx`,那么请填写 `www.abc.com`,也就是说请填写与网址匹配的域名,前者如果填写 `abc.com` 是通过不了的。
## SDK 中 OAuth 模块的 API
在 SDK 中,我们使用名称为 `oauth` 的模块来完成授权服务,我们主要用到以下两个 API:
### 发起授权
```php
$response = $app->oauth->scopes(['snsapi_userinfo'])
->redirect();
```
当你的应用是分布式架构且没有会话保持的情况下,你需要自行设置请求对象以实现会话共享。比如在 [Laravel](http://laravel.com) 框架中支持 Session 储存在 Redis 中,那么需要这样:
```php
$response = $app->oauth->scopes(['snsapi_userinfo'])
->setRequest($request)
->redirect();
//回调后获取user时也要设置$request对象
//$user = $app->oauth->setRequest($request)->user();
```
当然你也可以在发起授权的时候指定回调 URL,比如设置回调 URL 为当前页面:
```php
$response = $app->oauth->scopes(['snsapi_userinfo'])
->redirect($request->fullUrl());
```
它的返回值 `$response` 是一个 [Symfony\Component\HttpFoundation\RedirectResponse](http://api.symfony.com/3.0/Symfony/Component/HttpFoundation/RedirectResponse.html) 实例。
你可以选择在框架中做一些正确的响应,比如在 [Laravel](http://laravel.com) 框架中控制器方法是要求返回响应值的,那么你就直接:
```php
return $response;
```
在有的框架 (比如 yii2) 中是直接 `echo` 或者 `$this->display()` 这种的时候,你就直接:
```php
$response->send(); // Laravel 里请使用:return $response;
```
### 获取已授权用户
```php
$user = $app->oauth->user();
// $user 可以用的方法:
// $user->getId(); // 对应微信的 OPENID
// $user->getNickname(); // 对应微信的 nickname
// $user->getName(); // 对应微信的 nickname
// $user->getAvatar(); // 头像网址
// $user->getOriginal(); // 原始API返回的结果
// $user->getToken(); // access_token, 比如用于地址共享时使用
```
返回的 `$user` 是 [Overtrue\Socialite\User](https://github.com/overtrue/socialite/blob/master/src/User.php) 对象,你可以从该对象拿到[更多的信息](https://github.com/overtrue/socialite#user-interface)。
> r`里没有`openid`, `$user->id` 便是 `openid`.
> 如果你想拿微信返回给你的原样的全部信息,请使用:$user->getOriginal();
当 `scope` 为 `snsapi_base` 时 `$oauth->user();` 对象里只有 `id`,没有其它信息。
## 网页授权实例
我们这里来用原生 PHP 写法举个例子,`oauth_callback` 是我们的授权回调 URL (未 urlencode 编码的 URL), `user/profile` 是我们需要授权才能访问的页面,它的 PHP 代码如下:
```php
// http://easywechat.com/user/profile
[
'scopes' => ['snsapi_userinfo'],
'callback' => '/oauth_callback',
],
// ..
];
$app = Factory::officialAccount($config);
$oauth = $app->oauth;
// 未登录
if (empty($_SESSION['wechat_user'])) {
$_SESSION['target_url'] = 'user/profile';
return $oauth->redirect();
// 这里不一定是return,如果你的框架action不是返回内容的话你就得使用
// $oauth->redirect()->send();
}
// 已经登录过
$user = $_SESSION['wechat_user'];
// ...
```
授权回调页:
```php
// http://easywechat.com/oauth_callback
oauth;
// 获取 OAuth 授权结果用户信息
$user = $oauth->user();
$_SESSION['wechat_user'] = $user->toArray();
$targetUrl = empty($_SESSION['target_url']) ? '/' : $_SESSION['target_url'];
header('location:'. $targetUrl); // 跳转到 user/profile
```
上面的例子呢都是基于 `$_SESSION` 来保持会话的,在微信客户端中,你可以结合 COOKIE 来存储,但是有效期平台不一样时间也不一样,好像 Android 的失效会快一些,不过基本也够用了。
================================================
FILE: docs/src/4.x/official-account/poi.md
================================================
# 门店
## 创建门店
用 POI 接口新建门店时所使用的图片 url 必须为微信自己域名的 url,因此需要先用上传图片接 口上传图片并获取 url,再创建门店。上传的图片限制文件大小限制 1MB,支持 JPG 格式,图片接口请参考:[临时素材](../basic-services/media.md)
```php
$app->poi->create($baseInfo);
```
> - `$baseInfo` 为门店的基本信息数组
示例:
```php
"33788392",
"business_name" => "麦当劳",
"branch_name" => "艺苑路店",
"province" => "广东省",
"city" => "广州市",
"district" => "海珠区",
"address" => "艺苑路 11 号",
"telephone" => "020-12345678",
"categories" => array("美食,快餐小吃"),
"offset_type" => 1,
"longitude" => 115.32375,
"latitude" => 25.097486,
"photo_list" => array(
array("photo_url" => "https://easywechat.com"),
array("photo_url" => "https://easywechat.com"),
),
"recommend" => "麦辣鸡腿堡套餐,麦乐鸡,全家桶",
"special" => "免费 wifi,外卖服务",
"introduction" => "麦当劳是全球大型跨国连锁餐厅,1940 年创立于美国,在世界上大约拥有 3 万间分店。主要售卖汉堡包,以及薯条、炸鸡、汽水、冰品、沙拉、水果等 快餐食品",
"open_time" => "8:00-20:00",
"avg_price" => 35,
);
$result = $app->poi->create($info); // true or exception
```
> 注意:新创建的门店在审核通过后,会以事件形式推送给商户填写的回调 URL
## 获取指定门店信息
```php
$app->poi->get($poiId);
```
> - `$poiId` 为门店 ID
示例:
```php
$info = $app->poi->get(271262077);
```
## 获取门店列表
```php
$app->poi->list($begin, $limit);// begin:0, limit:10
```
> - `$begin` 就是查询起点,`MySQL` 里的 `offset`;
> - `$limit` 查询条数,同 `MySQL` 里的 `limit`;
> 两参数均可选
示例:
```php
$pois = $app->poi->list(0, 2);// 取2条记录
//
//[
// {
// "sid": "100",
// "poi_id": "271864249",
// "business_name": "麦当劳",
// "branch_name": "艺苑路店",
// "address": "艺苑路 11 号",
// "available_state": 3
// },
// {
// "sid": "101",
// "business_name": "麦当劳",
// "branch_name": "赤岗路店",
// "address": "赤岗路 102 号",
// "available_state": 4
// }
//]
```
## 修改门店信息
商户可以通过该接口,修改门店的服务信息,包括:图片列表、营业时间、推荐、特色服务、简 介、人均价格、电话 7 个字段。目前基础字段包括(名称、坐标、地址等不可修改)。
```php
$app->poi->update($poiId, $data);
```
> - `$poiId` 为门店 ID
> - `$data` 需要更新的部分数据,**若有填写内容则为覆盖更新,若无内容则视为不 修改,维持原有内容。photo_list 字段为全列表覆盖,若需要增加图片,需将之前图片同样放入 list 中,在其后增加新增图片。如:已有 A、B、C 三张图片,又要增加 D、E 两张图,则需要调 用该接口,photo_list 传入 A、B、C、D、E 五张图片的链接。**
示例:
```php
$data = array(
"telephone" => "020-12345678",
"recommend" => "麦辣鸡腿堡套餐,麦乐鸡,全家桶",
//...
);
$res = $app->poi->update(271262077, $data); //true or exception
```
## 删除门店
```php
$app->poi->delete($poiId);
```
示例:
```php
$app->poi->delete(271262077);// true or exception
```
================================================
FILE: docs/src/4.x/official-account/reply.md
================================================
# 自动回复
## 获取当前设置的回复规则
```php
$app->auto_reply->current();
```
================================================
FILE: docs/src/4.x/official-account/semantic.md
================================================
# 语义理解
> 貌似此接口已经下线,调用无正确返回值
+ `query($keyword, $categories, $optional = [])` 语义理解:
+ `$keyword` 为关键字
+ `$categories` 需要使用的服务类型,多个用 “,” 隔开字符串,不能为空;
+ `$optional` 为其它属性:
+ `latitude` `float` 纬度坐标,与经度同时传入;与城市二选一传入
+ `longitude` `float` 经度坐标,与纬度同时传入;与城市二选一传入
+ `city` `string` 城市名称,与经纬度二选一传入
+ `region` `string` 区域名称,在城市存在的情况下可省;与经纬度二选一传入
+ `uid` `string` 用户唯一id(非开发者id),用户区分公众号下的不同用户(建议填入用户openid),如果为空,则无法使用上下文理解功能。appid和uid同时存在的情况下,才可以使用上下文理解功能。
> 注:单类别意图比较明确,识别的覆盖率比较大,所以如果只要使用特定某个类别,建议将 category 只设置为该类别。
示例:
```php
$result = $app->semantic->query('查一下明天从北京到上海的南航机票', "flight,hotel", array('city' => '北京', 'uid' => '123456'));
// 查询参数:
// {
// "query":"查一下明天从北京到上海的南航机票",
// "city":"北京",
// "category": "flight,hotel",
// "appid":"wxaaaaaaaaaaaaaaaa",
// "uid":"123456"
// }
```
返回值示例:
```json
{
"errcode":0,
"query":"查一下明天从北京到上海的南航机票",
"type":"flight",
"semantic":{
"details":{
"start_loc":{
"type":"LOC_CITY",
"city":"北京市",
"city_simple":"北京",
"loc_ori":"北京"
},
"end_loc": {
"type":"LOC_CITY",
"city":"上海市",
"city_simple":"上海",
"loc_ori":"上海"
},
"start_date": {
"type":"DT_ORI",
"date":"2014-03-05",
"date_ori":"明天"
},
"airline":"中国南方航空公司"
},
"intent":"SEARCH"
}
```
================================================
FILE: docs/src/4.x/official-account/server.md
================================================
# 服务端
我们在入门小教程一节以服务端为例讲解了一个基本的消息的处理,这里就不再讲服务器验证的流程了,请直接参考前面的入门实例即可。
服务端的作用呢,在整个微信开发中主要是负责 **[接收用户发送过来的消息](http://mp.weixin.qq.com/wiki/10/79502792eef98d6e0c6e1739da387346.html)**,还有 **[用户触发的一系列事件](http://mp.weixin.qq.com/wiki/2/5baf56ce4947d35003b86a9805634b1e.html)**。
首先我们得理清消息与事件的回复逻辑,当你收到用户消息后(消息由微信服务器推送到你的服务器),在你对消息进行一些处理后,不管是选择回复一个消息还是什么不都回给用户,你也应该给微信服务器一个 “答复”,如果是选择回复一条消息,就直接返回一个消息xml就好,如果选择不作任何回复,你也得回复一个空字符串或者字符串 `SUCCESS`(不然用户就会看到 `该公众号暂时无法提供服务`)。
## 基本使用
在 SDK 中使用 `$app->server->push(callable $callback)` 来设置消息处理器:
```php
$app->server->push(function ($message) {
// $message['FromUserName'] // 用户的 openid
// $message['MsgType'] // 消息类型:event, text....
return "您好!欢迎使用 EasyWeChat";
});
// 在 laravel 中:
$response = $app->server->serve();
// $response 为 `Symfony\Component\HttpFoundation\Response` 实例
// 对于需要直接输出响应的框架,或者原生 PHP 环境下
$response->send();
// 而 laravel 中直接返回即可:
return $response;
```
这里我们使用 `push` 传入了一个 **闭包([Closure](http://php.net/manual/en/class.closure.php))**,该闭包接收一个参数 `$message` 为消息对象(类型取决于你的配置中 `response_type`),你可以在全局消息处理器中对消息类型进行筛选:
```php
$app->server->push(function ($message) {
switch ($message['MsgType']) {
case 'event':
return '收到事件消息';
break;
case 'text':
return '收到文字消息';
break;
case 'image':
return '收到图片消息';
break;
case 'voice':
return '收到语音消息';
break;
case 'video':
return '收到视频消息';
break;
case 'location':
return '收到坐标消息';
break;
case 'link':
return '收到链接消息';
break;
case 'file':
return '收到文件消息';
// ... 其它消息
default:
return '收到其它消息';
break;
}
// ...
});
```
当然,因为这里 `push` 接收一个 [`callable`](http://php.net/manual/zh/language.types.callable.php) 的参数,所以你不一定要传入一个 Closure 闭包,你可以选择传入一个函数名,一个 `[$class, $method]` 或者 `Foo::bar` 这样的类型。
某些情况,我们需要直接使用 `$message` 参数,那么怎么在 `push` 的闭包外调用呢?
```php
$message = $server->getMessage();
```
> 注意:`$message` 的类型取决于你的配置中 `response_type`
## 注册多个消息处理器
有时候你可能需要对消息记日志,或者一系列的自定义操作,你可以注册多个 handler:
```php
$app->server->push(MessageLogHandler::class);
$app->server->push(MessageReplyHandler::class);
$app->server->push(OtherHandler::class);
$app->server->push(...);
```
1. 最后一个非空返回值将作为最终应答给用户的消息内容,如果中间某一个 handler 返回值 false, 则将终止整个调用链,不会调用后续的 handlers。
2. 传入的自定义 Handler 类需要实现 `\EasyWeChat\Kernel\Contracts\EventHandlerInterface`。
## 注册指定消息类型的消息处理器
我们想对特定类型的消息应用不同的处理器,可以在第二个参数传入类型筛选:
> 注意,第二个参数必须是 `\EasyWeChat\Kernel\Messages\Message` 类的常量。
```php
use EasyWeChat\Kernel\Messages\Message;
$app->server->push(ImageMessageHandler::class, Message::IMAGE); // 图片消息
$app->server->push(TextMessageHandler::class, Message::TEXT); // 文本消息
// 同时处理多种类型的处理器
$app->server->push(MediaMessageHandler::class, Message::VOICE|Message::VIDEO|Message::SHORT_VIDEO); // 当消息为 三种中任意一种都可触发
```
## 请求消息的属性
当你接收到用户发来的消息时,可能会提取消息中的相关属性,参考:
请求消息基本属性(以下所有消息都有的基本属性):
>> - `ToUserName` 接收方帐号(该公众号 ID)
>> - `FromUserName` 发送方帐号(OpenID, 代表用户的唯一标识)
>> - `CreateTime` 消息创建时间(时间戳)
>> - `MsgId` 消息 ID(64位整型)
### 文本:
> - `MsgType` text
> - `Content` 文本消息内容
### 图片:
> - `MsgType` image
> - `MediaId` 图片消息媒体id,可以调用多媒体文件下载接口拉取数据。
> - `PicUrl` 图片链接
### 语音:
> - `MsgType` voice
> - `MediaId` 语音消息媒体id,可以调用多媒体文件下载接口拉取数据。
> - `Format` 语音格式,如 amr,speex 等
> - `Recognition` * 开通语音识别后才有
> 识别后,用户每次发送语音给公众号时,微信会在推送的语音消息XML数据包中,增加一个 `Recongnition` 字段
### 视频:
> - `MsgType` video
> - `MediaId` 视频消息媒体id,可以调用多媒体文件下载接口拉取数据。
> - `ThumbMediaId` 视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。
### 小视频:
> - `MsgType` shortvideo
> - `MediaId` 视频消息媒体id,可以调用多媒体文件下载接口拉取数据。
> - `ThumbMediaId` 视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。
### 事件:
> - `MsgType` event
> - `Event` 事件类型 (如:subscribe(订阅)、unsubscribe(取消订阅) ..., CLICK 等)
#### 扫描带参数二维码事件
> - `EventKey` 事件KEY值,比如:qrscene_123123,qrscene_为前缀,后面为二维码的参数值
> - `Ticket` 二维码的 ticket,可用来换取二维码图片
#### 上报地理位置事件
> - `Latitude` 23.137466 地理位置纬度
> - `Longitude` 113.352425 地理位置经度
> - `Precision` 119.385040 地理位置精度
#### 自定义菜单事件
> - `EventKey` 事件KEY值,与自定义菜单接口中KEY值对应,如:CUSTOM_KEY_001, www.qq.com
### 地理位置:
> - `MsgType` location
> - `Location_X` 地理位置纬度
> - `Location_Y` 地理位置经度
> - `Scale` 地图缩放大小
> - `Label` 地理位置信息
### 链接:
> - `MsgType` link
> - `Title` 消息标题
> - `Description` 消息描述
> - `Url` 消息链接
### 文件:
`MsgType` file
`Title` 文件名
`Description` 文件描述,可能为null
`FileKey` 文件KEY
`FileMd5` 文件MD5值
`FileTotalLen` 文件大小,单位字节
## 回复消息
回复的消息可以为 `null`,此时 SDK 会返回给微信一个 "SUCCESS",你也可以回复一个普通字符串,比如:`欢迎关注 overtrue.`,此时 SDK 会对它进行一个封装,产生一个 [`EasyWeChat\Kernel\Messages\Text`](https://github.com/EasyWeChat/message/blob/master/src/Kernel/Messages/Text.php) 类型的消息并在最后的 `$app->server->serve();` 时生成对应的消息 XML 格式。
如果你想返回一个自己手动拼的原生 XML 格式消息,请返回一个 [`EasyWeChat\Kernel\Messages\Raw`](https://github.com/EasyWeChat/message/blob/master/src/Kernel/Messages/Raw.php) 实例即可。
## 消息转发给客服系统
参见:[多客服消息转发](message-transfer)
关于消息的使用,请参考 [`消息`](messages) 章节。
================================================
FILE: docs/src/4.x/official-account/shake-around.md
================================================
# 摇一摇周边
摇一摇周边是微信在线下的全新功能, 为线下商户提供近距离连接用户的能力, 并支持线下商户向周边用户提供个性化营销、互动及信息推荐等服务。
## 获取实例
```php
$shakearound = $app->shake_around;
```
## 说明
> 特别提醒:
1、下述所有的接口调用的方法参数都要严格按照方法参数前的类型传入相应类型的实参,否则可能会得到非预期的结果。
2、涉及需要传入设备id($deviceIdentifier)的参数时,该参数是一个以 `device_id` 或包含 `uuid` `major` `minor` 为key的关联数组。
3、涉及需要传入设备id列表($deviceIdentifiers)的参数时,该参数是一个二维数组,第一层为索引类型,第二层为关联类型($deviceIdentifier)。
```php
// 参数 $deviceIdentifier 的实参形式:
['device_id' => 10097]
// 或
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12102,
]
// 参数$deviceIdentifiers的实参形式:
[
['device_id' => 10097],
['device_id' => 10098],
]
// 或
[
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12102,
],
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12103,
]
]
```
## 开通摇一摇周边
> 提示:
若不是做 [公众号第三方平台](https://open.weixin.qq.com/cgi-bin/frame?t=home/wx_plugin_tmpl&lang=zh_CN) 开发,建议直接在微信管理后台申请开通摇一摇周边功能。
### 申请开通
申请开通摇一摇周边功能。成功提交申请请求后,工作人员会在三个工作日内完成审核。若审核不通过,可以重新提交申请请求。若是审核中,请耐心等待工作人员审核,在审核中状态不能再提交申请请求。
方法
```php
$shakearound->register($data)
```
> 注意:
1、相关资质文件的图片是使用本页面下方的素材管理的接口上传的,切勿和另一个 [素材管理](material) 接口混淆。
2、行业代码请务必传入**字符串**类型的实参,否则以数字0开头的行业代码将会被当成八进制数处理(将转换为十进制数),这可能不是期望的。
### 查询审核状态
查询已经提交的开通摇一摇周边功能申请的审核状态。在申请提交后,工作人员会在三个工作日内完成审核。
方法
```php
$shakearound->status()
```
### 获取摇一摇的设备及用户信息
获取设备信息,包括UUID、major、minor,以及距离、openID等信息。
方法
```php
$shakearound->user($ticket);
// 或者需要返回门店poi_id
$shakearound->user($ticket, true);
```
## 设备管理
### 申请设备 ID
申请配置设备所需的UUID、Major、Minor。申请成功后返回批次ID,可用返回的批次ID通过“查询设备ID申请状态”接口查询目前申请的审核状态。
一个公众账号最多可申请100000个设备ID,如需申请的设备ID数超过最大限额,请邮件至zhoubian@tencent.com,邮件格式如下:
> 标题:申请提升设备ID额度
内容:
1、公众账号名称及appid(wx开头的字符串,在mp平台可查看)
2、用途
3、预估需要多少设备ID
方法
```php
$shakearound->device->apply($data)
```
### 查询设备 ID 申请审核状态
查询设备ID申请的审核状态。若单次申请的设备ID数量小于等于500个,系统会进行快速审核;若单次申请的设备ID数量大于500个,则在三个工作日内完成审核。
方法
```php
$shakearound->device->status($applyId) // $applyId 批次ID,申请设备ID时所返回的批次ID
```
### 编辑设备信息
> 仅能修改设备的备注信息。
方法
```php
$shakearound->device->update(array $deviceIdentifier, string $comment)
```
参数
> $deviceIdentifier 设备id,设备编号device_id或UUID、major、minor的关联数组,若二者都填,则以设备编号为优先
$comment 设备的备注信息,不超过15个汉字或30个英文字母
示例
```php
$result = $shakearound->device->update(['device_id' => 10011], 'test');
// 或
$result = $shakearound->device->update(['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
], 'test');
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result['errcode']) // 0
```
### 配置设备与门店/其他公众账号门店的关联关系
关联本公众账号门店时,支持创建门店后直接关联在设备上,无需为审核通过状态,摇周边后台自动更新门店的最新信息和状态。
关联其他公众账号门店时,支持设备关联其他公众账号的门店,门店需为审核通过状态。
> 因为第三方门店不归属本公众账号,所以未保存到设备详情中,查询设备列表接口与获取摇周边的设备及用户信息接口不会返回第三方门店。
方法
```php
$shakearound->device->bindPoi(array $deviceIdentifier, $poiId)
//或者 绑定第三方
$shakearound->device->bindThirdPoi(array $deviceIdentifier, $poiId, $poiAppId)
```
参数
> $deviceIdentifier 设备 id,设备编号 device_id 或 UUID、major、minor 的关联数组,若二者都填,则以设备编号为优先
$poiId 设备关联的门店 ID,关联门店后,在门店 1KM 的范围内有优先摇出信息的机会。当值为0时,将清除设备已关联的门店 ID
$poiAppId 关联门店所归属的公众账号的 APP ID
示例
```php
// 关联本公众账号门店
$result = $shakearound->device->bindLocation(['device_id' => 10011], 1231);
// 或
$result = $shakearound->device->bindLocation([
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
], 1231);
// 关联其他公众账号门店
// wxappid 为关联门店所归属的公众账号的 APP ID
$result = $shakearound->device->bindThirdPoi(['device_id' => 10011], 1231, 'wxappid');
// 或
$result = $shakearound->device->bindThirdPoi([
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
], 1231, 'wxappid');
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
```
## 查询设备列表
查询已有的设备 ID、UUID、Major、Minor、激活状态、备注信息、关联门店、关联页面等信息。
### 根据设备id批量取回设备数据
方法
> $shakearound->device->listByIds(array $deviceIdentifiers)
参数
> $deviceIdentifiers 设备id列表
示例
```php
$result = $shakearound->device->listByIds([
['device_id' => 10097],
['device_id' => 10098],
]);
// 或
$result = $shakearound->device->listByIds([
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12102,
],
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12103,
]
]);
/* 返回结果
{
"data": {
"devices": [
{
"comment": "",
"device_id": 10097,
"major": 10001,
"minor": 12102,
"status": 1,
"last_active_time":1437276018,
"poi_id": 0,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
},
{
"comment": "",
"device_id": 10098,
"major": 10001,
"minor": 12103,
"status": 1,
"last_active_time":1437276018,
"poi_appid":"wxe3813f5d8c546fc7"
"poi_id": 123,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
}
],
"total_count": 151
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 分页批量取回设备数据
方法
```php
$shakearound->device->list(int $lastId, int $count)
```
参数
> $lastId 前一次查询列表末尾的设备编号 device_id,第一次查询 lastId 为 0
$count 待查询的设备数量,不能超过50个
示例
```php
$result = $shakearound->device->list(10097, 3);
// 返回结果同上
```
### 根据申请时的批次 ID 分页批量取回设备数据
方法
> $shakearound->device->listByApplyId(int $applyId, int $lastId, int $count)
参数
> $applyId 批次ID,申请设备ID时所返回的批次ID
$lastId 前一次查询列表末尾的设备编号device_id,第一次查询 lastId 为 0
$count 待查询的设备数量,不能超过50个
示例
```php
$result = $shakearound->device->listByApplyId(1231, 10097, 3);
// 返回结果同上
```
## 页面管理
### 新增页面
新增摇一摇出来的页面信息,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。其中,图片必须为用素材管理接口上传至微信侧服务器后返回的链接。
>
图片是使用本页面下方的素材管理的接口上传的,切勿和另一个 [素材管理](material) 接口混淆。
方法
```php
$shakearound->page->create($data)
```
参数
> $title 在摇一摇页面展示的主标题,不超过6个汉字或12个英文字母
$description 在摇一摇页面展示的副标题,不超过7个汉字或14个英文字母
$pageUrl 点击进去的超链接
$iconUrl 在摇一摇页面展示的图片。图片需先上传至微信侧服务器,用“素材管理-上传图片素材”接口上传图片,返回的图片URL再配置在此处
$comment 可选,页面的备注信息,不超过15个汉字或30个英文字母
示例
```php
$result = $shakearound->page->create($data);
/* 返回结果
{
"data": {
"page_id": 28840
}
"errcode": 0,
"errmsg": "success."
}
*/
```
### 编辑页面信息
编辑摇一摇出来的页面信息,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。
方法
```php
$shakearound->page->update(int $pageId, array $data)
```
参数
> $pageId 摇周边页面唯一ID
$data 需要更新的信息
示例
```php
$result = $shakearound->page->update(28840, [
'title' => '主标题',
'description' => '副标题',
//...
]);
```
## 查询页面列表
查询已有的页面,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。
### 根据页面id批量取回页面数据
方法
```php
$shakearound->page->listByIds(array $pageIds)
```
参数
> $pageIds 页面的id列表,索引数组
示例
```php
$result = $shakearound->page->listByIds([28840, 28842]);
/* 返回结果
{
"data": {
"pages": [
{
"comment": "just for test",
"description": "test",
"icon_url": "https://www.baidu.com/img/bd_logo1",
"page_id": 28840,
"page_url": "http://xw.qq.com/testapi1",
"title": "测试1"
},
{
"comment": "just for test",
"description": "test",
"icon_url": "https://www.baidu.com/img/bd_logo1",
"page_id": 28842,
"page_url": "http://xw.qq.com/testapi2",
"title": "测试2"
}
],
"total_count": 2
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 分页批量取回页面数据
方法
```php
$shakearound->page->list(int $begin, int $count)
```
参数
> $begin 页面列表的起始索引值
$count 待查询的页面数量,不能超过50个
示例
```php
$result = $shakearound->page->list(0,2);
// 返回结果同上
```
### 删除页面
删除已有的页面,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。
>
只有页面与设备没有关联关系时,才可被删除。
方法
```php
$shakearound->page->delete(int $pageId)
```
参数
> $pageId 页面的id
示例
```php
$result = $shakearound->page->delete(34567);
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 素材管理
上传在摇一摇功能中需使用到的图片素材,素材保存在微信侧服务器上。图片格式限定为:jpg,jpeg,png,gif。
若图片为在摇一摇页面展示的图片,则其素材为 `icon` 类型的图片,图片大小建议 `120px*120 px` ,限制不超过 `200 px *200 px` ,图片需为 `正方形` 。
若图片为申请开通摇一摇周边功能需要上传的资质文件图片,则其素材为 `license` 类型的图片,图片的文件大小不超过 `2MB` ,尺寸不限,形状不限。
方法
> $shakearound->material->uploadImage(string $path [, string $type = 'icon'])
参数
> $path 图片所在路径
$type 可选,值为icon或license
示例
```php
$result = $shakearound->material->uploadImage(__DIR__ . '/stubs/image.jpg');
/* 返回结果
{
"data": {
"pic_url": http://shp.qpic.cn/wechat_shakearound_pic/0/1428377032e9dd2797018cad79186e03e8c5aec8dc/120"
},
"errcode": 0,
"errmsg": "success."
}
*/
```
## 管理设备与页面的关系
通过接口申请的设备ID,需先配置页面,若未配置页面,则摇不出页面信息。
### 配置设备与页面的关联关系
配置完成后,在此设备的信号范围内,即可摇出关联的页面信息。
若设备配置多个页面,则随机出现页面信息。一个设备最多可配置30个关联页面。
>
1、配置时传入该设备需要关联的页面的id列表,该设备原有的关联关系将被直接清除。
2、页面的id列表允许为空(**传入空数组**),当页面的id列表为空时则会清除该设备的所有关联关系。
方法
> $shakearound->relation->bindPage(array $deviceIdentifier, array $pageIds)
参数
> $deviceIdentifier 设备id,设备编号device_id或UUID、major、minor的关联数组,若二者都填,则以设备编号为优先
$pageIds 页面的id列表,索引数组
示例
```php
$result = $shakearound->relation->bindPage(['device_id' => 10011], [12345, 23456, 334567]);
// 或
$result = $shakearound->relation->bindPage(['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
], [12345, 23456, 334567]);
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->errcode) // 0
```
### 查询设备与页面的关联关系
#### 查询指定设备所关联的页面
根据设备ID或完整的UUID、Major、Minor查询该设备所关联的所有页面信息
方法
> $shakearound->relation->listByDeviceId(array $deviceIdentifier [, boolean $raw = false])
>
该方法默认对返回的数据进行处理后返回一个包含页面id的索引数组。若要返回和 `getDeviceByPageId` 方法类似的数据,请传入 `true` 作为第二个参数。
参数
> $deviceIdentifier 设备id,设备编号device_id或UUID、major、minor的关联数组,若二者都填,则以设备编号为优先
$raw 可选,当为true时,返回值和getDeviceByPageId方法类似,否则返回页面的id列表(索引数组,无关联时为空数组)
示例
```php
$result = $shakearound->relation->listByDeviceId(['device_id' => 10011]);
// 或
$result = $shakearound->relation->listByDeviceId([
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
]);
// 返回结果
var_dump($result) // [50054,50055]
```
##### 查询指定页面所关联的设备
指定页面ID分页查询该页面所关联的所有的设备信息
方法
> $shakearound->relation->listByPageId(int $pageId, int $begin, int $count)
参数
> $pageId 指定的页面id
$begin 关联关系列表的起始索引值
$count 待查询的关联关系数量,不能超过50个
示例
```php
$result = $shakearound->relation->listByPageId(50054, 0, 3);
/* 返回结果
{
"data": {
"relations": [
{
"device_id": 797994,
"major": 10001,
"minor": 10023,
"page_id": 50054,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
},
{
"device_id": 797995,
"major": 10001,
"minor": 10024,
"page_id": 50054,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
}
],
"total_count": 2
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 摇一摇数据统计
> 此接口无法获取当天的数据,最早只能获取前一天的数据。
由于系统在凌晨处理前一天的数据,太早调用此接口可能获取不到数据,建议在早上8:00之后调用此接口。
### 以设备为维度的数据统计
查询单个设备进行摇周边操作的人数、次数,点击摇周边消息的人数、次数。
>
查询的最长时间跨度为 30 天。只能查询最近 90 天的数据。
方法
> $shakearound->stats->deviceSummary(array $deviceIdentifier, int $beginDate, int $endDate)
参数
> $deviceIdentifier 设备id,设备编号device_id或UUID、major、minor的关联数组,若二者都填,则以设备编号为优先
$beginDate 起始日期时间戳,最长时间跨度为30天,单位为秒
$endDate 结束日期时间戳,最长时间跨度为30天,单位为秒
示例
```php
$result = $shakearound->stats->deviceSummary(['device_id' => 10011], 1425052800, 1425139200);
// 或
$result = $shakearound->stats->deviceSummary(['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
], 1425052800, 1425139200);
/* 返回结果
{
"data": [
{
"click_pv": 0,
"click_uv": 0,
"ftime": 1425052800,
"shake_pv": 0,
"shake_uv": 0
},
{
"click_pv": 0,
"click_uv": 0,
"ftime": 1425139200,
"shake_pv": 0,
"shake_uv": 0
}
],
"errcode": 0,
"errmsg": "success."
}
*/
```
### 批量查询设备统计数据
查询指定时间商家帐号下的每个设备进行摇周边操作的人数、次数,点击摇周边消息的人数、次数。
> 只能查询最近90天内的数据,且一次只能查询一天。
>
对于摇周边人数、摇周边次数、点击摇周边消息的人数、点击摇周边消息的次数都为0的设备,不在结果列表中返回。
方法
```php
$shakearound->stats->devicesSummary(int $timestamp, int $pageIndex)
```
参数
> $timestamp 指定查询日期时间戳,单位为秒
$pageIndex 指定查询的结果页序号,返回结果按摇周边人数降序排序,每50条记录为一页
示例
```php
$result = $shakearound->stats->devicesSummary(1435075200, 1);
/* 返回结果
{
"data": {
"devices": [
{
"device_id": 10097,
"major": 10001,
"minor": 12102,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
"shake_pv": 1
"shake_uv": 2
"click_pv": 3
"click_uv": 4
},
{
"device_id": 10098,
"major": 10001,
"minor": 12103,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
"shake_pv": 1
"shake_uv": 2
"click_pv": 3
"click_uv": 4
}
],
},
"date":1435075200
"total_count": 151
"page_index":1
"errcode": 0,
"errmsg": "success."
}
*/
```
### 以页面为维度的数据统计
查询单个页面通过摇周边摇出来的人数、次数,点击摇周边页面的人数、次数
> 注意:
查询的最长时间跨度为30天。只能查询最近90天的数据。
方法
```php
$shakearound->stats->pageSummary(int $pageId, int $beginDate, int $endDate);
```
参数
> $pageId 指定页面的页面ID
$beginDate 起始日期时间戳,最长时间跨度为30天,单位为秒
$endDate 结束日期时间戳,最长时间跨度为30天,单位为秒
示例
```php
$result = $shakearound->stats->pageSummary(12345, 1425052800, 1425139200);
/* 返回结果
{
"data": [
{
"click_pv": 0,
"click_uv": 0,
"ftime": 1425052800,
"shake_pv": 0,
"shake_uv": 0
},
{
"click_pv": 0,
"click_uv": 0,
"ftime": 1425139200,
"shake_pv": 0,
"shake_uv": 0
}
],
"errcode": 0,
"errmsg": "success."
}
*/
```
### 批量查询页面统计数据
查询指定时间商家帐号下的每个页面进行摇周边操作的人数、次数,点击摇周边消息的人数、次数。
>
对于摇周边人数、摇周边次数、点击摇周边消息的人数、点击摇周边消息的次数都为0的页面,不在结果列表中返回。
方法
```php
$shakearound->stats->pagesSummary(int $timestamp, int $pageIndex);
```
参数
> $timestamp 指定查询日期时间戳,单位为秒
$pageIndex 指定查询的结果页序号,返回结果按摇周边人数降序排序,每50条记录为一页
示例
```php
$result = $shakearound->stats->pagesSummary(1435075200, 1);
/* 返回结果
{
"data": {
"pages": [
{
"page_id":1234
"click_pv": 1,
"click_uv": 3,
"shake_pv": 0,
"shake_uv": 0
},
{
"page_id":5678
"click_pv": 1,
"click_uv": 2,
"shake_pv": 0,
"shake_uv": 0
},
],
},
"date":1435075200
"total_count": 151
"page_index":1
"errcode": 0,
"errmsg": "success."
}
*/
```
## 设备分组管理
调用H5页面获取设备信息 JS API接口,需要先把设备分组,微信客户端只会返回已在分组中的设备信息。
### 新增分组
新建设备分组,每个帐号下最多只有1000个分组。
方法
```php
$shakearound->group->create(string $name)
参数
> $name 分组名称,不超过100汉字或200个英文字母
示例
```php
$result = $shakearound->group->create('test');
/* 返回结果
{
"data": {
"group_id" : 123,
"group_name" : "test"
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 编辑分组信息
编辑设备分组信息,目前只能修改分组名。
方法
> $shakearound->group->update(int $groupId, string $name)
参数
> $groupId 分组唯一标识,全局唯一
$name 分组名称,不超过100汉字或200个英文字母
示例
```php
$result = $shakearound->group->update(123, 'newName');
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 删除分组
删除设备分组,若分组中还存在设备,则不能删除成功。需把设备移除以后,才能删除。
> 在执行删除前,最好先使用 `get` 方法查询分组详情,若分组内有设备,先使用 `removeDevices` 方法移除。
方法
```php
$shakearound->group->delete(int $groupId)
```
参数
> $groupId 分组唯一标识,全局唯一
示例
```php
$result = $shakearound->group->delete(123);
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 查询分组列表
查询账号下所有的分组。
方法
```php
$shakearound->group->list(int $begin, int $count)
```
参数
> $begin 分组列表的起始索引值
$count 待查询的分组数量,不能超过1000个
示例
```php
$result = $shakearound->group->list(0, 2);
/* 返回结果
{
"data": {
"groups":[
{
"group_id" : 123,
"group_name" : "test1"
},
{
"group_id" : 124,
"group_name" : "test2"
}
],
"total_count": 100
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 查询分组详情
查询分组详情,包括分组名,分组id,分组里的设备列表。
方法
```php
$shakearound->group->get(int $groupId, int $begin, int $count)
```
参数
> $groupId 分组唯一标识,全局唯一
$begin 分组里设备的起始索引值
$count 待查询的分组里设备的数量,不能超过1000个
示例
```php
$result = $shakearound->group->get(123, 0, 2);
/* 返回结果
{
"data": {
"group_id" : 123,
"group_name" : "test",
"total_count": 100,
"devices" :[
{
"device_id" : 123456,
"uuid" : "FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
"major" : 10001,
"minor" : 10001,
"comment" : "test device1",
"poi_id" : 12345,
},
{
"device_id" : 123457,
"uuid" : "FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
"major" : 10001,
"minor" : 10002,
"comment" : "test device2",
"poi_id" : 12345,
}
]
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 添加设备到分组
添加设备到分组,每个分组能够持有的设备上限为10000,并且每次添加操作的添加上限为1000。
> 只有在摇周边申请的设备才能添加到分组。
方法
> $shakearound->group->addDevices(int $groupId, array $deviceIdentifiers)
参数
> $groupId 分组唯一标识,全局唯一
$deviceIdentifiers 设备id列表
示例
```php
$result = $shakearound->group->addDevices(123, [
['device_id' => 10097],
['device_id' => 10098],
]);
// 或
$result = $shakearound->group->addDevices(123, [
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12102,
],
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12103,
]
]);
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 从分组中移除设备
从分组中移除设备,每次删除操作的上限为 1000。
方法
```php
$shakearound->group->removeDevices(int $groupId, array $deviceIdentifiers)
```
参数
> $groupId 分组唯一标识,全局唯一
$deviceIdentifiers 设备id列表
示例
```php
$result = $shakearound->group->removeDevices(123, [
['device_id' => 10097],
['device_id' => 10098],
]);
// 或
$result = $shakearound->group->removeDevices(123, [
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12102,
],
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12103,
]
]);
```
## 摇一摇事件通知
用户进入摇一摇界面,在“周边”页卡下摇一摇时,微信会把这个事件推送到开发者填写的URL(登录公众平台进入开发者中心设置)。推送内容包含摇一摇时“周边”页卡展示出来的页面所对应的设备信息,以及附近最多五个属于该公众账号的设备的信息。当摇出列表时,此事件不推送。
> 摇一摇事件的事件类型:ShakearoundUserShake
关于事件的处理请移步: [事件](events)
================================================
FILE: docs/src/4.x/official-account/store.md
================================================
# 门店小程序
## 拉取门店小程序类目
```php
$app->store->categories();
```
## 创建门店小程序
> 说明:创建门店小程序提交后需要公众号管理员确认通过后才可进行审核。如果主管理员 24 小时超时未确认,才能再次提交。
```php
$app->store->createMerchant($baseInfo);
```
> - `$baseInfo` 为门店小程序的基本信息数组,**`qualification_list` 字段为类目相关证件的临时素材 `mediaid` 如果 `second_catid` 对应的 `sensitive_type` 为 1 ,则 `qualification_list` 字段需要填 支持 0~5 个 `mediaid`,例如 `mediaid1`。`headimg_mediaid` 字段为头像 --- 临时素材 `mediaid`。`mediaid` 用现有的 `media/upload` 接口得到的,获取链接: [临时素材](../basic-services/media.md) ( 支持 PNG\JPEG\JPG\GIF 格式的图片,后续加上其他格式)**
示例:
```php
$info = [
"first_catid" => 476, //categories 接口获取的一级类目id
"second_catid" => 477, //categories 接口获取的二级类目id
"qualification_list" => "RTZgKZ386yFn5kQSWLTxe4bqxwgzGBjs3OE02cg9CVQk1wRVE3c8fjUFX7jvpi-P",
"headimg_mediaid" => "RTZgKZ386yFn5kQSWLTxe4bqxwgzGBjs3OE02cg9CVQk1wRVE3c8fjUFX7jvpi-P",
"nickname" => "hardenzhang308",
"intro" => "hardenzhangtest",
"org_code" => "",
"other_files" => ""
];
$result = $app->store->createMerchant($info);
```
> 注意:创建门店小程序的审核结果,会以事件形式推送给商户填写的回调 URL
## 查询门店小程序审核结果
```php
$app->store->getStatus($baseInfo);
```
## 修改门店小程序信息
```php
$app->store->updateMerchant($data);
```
> - `$data` 需要更新的部分数据,目前仅支持门店头像和门店小程序介绍,**若有填写内容则为覆盖更新,若无内容则视为不修改,维持原有内容。`headimg_mediaid`、`intro` 字段参考创建门店小程序**
示例:
```php
$data = [
"headimg_mediaid" => "RTZgKZ386yFn5kQSWLTxe4bqxwgzGBjs3OE02cg9CVQk1wRVE3c8fjUFX7jvpi-P",
"intro" => "麦辣鸡腿堡套餐,麦乐鸡,全家桶",
];
$result = $app->store->updateMerchant($data);
```
## 从腾讯地图拉取省市区信息
```php
$app->store->districts();
```
## 在腾讯地图中搜索门店
```php
$app->store->searchFromMap($districtId, $keyword);
```
> - `$districtId` 为从腾讯地图拉取的地区 `id`
> - `$keyword` 为搜索的关键词
## 在腾讯地图中创建门店
```php
$app->store->createFromMap($baseInfo);
```
示例:
```php
$baseInfo = [
"name" => "hardenzhang",
"longitude" => "113.323753357",
"latitude" => "23.0974903107",
"province" => "广东省",
"city" => "广州市",
"district" => "海珠区",
"address" => "TIT",
"category" => "类目1:类目2",
"telephone" => "12345678901",
"photo" => "http://mmbiz.qpic.cn/mmbiz_png/tW66AWE2K6ECFPcyAcIZTG8RlcR0sAqBibOm8gao5xOoLfIic9ZJ6MADAktGPxZI7MZLcadZUT36b14NJ2cHRHA/0?wx_fmt=png",
"license" => "http://mmbiz.qpic.cn/mmbiz_png/tW66AWE2K6ECFPcyAcIZTG8RlcR0sAqBibOm8gao5xOoLfIic9ZJ6MADAktGPxZI7MZLcadZUT36b14NJ2cHRHA/0?wx_fmt=png",
"introduct" => "test",
"districtid" => "440105",
];
```
> - `$baseInfo`: 门店相关信息
> 事件推送 --- 腾讯地图中创建门店的审核结果。腾讯地图审核周期为 3 个工作日,请在期间内留意审核结果事件推送。提交后未当即返回事件推送即为审核中,请耐心等待。
## 添加门店
```php
$app->store->create($baseInfo);
```
示例:
```php
$baseInfo = [
"poi_id" => "",
"map_poi_id" => "2880741500279549033",
"pic_list" => "['list' => ['http://mmbiz.qpic.cn/mmbiz_jpg/tW66AWvE2K4EJxIYOVpiaGOkfg0iayibiaP2xHOChvbmKQD5uh8ymibbEKlTTPmjTdQ8ia43sULLeG1pT2psOfPic4kTw/0?wx_fmt=jpeg']]",
"contract_phone" => "1111222222",
"credential" => "22883878-0",
"qualification_list" => "RTZgKZ386yFn5kQSWLTxe4bqxwgzGBjs3OE02cg9CVQk1wRVE3c8fjUFX7jvpi-P"
];
```
> - `$baseInfo`: 门店相关信息。`pic_list` 门店图片,可传多张图片 `pic_list`
> 事件推送 - 创建门店的审核结果
## 更新门店信息
```php
$app->store->update($baseInfo);
```
> - `$baseInfo`: 门店相关信息。
> 果要更新门店的图片,实际相当于走一次重新为门店添加图片的流程,之前的旧图片会全部废弃。并且如果重新添加的图片中有与之前旧图片相同的,此时这个图片不需要重新审核。
================================================
FILE: docs/src/4.x/official-account/template_message.md
================================================
# 模板消息
模板消息仅用于公众号向用户发送重要的服务通知,只能用于符合其要求的服务场景中,如信用卡刷卡通知,商品购买成功通知等。不支持广告等营销类消息以及其它所有可能对用户造成骚扰的消息。
## 修改账号所属行业
```php
$app->template_message->setIndustry($industryId1, $industryId2);
```
## 获取支持的行业列表
```php
$app->template_message->getIndustry();
```
## 添加模板
在公众号后台获取 `$shortId` 并添加到账户。
```php
$app->template_message->addTemplate($shortId);
```
## 获取所有模板列表
```php
$app->template_message->getPrivateTemplates();
```
## 删除模板
```php
$app->template_message->deletePrivateTemplate($templateId);
```
## 发送模板消息
```php
$app->template_message->send([
'touser' => 'user-openid',
'template_id' => 'template-id',
'url' => 'https://easywechat.com',
'miniprogram' => [
'appid' => 'xxxxxxx',
'pagepath' => 'pages/xxx',
],
'data' => [
'key1' => 'VALUE',
'key2' => 'VALUE2',
...
],
]);
```
> 如果 url 和 miniprogram 字段都传,会优先跳转小程序。
## 发送一次性订阅消息
```php
$app->template_message->sendSubscription([
'touser' => 'user-openid',
'template_id' => 'template-id',
'url' => 'https://easywechat.com',
'scene' => 1000,
'data' => [
'key1' => 'VALUE',
'key2' => 'VALUE2',
...
],
]);
```
> 如果你想为发送的内容字段指定颜色,你可以将 "data" 部分写成下面 4 种不同的样式,不写 `color` 将会是默认黑色:
```php
'data' => [
'foo' => '你好', // 不需要指定颜色
'bar' => ['你好', '#F00'], // 指定为红色
'baz' => ['value' => '你好', 'color' => '#550038'], // 与第二种一样
'zoo' => ['value' => '你好'], // 与第一种一样
]
```
================================================
FILE: docs/src/4.x/official-account/tutorial.md
================================================
# 快速开始
在我们已经安装完成后,即可很快的开始使用它了,当然你还是有必要明白 PHP 基本知识,如命名空间等,我这里就不赘述了。
我们以完成服务器端验证与接收响应用户发送的消息为例来演示,首先你有必要了解一下微信交互的运行流程:
```
+-----------------+ +---------------+
+----------+ | | POST/GET/PUT | |
| | ------------------> | | -------------------> | |
| user | | wechat server | | your server |
| | < - - - - - - - - - | | | |
+----------+ | | <- - - - - - - - - - | |
+-----------------+ +---------------+
```
那么我们要做的就是图中 **微信服务器把用户消息转到我们的自有服务器(虚线返回部分)** 后的处理过程。
## 服务端验证
在微信接入开始有一个 “服务器验证” 的过程,这一步呢,其实就是微信服务器向我们服务器发起一个请求(上图实线部分),传了一个名称为 `echostr` 的字符串过来,我们只需要原样返回就好了。
你也知道,微信后台只能填写一个服务器地址,所以 **服务器验证** 与 **消息的接收与回复**,都在这一个链接内完成交互。
考虑到这些,我已经把验证这一步给封装到 SDK 里了,你可以完全忽略这一步。
下面我们来配置一个基本的服务端,这里假设我们自己的服务器域名叫 `easywechat.com`,我们在服务器上准备这么一个文件`server.php`:
// server.php
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'wx3cf0f39249eb0xxx',
'secret' => 'f1c242f4f28f735d4687abb469072xxx',
'token' => 'TestToken',
'response_type' => 'array',
//...
];
$app = Factory::officialAccount($config);
$response = $app->server->serve();
// 将响应输出
$response->send();exit; // Laravel 里请使用:return $response;
```
> :heart: 安全模式下请一定要配置 `aes_key`
一个服务端带验证功能的代码已经完成,当然没有对消息做处理,别着急,后面我们再讲。
我们先来分析上面的代码:
```php
// 引入我们的主项目工厂类。
use EasyWeChat\Factory;
// 一些配置
$config = [...];
// 使用配置来初始化一个公众号应用实例。
$app = Factory::officialAccount($config);
$response = $app->server->serve();
// 将响应输出
$response->send(); exit; // Laravel 里请使用:return $response;
```
最后这一行我有必要详细讲一下:
> 1. 我们的 `$app->server->serve()` 就是执行服务端业务了,那么它的返回值是一个 `Symfony\Component\HttpFoundation\Response` 实例。
> 2. 我这里是直接调用了它的 `send()` 方法,它就是直接输出(echo)了,我们在一些框架就不能直接输出了,那你就直接拿到 Response 实例后做相应的操作即可,比如 Laravel 里你就可以直接 `return $app->server->serve();`
OK, 有了上面的代码,那么请你按 **[微信官方的接入指引](http://mp.weixin.qq.com/wiki/)** 在公众号后台完成配置并启用,并相应修改上面的 `$config` 的相关配置。
> URL 就是我们的 `http://easywechat.com/server.php`,这里我是举例哦,你可不要填写我的域名。
这样,点击提交验证就 OK 了。
> :heart: 请一定要将微信后台的开发者模式 “**启用**” !!!!!!看到红色 “**停用**” 才真正的是启用了。
> 最后,请不要用浏览器访问这个地址,它是给微信服务器访问的,不是给人访问的。
## 接收 & 回复用户消息
那服务端验证通过了,我们就来试一下接收消息吧。
> 在刚刚上面代码最后一行 `$app->server->serve()->send();` 前面,我们调用 `$app->server` 的 `push()` 方法来注册一个消息处理器,这里用到了 **[PHP 闭包](http://php.net/manual/zh/functions.anonymous.php)** 的知识,如果你不熟悉赶紧补课去。
```php
// ...
$app->server->push(function ($message) {
return "您好!欢迎使用 EasyWeChat!";
});
$response = $app->server->serve();
// 将响应输出
$response->send(); // Laravel 里请使用:return $response;
```
> 注意:send() 方法里已经包含 echo 了,请不要再加 echo 在前面。
好吧,打开你的微信客户端,向你的公众号发送任意一条消息,你应该会收到回复:`您好!欢迎使用 EasyWeChat!`。
> 到了“你的公众号暂时无法提供服务” ?好,那检查一下你的日志吧,日志在哪儿?我们的配置里写了日志路径了(`__DIR__.'/wechat.log'`)。 没有这个文件?看看权限哦。
> 注意:在 Laravel 框架应用时,因 POST 请求默认会有 CSRF 验证,所以需要在 `App\Http\Middleware\VerifyCsrfToken` 的 `except` 数组中添加微信请求,否则会提示“你的公众号暂时无法提供服务”。
一个基本的服务端验证就完成了。
## 总结
1. 所有的应用服务都通过主入口 `EasyWeChat\Factory` 类来创建:
```php
// 公众号
$app = Factory::officialAccount($config);
// 小程序
$app = Factory::miniProgram($config);
// 开放平台
$app = Factory::openPlatform($config);
// 企业微信
$app = Factory::work($config);
// 企业微信开放平台
$app = Factory::openWork($config);
// 微信支付
$app = Factory::payment($config);
```
## 最后
希望你在使用本 SDK 的时候如果你发现 SDK 的不足,欢迎提交 PR 或者给我[提建议 & 报告问题](https://github.com/overtrue/wechat/issues)。
================================================
FILE: docs/src/4.x/official-account/user-tag.md
================================================
# 用户标签
## 获取所有标签
```php
$app->user_tag->list();
```
示例:
```php
$tags = $app->user_tag->list();
// {
// "tags": [
// {
// "id": 0,
// "name": "标签1",
// "count": 72596
// },
// {
// "id": 1,
// "name": "标签2",
// "count": 36
// },
// ...
// ]
// }
```
## 创建标签
```php
$app->user_tag->create($name);
```
示例:
```php
$app->user_tag->create('测试标签');
```
## 修改标签信息
```php
$app->user_tag->update($tagId, $name);
```
示例:
```php
$app->user_tag->update(12, "新的名称");
```
## 删除标签
```php
$app->user_tag->delete($tagId);
```
## 获取指定 openid 用户所属的标签
```php
$userTags = $app->user_tag->userTags($openId);
//
// {
// "tagid_list":["标签1","标签2"]
// }
```
## 获取标签下用户列表
```php
$app->user_tag->usersOfTag($tagId, $nextOpenId = '');
// $nextOpenId:第一个拉取的OPENID,不填默认从头开始拉取
// {
// "count":2, // 这次获取的粉丝数量
// "data":{ // 粉丝列表
// "openid":[
// "ocYxcuAEy30bX0NXmGn4ypqx3tI0",
// "ocYxcuBt0mRugKZ7tGAHPnUaOW7Y"
// ]
// },
// "next_openid":"ocYxcuBt0mRugKZ7tGAHPnUaOW7Y"//拉取列表最后一个用户的openid
// }
```
## 批量为用户添加标签
```php
$openIds = [$openId1, $openId2, ...];
$app->user_tag->tagUsers($openIds, $tagId);
```
## 批量为用户移除标签
```php
$openIds = [$openId1, $openId2, ...];
$app->user_tag->untagUsers($openIds, $tagId);
```
================================================
FILE: docs/src/4.x/official-account/user.md
================================================
# 用户
用户信息的获取是微信开发中比较常用的一个功能了,以下所有的用户信息的获取与更新,都是**基于微信的 `openid` 的,并且是已关注当前账号的**,其它情况可能无法正常使用。
## 获取用户信息
获取单个:
```php
$user = $app->user->get($openId);
```
获取多个:
```php
$users = $app->user->select([$openId1, $openId2, ...]);
```
## 获取用户列表
```php
$app->user->list($nextOpenId = null); // $nextOpenId 可选
```
示例:
```php
$users = $app->user->list();
// result
{
"total": 2,
"count": 2,
"data": {
"openid": [
"OPENID1",
"OPENID2"
]
},
"next_openid": "NEXT_OPENID"
}
```
## 修改用户备注
```php
$app->user->remark($openId, $remark); // 成功返回boolean
```
示例:
```php
$app->user->remark($openId, "僵尸粉");
```
## 拉黑用户
```php
$app->user->block('openidxxxxx');
// 或者多个用户
$app->user->block(['openid1', 'openid2', 'openid3', ...]);
```
## 取消拉黑用户
```php
$app->user->unblock('openidxxxxx');
// 或者多个用户
$app->user->unblock(['openid1', 'openid2', 'openid3', ...]);
```
## 获取黑名单
```php
$app->user->blacklist($beginOpenid = null); // $beginOpenid 可选
```
## 账号迁移 openid 转换
账号迁移请从这里了解:https://kf.qq.com/product/weixinmp.html#hid=2488
微信用户关注不同的公众号,对应的 OpenID 是不一样的,迁移成功后,粉丝的 OpenID 以目标帐号(即新公众号)对应的 OpenID 为准。但开发者可以通过开发接口转换 OpenID,开发文档可以参考:
提供一个 openid 转换的 API 接口,当帐号迁移后,可以通过该接口:
1. 将原帐号粉丝的 openid 转换为新帐号的 openid。
2. 将有授权关系用户的 openid 转换为新帐号的 openid。
3. 将卡券关联用户的 openid 转换为新帐号的 openid。
> - ◆ 原帐号:准备要迁移的帐号,当审核完成且管理员确认后即被回收。
> - ◆ 新帐号:用来接纳粉丝的帐号。新帐号在整个流程中均能正常使用。
一定要按照下面的步骤来操作。
1. 一定要在原帐号被冻结之前,最好是准备提交审核前,获取原帐号的用户列表。如果没有原帐号的用户列表,用不了转换工具。如果原账号被回收,这时候也没办法调用接口获取用户列表。
如何获取用户列表见这里:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140840
2. 转换 openid 的 API 接口如下,可在帐号迁移审核完成后开始调用,并最多保留 15 天。若帐号迁移没完成,调用时无返回结果或报错。帐号迁移 15 天后,该转换接口将会失效、无法拉取到数据。
```php
$app->user->changeOpenid($oldAppId, $openidList);
```
返回值样例:
```json
{
"errcode": 0,
"errmsg": "ok",
"result_list": [
{
"ori_openid": "oEmYbwN-n24jxvk4Sox81qedINkQ",
"new_openid": "o2FwqwI9xCsVadFah_HtpPfaR-X4",
"err_msg": "ok"
},
{
"ori_openid": "oEmYbwH9uVd4RKJk7ZZg6SzL6tTo",
"err_msg": "ori_openid error"
}
]
}
```
================================================
FILE: docs/src/4.x/open-platform/authorizer-delegate.md
================================================
# 代授权方实现业务
> 授权方已经把公众号、小程序授权给你的开放平台第三方平台了,接下来的代授权方实现业务只需一行代码即可获得授权方实例。
## 实例化
```php
use EasyWeChat\Factory;
$config = [
// ...
];
$openPlatform = Factory::openPlatform($config);
```
### 获取授权方实例
```php
// 代公众号实现业务
$officialAccount = $openPlatform->officialAccount(string $appId, string $refreshToken);
// 代小程序实现业务
$miniProgram = $openPlatform->miniProgram(string $appId, string $refreshToken);
```
> $appId 为授权方公众号 APPID,非开放平台第三方平台 APPID
>
> $refreshToken 为授权方的 refresh_token,可通过 [获取授权方授权信息](#) 接口获得。
### 帮助授权方管理开放平台账号
```php
// 代公众号实现业务
$account = $officialAccount->account;
// 代小程序实现业务
$account = $miniProgram->account;
// 创建开放平台账号
// 并绑定公众号或小程序
$result = $account->create();
// 将公众号或小程序绑定到指定开放平台帐号下
$result = $account->bindTo($openAppId);
// 将公众号/小程序从开放平台帐号下解绑
$result = $account->unbindFrom($openAppid);
// 获取公众号/小程序所绑定的开放平台帐号
$result = $account->getBinding();
```
> 授权第三方平台注册的开放平台帐号只可用于获取用户 unionid 实现用户身份打通。
>
> 第三方平台不可操作(包括绑定/解绑)通过 open.weixin.qq.com 线上流程注册的开放平台帐号。
>
> 公众号只可将此权限集授权给一个第三方平台,授权互斥。
接下来的 API 调用等操作和公众号、小程序的开发一致,请移步到[公众号](#)或[小程序](#)开发章节继续进行开发吧。
### 代码示例
```php
// 假设你的公众号消息与事件接收 URL 为:https://easywechat.com/$APPID$/callback ...
Route::post('{appId}/callback', function ($appId) {
// ...
$officialAccount = $openPlatform->officialAccount($appId);
$server = $officialAccount->server; // ❗️❗️ 这里的 server 为授权方的 server,而不是开放平台的 server,请注意!!!
$server->push(function () {
return 'Welcome!';
});
return $server->serve();
});
// 调用授权方业务例子
Route::get('how-to-use', function () {
$officialAccount = $openPlatform->officialAccount('已授权的公众号 APPID', 'Refresh-token');
// 获取用户列表:
$officialAccount->user->list();
$miniProgram = $openPlatform->miniProgram('已授权的小程序 APPID', 'Refresh-token');
// 根据 code 获取 session
$miniProgram->auth->session('js-code');
// 其他同理
});
```
================================================
FILE: docs/src/4.x/open-platform/index.md
================================================
# 微信开放平台第三方平台
此页涉及接口信息与说明请参见:[授权流程技术说明 - 官方文档](https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1453779503&token=&lang=)
# 微信开放平台第三方平台
## 实例化
```php
'开放平台第三方平台 APPID',
'secret' => '开放平台第三方平台 Secret',
'token' => '开放平台第三方平台 Token',
'aes_key' => '开放平台第三方平台 AES Key'
];
$openPlatform = Factory::openPlatform($config);
```
## 获取用户授权页 URL
```php
$openPlatform->getPreAuthorizationUrl('https://easywechat.com/callback'); // 传入回调URI即可
```
## 使用授权码换取接口调用凭据和授权信息
在用户在授权页授权流程完成后,授权页会自动跳转进入回调URI,并在URL参数中返回授权码和过期时间,如:(https://easywechat.com/callback?auth_code=xxx&expires_in=600)
```php
$openPlatform->handleAuthorize(string $authCode = null);
```
> $authCode 不传的时候会获取 url 中的 auth_code 参数值
## 获取授权方的帐号基本信息
```php
$openPlatform->getAuthorizer(string $appId);
```
## 获取授权方的选项设置信息
```php
$openPlatform->getAuthorizerOption(string $appId, string $name);
```
## 设置授权方的选项信息
```php
$openPlatform->setAuthorizerOption(string $appId, string $name, string $value);
```
> 该API用于获取授权方的公众号或小程序的选项设置信息,如:地理位置上报,语音识别开关,多客服开关。注意,获取各项选项设置信息,需要有授权方的授权,详见权限集说明。
## 获取已授权的授权方列表
```php
$openPlatform->getAuthorizers(int $offset = 0, int $count = 500)
```
================================================
FILE: docs/src/4.x/open-platform/server.md
================================================
# 服务端
## 第三方平台推送事件
公众号第三方平台推送的有四个事件:
> 如已经授权的公众号、小程序再次进行授权,而未修改已授权的权限的话,是没有相关事件推送的。
授权成功 `authorized`
授权更新 `updateauthorized`
授权取消 `unauthorized`
VerifyTicket `component_verify_ticket`
SDK 默认会处理事件 `component_verify_ticket` ,并会缓存 `verify_ticket` 所以如果你暂时不需要处理其他事件,直接这样使用即可:
```php
$server = $openPlatform->server;
return $server->serve();
```
## 自定义消息处理器
> *消息处理器详细说明见公众号开发 - 服务器一节*
```php
use EasyWeChat\OpenPlatform\Server\Guard;
$server = $openPlatform->server;
// 处理授权成功事件
$server->push(function ($message) {
// ...
}, Guard::EVENT_AUTHORIZED);
// 处理授权更新事件
$server->push(function ($message) {
// ...
}, Guard::EVENT_UPDATE_AUTHORIZED);
// 处理授权取消事件
$server->push(function ($message) {
// ...
}, Guard::EVENT_UNAUTHORIZED);
```
### 示例(Laravel 框架)
```php
// 假设你的开放平台第三方平台设置的授权事件接收 URL 为: https://easywechat.com/open-platform (其他事件推送同样会推送到这个 URL)
Route::post('open-platform', function () { // 关闭 CSRF
// $openPlatform 为你实例化的开放平台对象,此处省略实例化步骤
return $openPlatform->server->serve(); // Done!
});
// 处理事件
use EasyWeChat\OpenPlatform\Server\Guard;
Route::post('open-platform', function () {
$server = $openPlatform->server;
// 处理授权成功事件,其他事件同理
$server->push(function ($message) {
// $message 为微信推送的通知内容,不同事件不同内容,详看微信官方文档
// 获取授权公众号 AppId: $message['AuthorizerAppid']
// 获取 AuthCode:$message['AuthorizationCode']
// 然后进行业务处理,如存数据库等...
}, Guard::EVENT_AUTHORIZED);
return $server->serve();
});
```
================================================
FILE: docs/src/4.x/open-work/index.md
================================================
# 企业微信第三方服务商
## 实例化
```php
'服务商的corpid',
'secret' => '服务商的secret,在服务商管理后台可见',
'suite_id' => '以ww或wx开头应用id',
'suite_secret' => '应用secret',
'token' => '应用的Token',
'aes_key' => '应用的EncodingAESKey',
'reg_template_id' => '注册定制化模板ID',
'redirect_uri_install' => '安装应用的回调url(可选)',
'redirect_uri_single' => '单点登录回调url (可选)',
'redirect_uri_oauth' => '网页授权第三方回调url (可选)',
];
$app = Factory::openWork($config);
```
================================================
FILE: docs/src/4.x/open-work/provider.md
================================================
# 服务商相关接口
## 单点登录
### 获取从第三方单点登录连接
```php
$app->provider->getLoginUrl(string $redirectUri = '', string $userType = 'admin', string $state = ''); //$redirectUri 回调地址 $userType支持登录的类型
```
### 获取登录用户信息
```php
$app->provider->getLoginInfo(string $authCode); //$authCode oauth2.0授权企业微信管理员登录产生的code,最长为512字节。只能使用一次,5分钟未被使用自动过期
```
## 注册定制化
### 获取注册码
```php
$app->provider->getRegisterCode(
string $corpName = '', //企业名称
string $adminName = '',//管理员姓名
string $adminMobile = '',//管理员手机号
string $state = ''//自定义的状态值
);
```
### 获取注册Uri
```php
$app->provider->getRegisterUri(string $registerCode = ''); //$registerCode 注册码
```
### 查询注册状态
```php
$app->provider->getRegisterInfo(string $registerCode); //$registerCode 注册码
```
### 设置授权应用可见范围
```php
$app->provider->setAgentScope(
string $accessToken, //查询注册状态接口返回的access_token
string $agentId, // 授权方应用id
array $allowUser = [], //应用可见范围(成员)若未填该字段,则清空可见范围中成员列表
array $allowParty = [], // 应用可见范围(部门)若未填该字段,则清空可见范围中部门列表
array $allowTag = [] //应用可见范围(标签)若未填该字段,则清空可见范围中标签列表
)
```
### 设置通讯录同步完成
```php
$app->provider->contactSyncSuccess(string $accessToken); //$accessToken //查询注册状态接口返回的access_token
```
================================================
FILE: docs/src/4.x/open-work/server.md
================================================
# 服务端
## 企业微信第三方回调协议
SDK 默认会处理事件 `suite_ticket` ,并会缓存 `suite_ticket`
> 需要注意的是:授权成功、变更授权、取消授权通知时间的响应必须在 1000ms 内完成,以保证用户安装应用的体验。建议在接收到此事件时 立即回应企业微信,之后再做相关业务的处理。
```php
$server = $app->server;
$server->push(function ($message) {
switch ($message['InfoType']) {
//推送suite_ticket
case 'suite_ticket':
break;
//授权成功通知
case 'create_auth':
break;
//变更授权通知
case 'cancel_auth':
break;
//通讯录事件通知
case 'change_contact':
switch ($message['ChangeType']){
case 'create_user':
return '新增成员事件';
break;
case 'update_user':
return '更新成员事件';
break;
case 'delete_user':
return '删除成员事件';
break;
case 'create_party':
return '新增部门事件';
break;
case 'update_party':
return '更新部门事件';
break;
case 'delete_party':
return '删除部门事件';
break;
case 'update_tag':
return '标签成员变更事件';
break;
}
break;
default:
return 'fail';
break;
}
});
$response = $server->serve();
$response->send();
```
================================================
FILE: docs/src/4.x/open-work/service.md
================================================
# 第三方应用接口
## 获取预授权码
```php
$app->corp->getPreAuthCode();
```
## 设置授权配置
```php
$app->corp->setSession(string $preAuthCode, array $sessionInfo);
```
## 获取企业永久授权码
```php
$app->corp->getPermanentByCode(string $preAuthCode); //传入临时授权码
```
## 获取企业授权信息
```php
$app->corp->getAuthorization(string $authCorpId, string $permanentCode); //$authCorpId 授权的企业corp_id $permanentCode 授权的永久授权码
```
## 获取应用的管理员列表
```php
$app->corp->getManagers(string $authCorpId, string $agentId); //$authCorpId 授权的企业corp_id $agentId 授权方安装的应用agentid
```
## 网页授权登录第三方
### 构造第三方oauth2链接
```php
//$redirectUri 回调uri 这里可以覆盖 默认读取配置文件
//$scope 应用授权作用域。
//$state 自定义安全值
$app->corp->getOAuthRedirectUrl(string $redirectUri = '', string $scope = 'snsapi_userinfo', string $state = null);
```
### 第三方根据code获取企业成员信息
```php
$app->corp->getUserByCode(string $code);
```
### 第三方使用user_ticket获取成员详情
```php
$app->corp->getUserByTicket(string $userTicket);
```
================================================
FILE: docs/src/4.x/open-work/work.md
================================================
# 企业
### 获取授权企业的相关信息
```php
$work = $app->work('授权企业的corp_id','授权企业的永久授权码');
```
然后就可以像企业微信一样 获取相关的数据信息
================================================
FILE: docs/src/4.x/overview.md
================================================
# EasyWeChat
EasyWeChat 是一个开源的 [微信](http://www.wechat.com) 非官方 SDK。
EasyWeChat 的安装非常简单,因为它是一个标准的 [Composer](https://getcomposer.org/) 包,这意味着任何满足下列安装条件的 PHP 项目支持 Composer 都可以使用它。
### 环境需求
> - PHP >= 7.0
> - [PHP cURL 扩展](http://php.net/manual/en/book.curl.php)
> - [PHP OpenSSL 扩展](http://php.net/manual/en/book.openssl.php)
> - [PHP SimpleXML 扩展](http://php.net/manual/en/book.simplexml.php)
> - [PHP fileinfo 拓展](http://php.net/manual/en/book.fileinfo.php)
### 加入我们
[EasyWeChat SDK 交流群](http://shang.qq.com/wpa/qunwpa?idkey=b4dcf3ec51a7e8c3c3a746cf450ce59895e5c4ec4fbcb0f80c2cd97c3c6e63e9) ID: 319502940
> 为了避免广告及不看文档用户,加群需要付费,所以请使用 能支持群费的客户端。
> 另外:付费加群不代表我们有责任在群里回答你的问题,所以请认真阅读微信官方文档与 SDK 使用文档再使用,否则提的低级问题不会有人理你
> 不喜勿加,谢谢!
> 除非你发现了明确的 Bug,否则不要在群里 @ 我 :pray:
你有以下两种方式加入到我们中来,为广大开发者提供更优质的免费开源的服务:
> - **贡献代码**:我们的代码都在 [overtrue/wechat](https://github.com/overtrue/wechat) ,你可以提交 PR 到任何一个项目,当然,前提是代码质量必须是 OK 的。
> - **翻译或补充文档**:我们的文档在:[w7corp/EasyWeChat/docs](https://github.com/w7corp/easywechat/tree/master/docs),你可以选择补充文档或者参与英文文档的翻译,目前有 `zh-cn` 与 `en` 两个分支,你可以提交对应的 PR 到目标分支参与翻译工作。
### 开始之前
我们提供了视频教程: 当然,我还是建议你具备以下基础知识,否则可能没有那么快上手。
本 SDK 不是一个全新再造的东西,所以我不会从 0 开始教会你开发微信,你完全有必要在使用本 SDK 前做好以下工作:
> - 具备 PHP 基础知识,不要连闭包是啥都不明白,可以参考我在知乎的回答: [想要开发自己的 PHP 框架需要那些知识储备?](http://www.zhihu.com/question/26635323/answer/33812516)
> - 熟悉 PHP 常见的知识:自动加载、composer 的使用、JSON 处理、Curl 的使用等;
> - **仔细阅读并看懂**[微信官方文档](http://mp.weixin.qq.com/wiki/13/80a1a25adbc46faf2716774c423b3151.html) [微信开放平台文档](https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419318292&token=&lang=zh_CN);
> - 明白微信接口的组成,自有服务器、微信服务器、公众号(还有其它各种号)、测试号、以及通信原理(交互过程);
> - 了解基本的 HTTP 协议,Header 头、请求方式(GET\POST\PUT\PATCH\DELETE)等;
> - 基本的 Debug 技能,查看 php 日志,nginx 日志等。
如果你不具备这些知识,请不要使用,因为用起来会比较痛苦。
另外你有必要看一下以下的链接:
> -
> -
如果你在群里问以下类似的问题,这真的是你没有做好上面的工作:
> - "为啥我的不行啊,请问服务器日志怎么看啊?"
> - "请问这是什么原因啊?[结果/报错截图]"
> - "请问这个 SDK 怎么用啊?"
> - "谁能告诉我这个 SDK 是怎么安装的啊?"
> - "怎么接收用户发的消息啊?"
> - "为啥我的报这个错啊:Class XXXX not found..."
> - ...
我们专门针对一些容易出现的通用问题已经做了汇总: [疑难解答](troubleshooting.md) ,如果你在问题疑难解答没找到你出现的问题,那么可以在这里提问 [GitHub](https://github.com/overtrue/wechat/issues),提问请描述清楚你用的版本,你的做法是什么,不然别人没法帮你。
> 要在 QQ 单独找我提问\*\*,除非你是发现了明显的 bug。有问题先审查代码,看文档, 再 google,然后 去群里发个问题,带上你的代码,重现流程,大家有空的会帮忙你解答。谢谢合作!:pray:
### 打赏支持
这是一个开源的项目,我们没有收费服务,你如果觉得你从中获益,简化了你的开发工作,你可以 [打赏](https://github.com/sponsors/overtrue) 来支持我们。
================================================
FILE: docs/src/4.x/payment/bill.md
================================================
# 对账单
## 下载对账单
> 调用参数正确会返回一个 `EasyWeChat\Kernel\Http\StreamResponse` 对象,否则会返回相应错误信息
Example:
```php
$bill = $app->bill->get('20140603'); // type: ALL
// or
$bill = $app->bill->get('20140603', 'SUCCESS'); // type: SUCCESS
// 调用正确,`$bill` 为 csv 格式的内容,保存为文件:
$bill->saveAs('your/path/to', 'file-20140603.csv');
```
第二个参数为账单类型,参考:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_6 中 `bill_type`,默认为 `ALL`
================================================
FILE: docs/src/4.x/payment/contract.md
================================================
# 签约
## 公众号签约
> 参数 `appid`, `version`, `timestamp`, `sign` 可不用传入
```php
$result = $app->contract->web([
'mch_id' => '1200009811',
'plan_id' => '12535',
'contract_code' => '100000',
'contract_display_account' => '微信代扣',
'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action',
]);
```
## APP 签约
```php
$result = $app->contract->app(array $params);
```
## H5 签约
```php
$result = $app->contract->h5(array $params);
```
## 小程序签约
```php
$result = $app->jssdk->contractConfig(array $params);
```
## 申请扣款
```php
$result = $app->contract->apply(array $params);
```
## 申请解约
```php
$result = $app->contract->delete(array $params);
```
================================================
FILE: docs/src/4.x/payment/index.md
================================================
# 支付
你在阅读本文之前确认你已经仔细阅读了:[微信支付 | 商户平台开发文档](https://pay.weixin.qq.com/wiki/doc/api/index.html)。
## 配置
配置在前面的例子中已经提到过了,支付的相关配置如下:
```php
use EasyWeChat\Factory;
$config = [
// 必要配置
'app_id' => 'xxxx',
'mch_id' => 'your-mch-id',
'key' => 'key-for-signature', // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
// 如需使用敏感接口(如退款、发送红包等)需要配置 API 证书路径(登录商户平台下载 API 证书)
'cert_path' => 'path/to/your/cert.pem', // XXX: 绝对路径!!!!
'key_path' => 'path/to/your/key', // XXX: 绝对路径!!!!
'notify_url' => '默认的订单回调地址', // 你也可以在下单时单独设置来想覆盖它
];
$app = Factory::payment($config);
```
### 服务商
#### 设置子商户信息
```php
$app->setSubMerchant('sub-merchant-id', 'sub-app-id'); // 子商户 AppID 为可选项
```
### 刷卡支付
[官方文档](https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=9_10)
```php
$result = $app->pay([
'body' => 'image形象店-深圳腾大- QQ公仔',
'out_trade_no' => '1217752501201407033233368018',
'total_fee' => 888,
'auth_code' => '120061098828009406',
]);
```
## 授权码查询 OPENID 接口
```php
$app->authCodeToOpenid($authCode);
```
## 沙箱模式
微信支付沙箱环境,是提供给微信支付商户的开发者,用于模拟支付及回调通知。以验证商户是否理解回调通知、账单格式,以及是否对异常做了正确的处理。EasyWeChat SDK 对于这一功能进行了封装,开发者只需一步即可在沙箱模式和常规模式间切换,方便开发与最终的部署。
```php
// 在实例化的时候传入配置即可
$app = Factory::payment([
// ...
'sandbox' => true, // 设置为 false 或注释则关闭沙箱模式
]);
// 判断当前是否为沙箱模式:
bool $app->inSandbox();
```
> 特别注意,沙箱模式对于测试用例有严格要求,若使用的用例与规定不符,将导致测试失败。具体用例要求可关注公众号“微信支付商户接入验收助手”(WXPayAssist)查看。
================================================
FILE: docs/src/4.x/payment/jssdk.md
================================================
# JSSDK
JSSDK 模块用于生成调起微信支付以及共享收货地址的调用所需的配置参数。
## 配置
```php
use EasyWeChat\Factory;
$config = [
// 前面的appid什么的也得保留哦
'app_id' => 'xxxx',
'mch_id' => 'your-mch-id',
'key' => 'key-for-signature',
'cert_path' => 'path/to/your/cert.pem', // XXX: 绝对路径!!!!
'key_path' => 'path/to/your/key', // XXX: 绝对路径!!!!
'notify_url' => '默认的订单回调地址', // 你也可以在下单时单独设置来想覆盖它
// 'device_info' => '013467007045764',
// 'sub_app_id' => '',
// 'sub_merchant_id' => '',
// ...
];
$payment = Factory::payment($config);
$jssdk = $payment->jssdk;
```
## 生成支付 JS 配置
有三种发起支付的方式:[WeixinJSBridge](https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6), [JSSDK](https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=15_1), [小程序](https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7)
1. WeixinJSBridge:
```php
$json = $jssdk->bridgeConfig($prepayId); // 返回 json 字符串,如果想返回数组,传第二个参数 false
```
javascript:
```js
...
WeixinJSBridge.invoke(
'getBrandWCPayRequest', = $json ?>,
function(res){
if(res.err_msg == "get_brand_wcpay_request:ok" ) {
// 使用以上方式判断前端返回,微信团队郑重提示:
// res.err_msg将在用户支付成功后返回
// ok,但并不保证它绝对可靠。
}
}
);
...
```
2. JSSDK:
```php
$config = $jssdk->sdkConfig($prepayId); // 返回数组
```
javascript:
```js
wx.chooseWXPay({
timestamp: = $config['timestamp'] ?>,
nonceStr: '= $config['nonceStr'] ?>',
package: '= $config['package'] ?>',
signType: '= $config['signType'] ?>',
paySign: '= $config['paySign'] ?>', // 支付签名
success: function (res) {
// 支付成功后的回调函数
}
});
```
3. 小程序:
```php
$config = $jssdk->bridgeConfig($prepayId, false); // 返回数组
```
javascript:
```js
wx.requestPayment({
timeStamp: = $config['timeStamp'] ?>, //注意 timeStamp 的格式
nonceStr: '= $config['nonceStr'] ?>',
package: '= $config['package'] ?>',
signType: '= $config['signType'] ?>',
paySign: '= $config['paySign'] ?>', // 支付签名
success: function (res) {
// 支付成功后的回调函数
}
});
```
## 生成共享收货地址 JS 配置
1. 发起 OAuth 授权,获取用户 `$accessToken`,参考网页授权章节。
2. 使用 `$accessToken` 获取配置
```php
$configForPickAddress = $jssdk->shareAddressConfig($token);
// 拿着这个生成好的配置 $configForPickAddress 去订单页(或者直接显示订单页)写 js 调用了
// ...
```
## 生成 APP 支付配置
```php
$config = $jssdk->appConfig($prepayId);
```
`$config` 为数组格式,你可以用 API 返回给客户端
# 二维码生成工具推荐
你也许需要生成二维码,那么以下这些供参考:
> - https://github.com/endroid/QrCode
> - https://github.com/Bacon/BaconQrCode
> - https://github.com/SimpleSoftwareIO/simple-qrcode (Bacon/BaconQrCode 的 Laravel 版本)
> - https://github.com/aferrandini/PHPQRCode
================================================
FILE: docs/src/4.x/payment/micropay.md
================================================
# 付款码支付
## 配置
> 请务必先熟悉流程:
```php
$result = $app->pay([
'body' => 'image形象店-深圳腾大- QQ公仔',
'out_trade_no' => '20150806125346',
'total_fee' => 88,
'spbill_create_ip' => '123.12.12.123', // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址
'auth_code' => '120061098828009406', // 扫码支付付款码,设备读取用户微信中的条码或者二维码信息
]);
```
#### 支付结果
付款码支付方式没有回调通知,支付结果直接返回,请参考:[微信付款码支付文档](https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=5_1) 更新您的订单状态。
================================================
FILE: docs/src/4.x/payment/notify.md
================================================
# 通知
## 支付结果通知
在用户成功支付后,微信服务器会向该 **订单中设置的回调 URL** 发起一个 POST 请求,请求的内容为一个 XML。里面包含了所有的详细信息,具体请参考:[支付结果通知](https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7)
而对于用户的退款操作,在退款成功之后也会有一个异步回调通知。
本 SDK 内预置了相关方法,以方便开发者处理这些通知,具体用法如下:
只需要在控制器中使用 `handlePaidNotify()` 方法,在其中对自己的业务进行处理并向微信服务器发送一个响应。
```php
$response = $app->handlePaidNotify(function ($message, $fail) {
// 你的逻辑
return true;
// 或者错误消息
$fail('Order not exists.');
});
$response->send(); // Laravel 里请使用:return $response;
```
这里需要注意的有几个点:
0. 退款结果通知和扫码支付通知的使用方法均类似。
1. `handlePaidNotify` 只接收一个 [`Closure`](http://php.net/manual/zh/class.closure.php) 匿名函数。
2. 该匿名函数接收两个参数,这两个参数分别为:
> - `$message` 为微信推送过来的通知信息,为一个数组;
> - `$fail` 为一个函数,触发该函数可向微信服务器返回对应的错误信息,**微信会稍后重试再通知**。
3. 该函数返回值就是告诉微信 **“我是否处理完成”**。如果你触发 `$fail` 函数,那么微信会在稍后再次继续通知你,直到你明确的告诉它:“我已经处理完成了”,**只有**在函数里 `return true;` 才代表处理完成。
4. `handlePaidNotify` 返回值 `$response` 是一个 Response 对象,如果你要直接输出,使用 `$response->send()`, 在一些框架里(如 Laravel)不是输出而是返回:`return $response`。
通常我们的处理逻辑大概是下面这样(**以下只是伪代码**):
```php
$response = $app->handlePaidNotify(function($message, $fail){
// 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
$order = 查询订单($message['out_trade_no']);
if (!$order || $order->paid_at) { // 如果订单不存在 或者 订单已经支付过了
return true; // 告诉微信,我已经处理完了,订单没找到,别再通知我了
}
///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况,确认是已经支付 /////////////
if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态,不代表支付状态
// 用户是否支付成功
if (array_get($message, 'result_code') === 'SUCCESS') {
$order->paid_at = time(); // 更新支付时间为当前时间
$order->status = 'paid';
// 用户支付失败
} elseif (array_get($message, 'result_code') === 'FAIL') {
$order->status = 'paid_fail';
}
} else {
return $fail('通信失败,请稍后再通知我');
}
$order->save(); // 保存订单
return true; // 返回处理完成
});
$response->send(); // return $response;
```
> 注意:请把 “支付成功与否” 与 “是否处理完成” 分开,它俩没有必然关系。
> 比如:微信通知你用户支付完成,但是支付失败了(result_code 为 'FAIL'),你应该**更新你的订单为支付失败**,但是要**告诉微信处理完成**。
## 退款结果通知
使用示例:
```php
$response = $app->handleRefundedNotify(function ($message, $reqInfo, $fail) {
// 其中 $message['req_info'] 获取到的是加密信息
// $reqInfo 为 message['req_info'] 解密后的信息
// 你的业务逻辑...
return true; // 返回 true 告诉微信“我已处理完成”
// 或返回错误原因 $fail('参数格式校验错误');
});
$response->send();
```
## 扫码支付通知
扫码支付【模式一】:https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=6_4
```php
// 扫码支付通知接收第三个参数 `$alert`,如果触发该函数,会返回“业务错误”到微信服务器,触发 `$fail` 则返回“通信错误”
$response = $app->handleScannedNotify(function ($message, $fail, $alert) use ($app) {
// 如:$alert('商品已售空');
// 如业务流程正常,则要调用“统一下单”接口,并返回 prepay_id 字符串,代码如下
$result = $app->order->unify([
'trade_type' => 'NATIVE',
'product_id' => $message['product_id'],
// ...
]);
return $result['prepay_id'];
});
$response->send();
```
================================================
FILE: docs/src/4.x/payment/order.md
================================================
# 订单
## 统一下单
没错,什么 H5 支付,公众号支付,扫码支付,支付中签约,全部都是用这个接口下单。
> 参数 `appid`, `mch_id`, `nonce_str`, `sign`, `sign_type` 可不用传入
> 服务商模式下, 需使用 `sub_openid`, 并传入`sub_mch_id` 和`sub_appid`
```php
$result = $app->order->unify([
'body' => '腾讯充值中心-QQ会员充值',
'out_trade_no' => '20150806125346',
'total_fee' => 88,
'spbill_create_ip' => '123.12.12.123', // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址
'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
'openid' => 'oUpF8uMuAJO_M2pxb1Q9zNjWeS6o',
]);
//如trade_type = APP
//需要进行二次签名
(new \EasyWeChat\Payment\Jssdk\Client($app))->appConfig($result['prepay_id']);
// $result:
//{
// "return_code": "SUCCESS",
// "return_msg": "OK",
// "appid": "wx2421b1c4390ec4sb",
// "mch_id": "10000100",
// "nonce_str": "IITRi8Iabbblz1J",
// "openid": "oUpF8uMuAJO_M2pxb1Q9zNjWeSs6o",
// "sign": "7921E432F65EB8ED0CE9755F0E86D72F2",
// "result_code": "SUCCESS",
// "prepay_id": "wx201411102639507cbf6ffd8b0779950874",
// "trade_type": "JSAPI"
//}
```
**第二个参数**为是否[支付中签约](https://pay.weixin.qq.com/wiki/doc/api/pap.php?chapter=18_13&index=5),默认 `false`
> 支付中签约相关参数 `contract_mchid`, `contract_appid`, `request_serial` 可不用传入
```php
$isContract = true;
$result = $app->order->unify([
'body' => '腾讯充值中心-QQ会员充值',
'out_trade_no' => '20150806125346',
'total_fee' => 88,
'spbill_create_ip' => '123.12.12.123', // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址
'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
'openid' => 'oUpF8uMuAJO_M2pxb1Q9zNjWeS6o',
'plan_id' => 123,// 协议模板id
'contract_code' => 100001256,// 签约协议号
'contract_display_account' => '腾讯充值中心',// 签约用户的名称
'contract_notify_url' => 'http://easywechat.com/contract_notify'
], $isContract);
//$result:
//{
// "return_code": "SUCCESS",
// "return_msg": "OK",
// "appid": "wx123456",
// "mch_id": "10000100",
// "nonce_str": "CfOcMkDFblzulYvI",
// "sign": "B53F4AFEE7FA6AD5739581486A5CB9C9",
// "result_code": "SUCCESS",
// "prepay_id": "wx08175759731015754a5c13791522969400",
// "trade_type": "JSAPI",
// "plan_id": "123",
// "request_serial": "1565258279",
// "contract_code": "100001256",
// "contract_display_account": "腾讯充值中心",
// "out_trade_no": "201908088195558331565258279",
// "contract_result_code": "SUCCESS"
//}
```
## 查询订单
该接口提供所有微信支付订单的查询,商户可以通过该接口主动查询订单状态,完成下一步的业务逻辑。
需要调用查询接口的情况:
> - 当商户后台、网络、服务器等出现异常,商户系统最终未接收到支付通知;
> - 调用支付接口后,返回系统错误或未知交易状态情况;
> - 调用被扫支付 API,返回 USERPAYING 的状态;
> - 调用关单或撤销接口 API 之前,需确认支付状态;
### 根据商户订单号查询
```php
$app->order->queryByOutTradeNumber("商户系统内部的订单号(out_trade_no)");
```
### 根据微信订单号查询
```php
$app->order->queryByTransactionId("微信订单号(transaction_id)");
```
## 关闭订单
> 注意:订单生成后不能马上调用关单接口,最短调用时间间隔为 5 分钟。
```php
$app->order->close(商户系统内部的订单号(out_trade_no));
```
================================================
FILE: docs/src/4.x/payment/profit-sharing.md
================================================
# 分账
> 官方文档 https://pay.weixin.qq.com/wiki/doc/api/allocation.php?chapter=27_1&index=1
```php
use EasyWeChat\Factory;
$config = [
'app_id' => '***',
"secret" => "***",
'mch_id' => '***',
'key' => '***',
'cert_path' => 'cert.pem',
'key_path' => 'key.pem',
'notify_url' => 'http://***.com/notify.php',
];
$payment = Factory::payment($config);
```
### 添加接收方
> 商户发起添加分账接收方请求,后续可通过发起分账请求将结算后的钱分到该分账接收方。
```php
$receiver = [
"type" => "PERSONAL_OPENID",
"account" => "…………",//PERSONAL_OPENID:个人openid
"name" => "张三",//接收方真实姓名
"relation_type" => "PARTNER"
];
$payment->profit_sharing->addReceiver($receiver);
$receiver = [
"type" => "MERCHANT_ID",
"account" => "132456798",//MERCHANT_ID:商户ID
"name" => "商户全称",//商户全称
"relation_type" => "PARTNER"
];
$payment->profit_sharing->addReceiver($receiver);
```
### 删除接收方
```php
$payment->profit_sharing->deleteReceiver($receiver);
```
### 单次分账
```php
$transaction_id = "***";
$out_trade_no = "***";
$receivers = [
[
"type" => "PERSONAL_OPENID",
"account" => "***",
"amount" => 2,
"description" => "分到个人"
],
[
"type" => "MERCHANT_ID",
"account" => "***",
"amount" => 1,
"description" => "分到商户"
]
];
$sharing = $payment->profit_sharing->share($transaction_id,$out_trade_no,$receivers);
```
### 多次分账
```php
$payment->profit_sharing->multiShare($transaction_id,$out_trade_no,$receivers);
```
### 多次分账完结
```php
$params = [
"transaction_id" => "",
"out_order_no" => "",
"description" => ""
];
$payment->profit_sharing->markOrderAsFinished($params);
```
### 分账查询
```php
$res = $payment->profit_sharing->query($transaction_id,$out_trade_no);
```
> 查询结果
```
Array
(
[return_code] => SUCCESS
[result_code] => SUCCESS
[mch_id] => ***
[nonce_str] => 38e92cbe2790642f
[sign] => 8904B6440C58785540950F2911500F55C9A94CAC75790B0721B9AA470E6BF9A8
[transaction_id] => 4200000589202007249764665257
[out_order_no] => 202007241544057945
[order_id] => 30000103702020072402011591464
[status] => FINISHED
[receivers] => [{"type":"MERCHANT_ID","account":"***","amount":7,"description":"解冻给分账方","result":"SUCCESS","finish_time":"20200724172033"},{"type":"PERSONAL_OPENID","account":"***","amount":2,"description":"分到个人1","result":"SUCCESS","finish_time":"20200724172033"},{"type":"PERSONAL_OPENID","account":"***-g4","amount":1,"description":"分到郭","result":"SUCCESS","finish_time":"20200724172034"}]
)
```
### 分账退回
```php
$out_trade_no = "***";//退款订单号
$out_return_no = "***";//系统内部退款单号
$return_amount = 1;
$return_account = "***-g4";
$description = "订单取消";
$payment->profit_sharing->returnShare($out_trade_no,$out_return_no,$return_amount,$return_account,$description);
```
================================================
FILE: docs/src/4.x/payment/redpack.md
================================================
# 红包
在阅读本文之前确认你已经仔细阅读了:[微信支付 | 现金红包文档 ](https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_1)。
## 配置
与支付接口一样,红包接口也需要配置如下参数,需要特别注意的是,红包相关的全部接口**都需要使用 SSL 证书**,因此**cert_path 以及 cert_key 必须正确配置**。
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'you-app-id',
'mch_id' => 'your-mch-id',
'key' => 'key-for-signature',
'cert_path' => 'path/to/your/cert.pem',
'key_path' => 'path/to/your/key',
// ...
];
$payment = Factory::payment($config);
$redpack = $payment->redpack;
```
## 发送红包
微信的现金红包分为**普通红包**和**裂变红包**两类。SDK 中对其分别进行了封装,同时也提供了一个统一的调用方法。
**默认情况下,通过接口发送的红包金额应该在200元以内,但可以通过在调用发送接口时传递场景 ID (scene_id)来发送特定场景的红包,不同场景红包可以由商户自己登录商户平台设置最大金额。scene_id 的可选值及对应含义可参阅微信支付官方文档。**
### 发送普通红包接口
```php
$redpackData = [
'mch_billno' => 'xy123456',
'send_name' => '测试红包',
're_openid' => 'oxTWIuGaIt6gTKsQRLau2M0yL16E',
'total_num' => 1, //固定为1,可不传
'total_amount' => 100, //单位为分,不小于100
'wishing' => '祝福语',
'client_ip' => '192.168.0.1', //可不传,不传则由 SDK 取当前客户端 IP
'act_name' => '测试活动',
'remark' => '测试备注',
// ...
];
$result = $redpack->sendNormal($redpackData);
```
### 发送裂变红包接口
```php
$redpackData = [
'mch_billno' => 'xy123456',
'send_name' => '测试红包',
're_openid' => 'oxTWIuGaIt6gTKsQRLau2M0yL16E',
'total_num' => 3, //不小于3
'total_amount' => 300, //单位为分,不小于300
'wishing' => '祝福语',
'act_name' => '测试活动',
'remark' => '测试备注',
'amt_type' => 'ALL_RAND', //可不传
// ...
];
$result = $redpack->sendGroup($redpackData);
```
## 红包预下单接口
红包预下单接口是为摇一摇红包接口配合使用的,在开发摇一摇周边的摇红包相关功能时,需要调用本接口获取红包单号。详情参见[官方文档](http://mp.weixin.qq.com/wiki/7/0ddd50ed2421b99fedd071281c074aab.html#.E7.BA.A2.E5.8C.85.E9.A2.84.E4.B8.8B.E5.8D.95.E6.8E.A5.E5.8F.A3)
```php
$redpackData = [
'hb_type' => 'NORMAL', //NORMAL 或 GROUP
'mch_billno' => 'xy123456',
'send_name' => '测试红包',
're_openid' => 'oxTWIuGaIt6gTKsQRLau2M0yL16E',
'total_num' => 1, //普通红包固定为1,裂变红包不小于3
'total_amount' => 100, //单位为分,普通红包不小于100,裂变红包不小于300
'wishing' => '祝福语',
'client_ip' => '192.168.0.1', //可不传,不传则由 SDK 取当前客户端 IP
'act_name' => '测试活动',
'remark' => '测试备注',
'amt_type' => 'ALL_RAND',
// ...
];
$result = $redpack->prepare($redpackData);
```
## 查询红包信息
用于商户对已发放的红包进行查询红包的具体信息以及领取情况 ,普通红包和裂变包均使用这一接口进行查询。
```php
$mchBillNo = "商户系统内部的订单号(mch_billno)";
$redpack->info($mchBillNo);
```
================================================
FILE: docs/src/4.x/payment/refund.md
================================================
# 退款
## 申请退款
当交易发生之后一段时间内,由于买家或者卖家的原因需要退款时,卖家可以通过退款接口将支付款退还给买家,微信支付将在收到退款请求并且验证成功之后,按照退款规则将支付款按原路退到买家帐号上。
注意:
> 1、交易时间超过一年的订单无法提交退款;
> 2、微信支付退款支持单笔交易分多次退款,多次退款需要提交原支付订单的商户订单号和设置不同的退款单号。一笔退款失败后重新提交,要采用原来的退款单号。总退款金额不能超过用户实际支付金额。
参考:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4
### 根据微信订单号退款
```php
// 参数分别为:微信订单号、商户退款单号、订单金额、退款金额、其他参数
$app->refund->byTransactionId(string $transactionId, string $refundNumber, int $totalFee, int $refundFee, array $config = []);
// Example:
$result = $app->refund->byTransactionId('transaction-id-xxx', 'refund-no-xxx', 10000, 10000, [
// 可在此处传入其他参数,详细参数见微信支付文档
'refund_desc' => '商品已售完',
]);
```
### 根据商户订单号退款
```php
// 参数分别为:商户订单号、商户退款单号、订单金额、退款金额、其他参数
$app->refund->byOutTradeNumber(string $number, string $refundNumber, int $totalFee, int $refundFee, array $config = []);
// Example:
$result = $app->refund->byOutTradeNumber('out-trade-no-xxx', 'refund-no-xxx', 20000, 1000, [
// 可在此处传入其他参数,详细参数见微信支付文档
'refund_desc' => '退运费',
]);
```
> $refundNumber 为商户退款单号,自己生成用于自己识别即可。
## 查询退款
提交退款申请后,通过调用该接口查询退款状态。退款有一定延时,用零钱支付的退款20分钟内到账,银行卡支付的退款3个工作日后重新查询退款状态。
可通过 4 种不同类型的单号查询:
> - 微信订单号 => `queryByTransactionId($transactionId)`
> - 商户订单号 => `queryByOutTradeNumber($outTradeNumber)`
> - 商户退款单号 => `queryByOutRefundNumber($outRefundNumber)`
> - 微信退款单号 => `queryByRefundId($refundId)`
================================================
FILE: docs/src/4.x/payment/reverse.md
================================================
# 撤销订单
目前只有 **刷卡支付** 有此功能。
> 调用支付接口后请勿立即调用撤销订单API,建议支付后至少15s后再调用撤销订单接口。
## 通过内部订单号撤销订单
```php
$app->reverse->byOutTradeNumber("商户系统内部的订单号(out_trade_no)");
```
## 通过微信订单号撤销订单
```php
$app->reverse->byTransactionId("微信的订单号(transaction_id)");
```
================================================
FILE: docs/src/4.x/payment/scan-pay.md
================================================
## 扫码支付
### 模式一:先生成产品二维码,扫码下单后支付
> 请务必先熟悉流程:
#### 生成产品二维码内容
```php
$content = $app->scheme($productId); // $productId 为你的产品/商品ID,用于回调时带回,自己识别即可
//结果示例:weixin://wxpay/bizpayurl?sign=XXXXX&appid=XXXXX&mch_id=XXXXX&product_id=XXXXXX&time_stamp=XXXXXX&nonce_str=XXXXX
```
将 `$content` 生成二维码,SDK 并不内置二维码生成库,使用你熟悉的工具创建二维码即可,比如 PHP 部分有以下工具可以选择:
> -
> -
> -
#### 处理回调
当用户扫码时,你的回调接口会收到一个通知,调用[统一下单接口](https://easywechat.com/docs/master/zh-CN/payment/order)创建订单后返回 `prepay_id`,你可以使用下面的代码处理扫码通知:
```php
// 扫码支付通知接收第三个参数 `$alert`,如果触发该函数,会返回“业务错误”到微信服务器,触发 `$fail` 则返回“通信错误”
$response = $app->handleScannedNotify(function ($message, $fail, $alert) use ($app) {
// 如:$alert('商品已售空');
// 如业务流程正常,则要调用“统一下单”接口,并返回 prepay_id 字符串,代码如下
$result = $app->order->unify([
'trade_type' => 'NATIVE',
'product_id' => $message['product_id'], // $message['product_id'] 则为生成二维码时的产品 ID
// ...
]);
return $result['prepay_id'];
});
$response->send();
```
用户在手机上付完钱以后,你会再收到**付款结果通知**,这时候请参考:[处理微信支付通知](https://easywechat.com/docs/master/zh-CN/payment/notify) 更新您的订单状态。
### 模式二:先下单,生成订单后创建二维码
> :
#### 根据用户选购的商品生成订单
调用[统一下单接口](https://easywechat.com/docs/master/zh-CN/payment/order)创建订单:
```php
$result = $app->order->unify([
'trade_type' => 'NATIVE',
'product_id' => $message['product_id'], // $message['product_id'] 则为生成二维码时的产品 ID
// ...
]);
```
#### 生成二维码
> 版本 4.1.7+ 支持
从上一步得到的 `$result['code_url']` 得到二维码内容:
将 `$result['code_url']` 生成二维码图片向用户展示即可扫码,生成工具上面自己找一下即可。 SDK 不内置
#### 支付通知
这种方式的通知就只有**付款结果通知**了,这时候请参考:[处理微信支付通知](https://easywechat.com/docs/master/zh-CN/payment/notify) 更新您的订单状态。
================================================
FILE: docs/src/4.x/payment/security.md
================================================
# 安全与风控
> EasyWeChat 4.0.7+
## 获取 RSA 公钥
```php
$result = $app->security->getPublicKey();
// 存成文件
file_put_contents('./public.pem', $result);
```
将会得到 PKCS#1 格式密钥:
```
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEArT82k67xybiJS9AD8nNAeuDYdrtCRaxkS6cgs8L9h83eqlDTlrdw
zBVSv5V4imTq/URbXn4K0V/KJ1TwDrqOI8hamGB0fvU13WW1NcJuv41RnJVua0QA
lS3tS1JzOZpMS9BEGeFvyFF/epbi/m9+2kUWG94FccArNnBtBqqvFncXgQsm98JB
3a62NbS1ePP/hMI7Kkz+JNMyYsWkrOUFDCXAbSZkWBJekY4nGZtK1erqGRve8Jbx
TWirAm/s08rUrjOuZFA21/EI2nea3DidJMTVnXVPY2qcAjF+595shwUKyTjKB8v1
REPB3hPF1Z75O6LwuLfyPiCrCTmVoyfqjwIDAQAB
-----END RSA PUBLIC KEY-----
```
使用 OpenSSL 转换 PKCS#1 为 PKCS#8 格式密钥:
```shell
openssl rsa -RSAPublicKey_in -in public.pem -out public.pem
```
PKCS#8 格式密钥:
```
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArT82k67xybiJS9AD8nNA
euDYdrtCRaxkS6cgs8L9h83eqlDTlrdwzBVSv5V4imTq/URbXn4K0V/KJ1TwDrqO
I8hamGB0fvU13WW1NcJuv41RnJVua0QAlS3tS1JzOZpMS9BEGeFvyFF/epbi/m9+
lkUWG94FccArNnBtBqqvFncXgQsm98JB3a42NbS1ePP/hMI7Kkz+JNMyYsWkrOUF
DCXAbSZkWBJekY4nGZtK1erqGRve8JbxTWirAm/s08rUrjOuZFA21/EI2nea3Did
JMTVnXVPY2qcAjF+595shwUKyTjKB8v1REPB3hPF1Z75O6LwuLfyPiCrCTmVoyfq
jwIDAQAB
-----END PUBLIC KEY-----
```
================================================
FILE: docs/src/4.x/payment/transfer.md
================================================
# 企业付款
> EasyWeChat 4.0.7+
该模块需要用到双向证书,请参考:https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=4_3
## 企业付款到用户零钱
```php
$app->transfer->toBalance([
'partner_trade_no' => '1233455', // 商户订单号,需保持唯一性(只能是字母或者数字,不能包含有符号)
'openid' => 'oxTWIuGaIt6gTKsQRLau2M0yL16E',
'check_name' => 'FORCE_CHECK', // NO_CHECK:不校验真实姓名, FORCE_CHECK:强校验真实姓名
're_user_name' => '王小帅', // 如果 check_name 设置为FORCE_CHECK,则必填用户真实姓名
'amount' => 10000, // 企业付款金额,单位为分
'desc' => '理赔', // 企业付款操作说明信息。必填
]);
```
## 查询付款到零钱的订单
```php
$partnerTradeNo = 1233455;
$app->transfer->queryBalanceOrder($partnerTradeNo);
```
## 企业付款到银行卡
企业付款到银行卡需要对银行卡号与姓名进行 RSA 加密,所以这里需要先下载 RSA 公钥到本地(服务器),我们提供了一个命令行工具:[EasyWeChat/console](https://github.com/EasyWeChat/console),请使用 composer 安装完成。
```bash
$ composer require easywechat/console -vvv
```
然后,在项目根目录执行以下命令下载公钥:
```bash
$ ./vendor/bin/easywechat payment:rsa_public_key \
> --mch_id=14339221228 \
> --api_key=36YTbDmLgyQ52noqdxgwGiYy \
> --cert_path=/Users/overtrue/www/demo/apiclient_cert.pem \
> --key_path=/Users/overtrue/www/demo/apiclient_key.pem
```
将会在当前目录生成一个 `./public-14339221228.pem` 文件,你可以将它移动到敏感目录,然后在支付配置文件中加如以下选项:
```php
use EasyWeChat\Factory;
$config = [
// 必要配置
'app_id' => 'xxxx',
'mch_id' => 'your-mch-id',
'key' => 'key-for-signature', // API 密钥
// 如需使用敏感接口(如退款、发送红包等)需要配置 API 证书路径(登录商户平台下载 API 证书)
'cert_path' => '/path/to/your/cert.pem', // XXX: 绝对路径!!!!
'key_path' => '/path/to/your/key', // XXX: 绝对路径!!!!
// 将上面得到的公钥存放路径填写在这里
'rsa_public_key_path' => '/path/to/your/rsa/publick/key/public-14339221228.pem', // <<<------------------------
'notify_url' => '默认的订单回调地址', // 你也可以在下单时单独设置来想覆盖它
];
$app = Factory::payment($config);
```
```php
$result = $app->transfer->toBankCard([
'partner_trade_no' => '1229222022',
'enc_bank_no' => '6214830901234564', // 银行卡号
'enc_true_name' => '安正超', // 银行卡对应的用户真实姓名
'bank_code' => '1001', // 银行编号
'amount' => 100, // 单位:分
'desc' => '测试',
]);
```
## 查询付款到银行卡的订单
```php
$partnerTradeNo = 1233455;
$app->transfer->queryBankCardOrder($partnerTradeNo);
```
================================================
FILE: docs/src/4.x/sidebar.js
================================================
exports = module.exports = [
{
text: '开始使用',
collapsible: true,
items: [
{ text: '概述', link: '/4.x/overview.html' },
{ text: '安装', link: '/4.x/installation.html' },
{ text: '在框架中使用', link: '/4.x/integration.html' },
{ text: '常见问题汇总', link: '/4.x/troubleshooting.html' }
]
},
{
text: '公众号',
collapsible: true,
items: [
{ text: '入门', link: '/4.x/official-account/index.html' },
{ text: '快速开始', link: '/4.x/official-account/tutorial.html' },
{ text: '配置', link: '/4.x/official-account/configuration.html' },
{ text: '基础接口', link: '/4.x/official-account/base.html' },
{ text: '服务端', link: '/4.x/official-account/server.html' },
{ text: '消息', link: '/4.x/official-account/messages.html' },
{
text: '多客服消息转发',
link: '/4.x/official-account/message-transfer'
},
{
text: '消息群发',
link: '/4.x/official-account/broadcasting.html'
},
{
text: '模板消息',
link: '/4.x/official-account/template_message.html'
},
{ text: '用户', link: '/4.x/official-account/user.html' },
{ text: '用户标签', link: '/4.x/official-account/user-tag.html' },
{ text: '网页授权', link: '/4.x/official-account/oauth.html' },
{ text: 'JSSDK', link: '/4.x/basic-services/jssdk.html' },
{ text: '临时素材', link: '/4.x/basic-services/media.html' },
{ text: '二维码', link: '/4.x/basic-services/qrcode.html' },
{ text: '短网址', link: '/4.x/basic-services/url.html' },
{ text: '素材管理', link: '/4.x/official-account/material.html' },
{ text: '菜单', link: '/4.x/official-account/menu.html' },
{ text: '卡券', link: '/4.x/official-account/card.html' },
{ text: '门店', link: '/4.x/official-account/poi.html' },
{
text: '客服',
link: '/4.x/official-account/customer_service.html'
},
{
text: '摇一摇周边',
link: '/4.x/official-account/shake-around.html'
},
{
text: '数据统计与分析',
link: '/4.x/official-account/data_cube.html'
},
{ text: '语义理解', link: '/4.x/official-account/semantic.html' },
{ text: '自动回复', link: '/4.x/official-account/reply.html' },
{ text: '评论数据管理', link: '/4.x/official-account/comment.html' },
{ text: '返佣商品', link: '/4.x/official-account/goods.html' }
]
},
{
text: '微信支付',
collapsible: true,
items: [
{ text: '入门', link: '/4.x/payment/index.html' },
{ text: '订单', link: '/4.x/payment/order.html' },
{ text: '退款', link: '/4.x/payment/refund.html' },
{ text: '账单', link: '/4.x/payment/bill.html' },
{ text: '通知', link: '/4.x/payment/notify.html' },
{ text: '红包', link: '/4.x/payment/redpack.html' },
{ text: '付款码支付', link: '/4.x/payment/micropay.html' },
{ text: '扫码支付', link: '/4.x/payment/scan-pay.html' },
{ text: 'JSSDK', link: '/4.x/payment/jssdk.html' },
{ text: '企业付款', link: '/4.x/payment/transfer.html' },
{ text: '撤销订单', link: '/4.x/payment/reverse.html' },
{ text: '安全工具', link: '/4.x/payment/security.html' },
{ text: '分账', link: '/4.x/payment/profit-sharing.html' }
]
},
{
text: '小程序',
collapsible: true,
items: [
{ text: '入门', link: '/4.x/mini-program/index.html' },
{ text: '小程序码', link: '/4.x/mini-program/app_code.html' },
{
text: '客服消息',
link: '/4.x/mini-program/customer_service.html'
},
{ text: '数据统计与分析', link: '/4.x/mini-program/data_cube.html' },
{ text: '微信登录', link: '/4.x/mini-program/auth.html' },
{
text: '模板消息',
link: '/4.x/mini-program/template_message.html'
},
{ text: '消息解密', link: '/4.x/mini-program/decrypt.html' },
{ text: '物流助手', link: '/4.x/mini-program/express.html' },
{ text: '生物认证', link: '/4.x/mini-program/soter.html' },
{ text: '插件管理', link: '/4.x/mini-program/plugin.html' },
{ text: '附近的小程序', link: '/4.x/mini-program/nearby_poi.html' },
{
text: '订阅消息',
link: '/4.x/mini-program/subscribe_message.html'
}
]
},
{
text: '开放平台',
collapsible: true,
items: [
{ text: '入门', link: '/4.x/open-platform/index.html' },
{ text: '服务端', link: '/4.x/open-platform/server.html' },
{
text: '代授权',
link: '/4.x/open-platform/authorizer-delegate.html'
}
]
},
{
text: '企业微信',
collapsible: true,
items: [
{ text: '入门', link: '/4.x/wework/index.html' },
{ text: '服务端', link: '/4.x/wework/server.html' },
{ text: '应用管理', link: '/4.x/wework/agents.html' },
{ text: '消息发送', link: '/4.x/wework/message.html' },
{ text: '通讯录', link: '/4.x/wework/contacts.html' },
{ text: '网页授权', link: '/4.x/wework/oauth.html' },
{
text: '客户联系(原外部联系人)',
link: '/4.x/wework/external-contact.html'
},
{ text: '自定义菜单', link: '/4.x/wework/menu.html' },
{ text: '素材管理', link: '/4.x/wework/media.html' },
{ text: 'OA', link: '/4.x/wework/oa.html' },
{ text: '企业互联', link: '/4.x/wework/corp-group.html' },
{ text: '会话内容存档', link: '/4.x/wework/msg-audit.html' },
{ text: '电子发票', link: '/4.x/wework/invoice.html' },
{ text: '小程序', link: '/4.x/wework/mini-program.html' },
{ text: 'JSSDK', link: '/4.x/wework/jssdk.html' },
{ text: '群机器人', link: '/4.x/wework/group-robot.html' },
{ text: '移动端', link: '/4.x/wework/mobile.html' }
]
},
{
text: '企业微信开放平台',
collapsible: true,
items: [
{ text: '入门', link: '/4.x/open-work/index.html' },
{ text: '服务商接口', link: '/4.x/open-work/provider.html' },
{ text: '服务商', link: '/4.x/open-work/server.html' },
{ text: '第三方应用接口', link: '/4.x/open-work/service.html' },
{ text: '企业相关', link: '/4.x/open-work/work.html' }
]
},
{
text: '小微商户',
collapsible: true,
items: [
{ text: '入门', link: '/4.x/micro-merchant/index.html' },
{
text: '获取平台证书',
link: '/4.x/micro-merchant/certficates.html'
},
{ text: '图片上传', link: '/4.x/micro-merchant/media.html' },
{
text: '商户入驻',
link: '/4.x/micro-merchant/submit-application.html'
},
{ text: '商户升级', link: '/4.x/micro-merchant/upgrade.html' },
{ text: '商户信息修改', link: '/4.x/micro-merchant/material.html' },
{ text: '提现相关', link: '/4.x/micro-merchant/withdraw.html' },
{
text: '商户配置',
link: '/4.x/micro-merchant/merchant-config.html'
}
]
},
{
text: '自定义',
collapsible: true,
items: [
{ text: 'Access Token', link: '/4.x/customize/access_token.html' },
{ text: '缓存', link: '/4.x/customize/cache.html' },
{ text: '模块替换', link: '/4.x/customize/replace-service.html' }
]
},
{
text: '通用',
collapsible: true,
items: [
{ text: 'API 调用', link: '/4.x/client.html' }
]
},
{
text: '其他',
collapsible: true,
items: [
{ text: '常见问题', link: '/4.x/troubleshooting.html' },
{ text: '参与贡献', link: '/4.x/contributing.html' }
]
}
]
================================================
FILE: docs/src/4.x/troubleshooting.md
================================================
# 疑难解答
在微信公众平台开发的道路上,遍布着各种大大小小的坑,有的人掉坑里,几经折腾又爬出来了,然后拍拍屁股走人。然而坑还在那里,还会继续有后来人掉进去……
这,是我们不愿看到的。
所以在这里,我们将陆续将微信开发中可能遇到的各种疑难问题进行汇总,并给出对应的解决办法。一般情况下,这些问题都可以对号入座,轻松地解决。但也不排除特殊情况,这时候你遇到的问题与文中某一个症状一致,但文中所给的解决方案并不凑效,这种情况下就需要发挥你自己的智慧,去……折腾了……
我们期待这一版块为各位的开发带来便利,同时也希望各位本着开源、分享的精神对其进行补充和完善,将各种坑一一填小、填平,让微信开发变得不那么痛苦,甚至,变成一件快乐的事……
## 时区不对
使用命令 `date` 可以在服务器上查看当前时间,如果发现时区不对则需要修改时区:[Setting The Correct Timezone In CentOS And Ubuntu Servers With NTP](https://www.liberiangeek.net/2013/02/setting-the-correct-timezone-in-centos-and-ubuntu-servers-with-ntp/)
## curl: (60) SSL certificate problem: unable to get local issuer certificate
这是 SSL 证书问题所致,在使用 SDK 调用微信支付等相关的操作时可能会遇到报 “SSL certificate problem: unable to get local issuer certificate” 的错误。
微信公众平台提供的文档中建议对部分较敏感的操作接口使用 https 协议进行访问,例如微信支付和红包等接口中涉及到操作商户资金的一些操作。
wechat SDK 遵循了官方建议,所以在调用这些接口时,除了按照官方文档设置操作证书文件外,还需要保证服务器正确安装了 CA 证书。
1. 下载 CA 证书
你可以从 http://curl.haxx.se/ca/cacert.pem 下载 或者 使用[微信官方提供的证书](https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=4_3)中的 CA 证书 `rootca.pem` 也是同样的效果。
2. 在 `php.ini` 中配置 CA 证书
只需要将上面下载好的 CA 证书放置到您的服务器上某个位置,然后修改 `php.ini` 的 `curl.cainfo` 为该路径(**绝对路径!**),重启 `php-fpm` 服务即可。
```ini
curl.cainfo = /path/to/downloaded/cacert.pem
```
> 注意证书文件**路径为绝对路径**!以自己实际情况为准。
其它修改 HTTP 类源文件的方式是不允许的。
## cURL error 56: SSLRead() return error -9806
目前在 OSX 下,发现使用 HomeBrew 装的 PHP 7.0 有这个问题,解决方案是重新 brew 安装 PHP:
```shell
$ brew install homebrew/php/php70 --with-homebrew-openssl --with-homebrew-curl --without-snmp -vvv
```
验证:
```shell
$ php -i | grep 'OpenSSL support'
OpenSSL support => enabled
OpenSSL support => enabled
```
## 支付失败!当前页面的 URL 未注册
这是由于微信支付授权目录未正确配置引起的。此时开发者应该登录微信公众平台,进入**【微信支付】->【开发设置】**进行设置。
1. 公众号可添加 3 个支付授权目录,满足不同应用使用同一个公众号进行支付的业务需求。
2. 正确的**【支付授权目录】**应以 `http://` 或 `https://` 开头,并以正斜杠 `/` 结尾,授权目录所包含的域名**必须经过 ICP 备案**。
3. 支付授权目录需**细化至二级或三级目录**。
4. 所有**实际调起微信支付请求的页面都必须要所配置的支付授权目录之下**。
5. 在开发过程中,也可以使用测试授权目录进行开发测试,此时还**应该将参与测试的个人微信号添加到测试白名单中**,否则将出现对应的错误提示……
> \*页面**、**目录**、**URL **以及**域名\*\*等几个基本概念,并对自己所使用的框架的路由机制有一个大致了解。这样你才会知道自己正在配置的参数是个啥玩意儿,有什么卵用…… :smile:
## redirect_url 参数错误
这是由于程序使用了**网页授权**而公众号没有正确配置**【网页授权域名】**所致。此时你需要登录[微信公众平台](https://mp.weixin.qq.com/),在【开发】->【接口权限】页面找到**网页授权获取用户基本信息**进行配置并保存。
1. 网页授权域名应该为通过 ICP 备案的有效域名,否则保存时无法通过安全监测。
2. 网页授权域名即程序完成授权获得授权 code 后跳转到的页面的域名,一般情况下为你的业务域名。
3. 网页授权域名配置成功后会立即生效。
4. 公众号的网页授权域名只可配置一个,请合理规划你的业务,否则你会发现……授权域名不够用哈。
## [JSAPI] config: invalid url domain
在使用 JS-SDK 进行开发时,每个页面都需要调用 wx.config() 方法配置 JSPAI 参数。如果没有正确配置 **JSAPI 安全域名**并且开启了调试模式,此时就报此错误。遇到这个问题时,开发者需要登录微信公众平台,进入【公众号设置】->【功能设置】页面,将项目所使用的域名添加至 **【JSAPI 安全域名】**列表中。
1. 一个公众号同时最多可绑定**三个**安全域名,并且这些域名必须为通过 **ICP 备案**的**一级或一级以上**的有效域名。
2. JSAPI 安全域名每个月**限修改三次**,修改任何一个都算,所以,请谨慎操作。
3. 如果需要使用 JSAPI 调起支付功能,则支付目录必须也在所配置的**安全域名之下**,并且需要将支付目录添加至**支付授权目录**。
## token 验证失败、向公众号发送消息无任何反应
相信对接公众号一般是微信开发者进行开发过程中最先进行的工作,而在这看似简单的配置操作中,也可能会掉坑里。
最常见的两种情况就如下:
1. 确认你 “**启用**” 了开发模式, token 验证通过不代表启用,保存后也不代表启用。看到红色 “**停用**” 才真正的是启用了。
2. 配置好 URL(服务器地址)以及 Token(令牌)后,点击保存时提示**token 验证失败**,出现这种情况的原因有多种,其中之一便是网络不稳定,所以**可尝试多次保存**,若始终无法通过再排查其它可能因素。
3. 配置保存成功之后,向公众号发送消息无任何反应,自己的消息处理程序也没有被调用的记录(无对应日志)。这种情况下如果你尝试**反复停用和启用服务器配置**,可能突然间惊奇地了现,问题莫名其妙的解决了。
4. 使用在线调试工具的消息接口,http://mp.weixin.qq.com/debug/, 只要返回绿色的“**请求成功**”,就代表你的代码没有问题,请**重复上面第 3 项**再测试。
5. **如果你在用什么本地开发工具,或者什么 ngrok 代理到本机这样的开发方式,那么失败就很正常了,微信服务器到你机器的网络延迟太大(还是用服务器开发吧)。**
> 器 TOKEN 验证原理(官方文档有说明)并谨记服务器验证时使用 GET 方式访问,而公众平台向你的服务器发送消息/数据则使用 POST 方式,所以服务器验证成功之后,在某些启用了 CSRF 验证的框架里,接收消息时可能还会遇到 CSRF 相关的问题,请根据自己项目实际情况进行排查。
> 另外有的朋友的 Laravel 里使用了 laravel-debugbar,这个组件的原理是在页面输出时在后面添加 HTML 来实现的,所以它会改变我们返回给微信的内容,此时要么卸载,要么禁用掉它。
## Maximum function nesting level of '100' reached, aborting!
在使用了 Xdebug 的环境下可能出现这个问题。这是由于 Xdebug 限制函数嵌套的最大层级数(默认为 100),当嵌套次数达到该值便会触发 Xdebug 跳出嵌套并报此错误。
为避免这个问题,**可以将 Xdebug 的 max_nesting_level 参数适当设置大一些**,通常设置为 200 就可以了(当然可根据自己实际情况设置为更大的值)。
如下,修改 php.ini 配置文件后,重启 Apache 或 php-fpm 服务即可。
```ini
xdebug.max_nesting_level=200
```
## 扫码支付 获取商户订单信息超时或商户返回 httpcode 非 200!
1.确定签名正确,使用 SDK 基本上不会出什么问题 2.微信调用扫码支付回调链接,使用 POST 方式,确定服务器回调方法是否取消 csrf 验证
## Request access_token fail:{"errcode":61023,"errmsg":"refresh_token is invalid hint: [zDNUIA07582974]"}!
在用户授权时会获得该 authorizer_refresh_token 刷新令牌,而当缓存或数据库存储的该 authorizer_refresh_token 刷新令牌丢失后,可能会出现该问题,微信文档中说明
1.接口调用凭据刷新令牌(在授权的公众号具备 API 权限时,才有此返回值),刷新令牌主要用于第三方平台获取和刷新已授权用户的 access_token,只会在授权时刻提供,请妥善保存。
2.一旦丢失,只能让用户重新授权,才能再次拿到新的刷新令牌(https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1453779503&token=&lang=)。
3.为避免该问题,请将存储该刷新令牌的缓存有效期设置为 0(永久存储),并尽量不要去将该缓存或数据库清空。
如下:以 redis 为例。
```php
'expire' => 0,
```
## 替换 Handler,让 easywechat 支持协程
在 Swoft、IMI 等基于 Swoole 的协程框架中使用 easywechat 时,不免会有一个问题,就是 guzzle 客户端内置的 handler 不支持协程的问题。
这里,提供一个办法主动替换容器内的 guzzle_handler.
```php
$app = Factory::miniProgram($config);
$app['guzzle_handler'] = CoroutineHandler::class;
```
鉴于有些同学找不到可用的 `CoroutineHandler`,这里提供几个,供大家使用。
- hyperf/guzzle
- yurunsoft/guzzle-swoole
- mix/guzzle-hook
================================================
FILE: docs/src/4.x/wework/agents.md
================================================
# 应用管理
> 企业微信在 17 年 11 月对 API 进行了大量的改动,应用管理部分已经没啥用了
应用管理是企业微信中比较特别的地方,因为它的使用是不基于应用的,或者说基于任何一个应用都能访问这些 API,所以在用法上是直接调用 work 实例的 `agent` 属性。
```php
$config = [
...
];
$app = Factory::work($config);
```
## 应用列表
```php
$agents = $app->agent->list(); // 测试拿不到内容
```
## 应用详情
```php
$agents = $app->agent->get($agentId); // 只能传配置文件中的 id,API 改动所致
```
## 设置应用
```php
$agents = $app->agent->set($agentId, ['foo' => 'bar']);
```
================================================
FILE: docs/src/4.x/wework/contacts.md
================================================
# 通讯录
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxx', // 通讯录的 secret
//...
];
$contacts = Factory::work($config);
```
## 成员管理
### 创建成员
```php
$data = [
"userid" => "overtrue",
"name" => "超哥",
"english_name" => "overtrue"
"mobile" => "1818888888",
];
$contacts->user->create($data);
```
### 读取成员
```php
$contacts->user->get('overtrue');
```
### 更新成员
```php
$contacts->user->update('overtrue', [
"isleader": 0,
'position' => 'PHP 酱油工程师',
//...
]);
```
### 删除成员
```php
$contacts->user->delete('overtrue');
// 或者删除多个
$contacts->user->delete(['overtrue', 'zhangsan', 'wangwu']);
```
### 获取部门成员
```php
$contacts->user->getDepartmentUsers($departmentId);
// 递归获取子部门下面的成员
$contacts->user->getDepartmentUsers($departmentId, true);
```
### 获取部门成员详情
```php
$contacts->user->getDetailedDepartmentUsers($departmentId);
// 递归获取子部门下面的成员
$contacts->user->getDetailedDepartmentUsers($departmentId, true);
```
### 用户 ID 转为 openid
```php
$contacts->user->userIdToOpenid($userId);
// 或者指定应用 ID
$contacts->user->userIdToOpenid($userId, $agentId);
```
### openid 转为用户 ID
```php
$contacts->user->openidToUserId($openid);
```
### 手机号转为用户 ID
```php
$contacts->user->mobileToUserId($mobile);
```
### 二次验证
企业在成员验证成功后,调用如下接口即可让成员加入成功
```php
$contacts->user->accept($userId);
```
### 邀请成员
企业可通过接口批量邀请成员使用企业微信,邀请后将通过短信或邮件下发通知。
```php
$params = [
'user' => ['UserID1', 'UserID2', 'UserID3'], // 成员ID列表, 最多支持1000个
'party' => ['PartyID1', 'PartyID2'], // 部门ID列表,最多支持100个
'tag' => ['TagID1', 'TagID2'], // 标签ID列表,最多支持100个
];
$contacts->user->invite($params);
```
> `user`, `party`, `tag` 三者不能同时为空
### 获取邀请二维码
```php
$sizeType = 1; // qrcode尺寸类型,1: 171 x 171; 2: 399 x 399; 3: 741 x 741; 4: 2052 x 2052
$contacts->user->getInvitationQrCode($sizeType);
```
## 部门管理
### 创建部门
```php
$contacts->department->create([
'name' => '广州研发中心',
'parentid' => 1,
'order' => 1,
'id' => 2,
]);
```
### 更新部门
```php
$contacts->department->update($id, [
'name' => '广州研发中心',
'parentid' => 1,
'order' => 1,
]);
```
### 删除部门
```php
$contacts->department->delete($id);
```
### 获取部门列表
```php
$contacts->department->list();
// 获取指定部门及其下的子部门
$contacts->department->list($id);
```
## 标签管理
### 创建标签
```php
$contacts->tag->create($tagName, $tagId);
```
### 更新标签名字
```php
$contacts->tag->update($tagId, $tagName);
```
### 删除标签
```php
$contacts->tag->delete($tagId);
```
### 获取标签列表
```php
$contacts->tag->list();
```
### 获取标签成员(标签详情)
```php
$contacts->tag->get($tagId);
```
### 增加标签成员
```php
$contacts->tag->tagUsers($tagId, [$userId1, $userId2, ...]);
// 指定部门
$contacts->tag->tagDepartments($tagId, [$departmentId1, $departmentId2, ...]);
```
### 删除标签成员
```php
$contacts->tag->untagUsers($tagId, [$userId1, $userId2, ...]);
// 指定部门
$contacts->tag->untagDepartments($tagId, [$departmentId1, $departmentId2, ...]);
```
================================================
FILE: docs/src/4.x/wework/external-contact.md
================================================
# 外部联系人管理
## 获取实例
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxx',
...
];
$app = Factory::work($config);
// 基础接口
$app->external_contact;
// 「联系我」
$app->contact_way;
// 消息管理
$app->external_contact_message;
// 数据统计
$app->external_contact_statistics;
```
## 基础接口
### 获取配置了客户联系功能的成员列表
```php
$app->external_contact->getFollowUsers();
```
### 获取外部联系人列表
```php
$userId = 'zhangsan';
$app->external_contact->list($userId);
```
### 获取外部联系人详情
```php
$externalUserId = 'woAJ2GCAAAXtWyujaWJHDDGi0mACH71w';
$app->external_contact->get($externalUserId);
```
### 获取离职成员的客户列表
```php
$pageId = 0;
$pageSize = 1000;
$app->external_contact->getUnassigned($pageId, $pageSize);
```
### 离职成员的外部联系人再分配
```php
$externalUserId = 'woAJ2GCAAAXtWyujaWJHDDGi0mACH71w';
$handoverUserId = 'zhangsan';
$takeoverUserId = 'lisi';
$app->external_contact->transfer($externalUserId, $handoverUserId, $takeoverUserId);
```
## 配置客户联系「联系我」方式
> 注意:
> 1. 通过API添加的「联系我」不会在管理端进行展示。
> 2. 每个企业可通过API最多配置10万个「联系我」。
> 3. 截止 2019-06-21 官方文档没有提供获取所有「联系我」列表的接口,请开发者注意自行保管处理 configId,避免无法溯源。
### 增加「联系我」方式
```php
$type = 1;
$scene = 1;
$config = [
'style' => 1,
'remark' => '渠道客户',
'skip_verify' => true,
'state' => 'teststate',
'user' => ['UserID1', 'UserID2', 'UserID3'],
];
$app->contact_way->create($type, $scene, $config);
// {
// "errcode": 0,
// "errmsg": "ok",
// "config_id":"42b34949e138eb6e027c123cba77fad7"
// }
```
### 获取「联系我」方式
```php
$configId = '42b34949e138eb6e027c123cba77fad7';
$app->contact_way->get($configId);
```
### 更新「联系我」方式
```php
$configId = '42b34949e138eb6e027c123cba77fad7';
$config = [
'style' => 1,
'remark' => '渠道客户2',
'skip_verify' => true,
'state' => 'teststate2',
'user' => ['UserID4', 'UserID5', 'UserID6'],
];
$app->contact_way->update($configId, $config);
```
### 删除「联系我」方式
```php
$configId = '42b34949e138eb6e027c123cba77fad7';
$app->contact_way->delete($configId);
```
## 客户朋友圈
### 企业发表内容到客户的朋友圈
```php
$msg = [
"text" => [
"content" => "文本消息内容"
],
"attachments" => [
[
"msgtype" => "image",
"image" => [
"media_id" => "MEDIA_ID"
]
],
[
"msgtype" => "video",
"video" => [
"media_id" => "MEDIA_ID"
]
],
[
"msgtype" => "link",
"link" => [
"title" => "消息标题",
"url" => "https://example.link.com/path",
"media_id" => "MEDIA_ID"
]
]
],
"visible_range" => [
"sender_list" => [
"user_list" => ["zhangshan","lisi"],
"department_list" => [2,3]
],
"external_contact_list" => [
"tag_list" => [ "etXXXXXXXXXX", "etYYYYYYYYYY"]
]
]
];
$app->external_contact_message->moments($msg);
//{
// "errcode":0,
// "errmsg":"ok",
// "jobid":"xxxx"
//}
```
## 消息管理
### 添加企业群发消息模板
```php
$msg = [
'external_userid' => [
'woAJ2GCAAAXtWyujaWJHDDGi0mACas1w',
'wmqfasd1e1927831291723123109r712',
],
'sender' => 'zhangsan',
'text' => [
'content' => '文本消息内容',
],
'image' => [
'media_id' => 'MEDIA_ID',
],
'link' => [
'title' => '消息标题',
'picurl' => 'https://example.pic.com/path',
'desc' => '消息描述',
'url' => 'https://example.link.com/path',
],
'miniprogram' => [
'title' => '消息标题',
'pic_media_id' => 'MEDIA_ID',
'appid' => 'wx8bd80126147df384',
'page' => '/path/index',
],
];
$app->external_contact_message->submit($msg);
// {
// "errcode": 0,
// "errmsg": "ok",
// "fail_list":["wmqfasd1e19278asdasdasd"],
// "msgid":"msgGCAAAXtWyujaWJHDDGi0mACas1w"
// }
```
### 获取企业群发消息发送结果
```php
$msgId = 'msgGCAAAXtWyujaWJHDDGi0mACas1w';
$app->external_contact_message->get($msgId);
```
### 发送新客户欢迎语
```php
$welcomeCode = 'WELCOMECODE';
$msg = [
'text' => [
'content' => '文本消息内容',
],
'image' => [
'media_id' => 'MEDIA_ID',
],
'link' => [
'title' => '消息标题',
'picurl' => 'https://example.pic.com/path',
'desc' => '消息描述',
'url' => 'https://example.link.com/path',
],
'miniprogram' => [
'title' => '消息标题',
'pic_media_id' => 'MEDIA_ID',
'appid' => 'wx8bd80126147df384',
'page' => '/path/index',
],
];
$app->external_contact_message->sendWelcome($welcomeCode, $msg);
```
## 数据统计
### 获取员工行为数据
```php
$userIds = [
'zhangsan',
'lisi'
];
$from = 1536508800;
$to = 1536940800;
$app->external_contact_statistics->userBehavior($userIds, $from, $to);
```
================================================
FILE: docs/src/4.x/wework/group-robot.md
================================================
# 群机器人
## 使用说明
使用前必须先在群组里面添加机器人,然后将 `Webhook 地址` 中的 `key` 取出来,作为示例中 `$groupKey` 的值。
> Webhook 地址示例:
> 微信文档:
## 发送文本类型消息
快速发送文本消息
```php
// 获取 Messenger 实例
$messenger = $app->group_robot_messenger;
// 群组 key
$groupKey = 'ab4f609a-3feb-427c-ae9d-b319ca712d36';
$messenger->message('大家好,我是本群的"喝水提醒小助手"')->toGroup($groupKey)->send();
// 或者写成
$messenger->toGroup($groupKey)->send('大家好,我是本群的"喝水提醒小助手"');
```
使用 `Text` 发送文本消息
```php
use EasyWeChat\Work\GroupRobot\Messages\Text;
// 准备消息
$text = new Text('hello');
// 发送
$messenger->message($text)->toGroup($groupKey)->send();
```
@某人:
```php
use EasyWeChat\Work\GroupRobot\Messages\Text;
// 通过构造函数传参
$text = new Text('hello', 'her-cat', '18700000000');
//$text = new Text('hello', ['her-cat', 'overtrue'], ['18700000000', '18700000001']);
// 通过 userId
$text->mention('her-cat');
//$text->mention(['her-cat', 'overtrue']);
// 通过手机号
$text->mentionByMobile('18700000000');
//$text->mentionByMobile(['18700000000', '18700000001']);
// @所有人
$text->mention('@all');
//$text->mentionByMobile('@all');
$messenger->message($text)->toGroup($groupKey)->send();
```
## 发送 Markdown 类型消息
```php
use EasyWeChat\Work\GroupRobot\Messages\Markdown;
$content = '
# 标题一
## 标题二
绿色
灰色
橙红色
> 引用文字
';
$markdown = new Markdown($content);
$messenger->message($markdown)->toGroup($groupKey)->send();
```
## 发送图片类型消息
```php
use EasyWeChat\Work\GroupRobot\Messages\Image;
$img = file_get_contents('http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png');
$image = new Image(base64_encode($img), md5($img));
$result = $messenger->message($image)->toGroup($groupKey)->send();
```
## 发送图文类型消息
```php
use EasyWeChat\Work\GroupRobot\Messages\News;
use EasyWeChat\Work\GroupRobot\Messages\NewsItem;
$items = [
new NewsItem([
'title' => '中秋节礼品领取',
'description' => '今年中秋节公司有豪礼相送',
'url' => 'https://easywechat.com',
'image' => 'http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png',
]),
//...
];
$news = new News($items);
$messenger->message($news)->toGroup($groupKey)->send();
```
## 其他方式
使用 `group_robot` 发送消息。
```php
$app->group_robot->message('大家好,我是本群的"喝水提醒小助手"')->toGroup($groupKey)->send();
```
================================================
FILE: docs/src/4.x/wework/index.md
================================================
## 企业微信
企业微信的使用与公众号以及其它几个应用的使用方式都是一致的,使用 `\EasyWeChat\Factory::work($config)` 来初始化:
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'agent_id' => 100020, // 如果有 agend_id 则填写
'secret' => 'xxxxxxxxxx',
// 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
'response_type' => 'array',
'log' => [
'level' => 'debug',
'file' => __DIR__.'/wechat.log',
],
];
$app = Factory::work($config);
```
然后你就可以用 `$app` 来调用企业微信的服务了。
================================================
FILE: docs/src/4.x/wework/invoice.md
================================================
# 电子发票
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxx',
//...
];
$app = Factory::work($config);
```
## 查询电子发票
https://work.weixin.qq.com/api/doc#11631
API:
```php
mixed get(string $cardId, string $encryptCode)
```
example:
```php
$app->invoice->get('CARDID', 'ENCRYPTCODE');
```
## 批量查询电子发票
https://work.weixin.qq.com/api/doc#11974
API:
```php
mixed select(array $invoices)
```
> $invoices: 发票参数列表
example:
```php
$invoices = [
["card_id" => "CARDID1", "encrypt_code" => "ENCRYPTCODE1"],
["card_id" => "CARDID2", "encrypt_code" => "ENCRYPTCODE2"]
];
$app->invoice->select($invoices);
```
## 更新发票状态
https://work.weixin.qq.com/api/doc#11633
API:
```php
mixed update(string $cardId, string $encryptCode, string $status)
```
> $status: 发报销状态
>
> > - INVOICE_REIMBURSE_INIT:发票初始状态,未锁定;
> > - INVOICE_REIMBURSE_LOCK:发票已锁定,无法重复提交报销;
> > - INVOICE_REIMBURSE_CLOSURE:发票已核销,从用户卡包中移除
## 批量更新发票状态
https://work.weixin.qq.com/api/doc#11633
API:
```php
mixed batchUpdate(array $invoices, string $openid, string $status)
```
example:
```php
$invoices = [
["card_id" => "CARDID1", "encrypt_code" => "ENCRYPTCODE1"],
["card_id" => "CARDID2", "encrypt_code" => "ENCRYPTCODE2"]
];
$openid = 'oV-gpwSU3xlMXbq0PqqRp1xHu9O4';
$status = 'INVOICE_REIMBURSE_CLOSURE';
$app->invoice->batchUpdate($invoices, $openid, $status)
```
================================================
FILE: docs/src/4.x/wework/media.md
================================================
# 临时素材
它的使用是不基于应用的,或者说基于任何一个应用都能访问这些 API,所以在用法上是直接调用 work 实例的 `media` 属性:
**上传的媒体文件限制:**
所有文件size必须大于5个字节
> - 图片(image):2MB,支持JPG,PNG格式
> - 语音(voice):2MB,播放长度不超过60s,支持AMR格式
> - 视频(video):10MB,支持MP4格式
> - 普通文件(file):20MB
## 上传图片
> 注意:微信图片上传服务有敏感检测系统,图片内容如果含有敏感内容,如色情,商品推广,虚假信息等,上传可能失败。
```php
$app->media->uploadImage($path); // $path 为本地文件路径
```
## 上传声音
```php
$app->media->uploadVoice($path);
```
## 上传视频
```php
$app->media->uploadVideo($path, $title, $description);
```
## 上传普通文件
```php
$app->media->uploadFile($path);
```
## 获取素材
```php
$app->media->get($mediaId);
```
## 上传附件资源
所有文件size必须大于5个字节
目前 商品图册只支持图片类型; 朋友圈只支持图片、视频类型
> - 图片(image):10MB,支持JPG,PNG格式,朋友圈类型图片不超过1440 x 1080
> - 视频(video) :10MB,支持MP4格式,朋友圈类型视频时长不超过30秒
> - 文件(file) :10MB
```php
$app->media->uploadAttachmentResources($path, 'image', 1);
```
================================================
FILE: docs/src/4.x/wework/menu.md
================================================
# 自定义菜单
自定义菜单是指为单个应用设置自定义菜单功能,所以在使用时请注意调用正确的应用实例。
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxx', // 应用的 secret
//...
];
$app = Factory::work($config);
```
## 创建菜单
```php
$menus = [
'button' => [
[
'name' => '首页',
'type' => 'view',
'url' => 'https://easywechat.com'
],
[
'name' => '关于我们',
'type' => 'view',
'url' => 'https://easywechat.com/about'
],
//...
],
];
$app->menu->create($menus);
```
## 获取菜单
```php
$app->menu->get();
```
## 删除菜单
```php
$app->menu->delete();
```
================================================
FILE: docs/src/4.x/wework/message.md
================================================
# 消息
## 主动发送消息
```php
use EasyWeChat\Kernel\Messages\TextCard;
// 获取 Messenger 实例
$messenger = $app->messenger;
// 准备消息
$message = new TextCard([
'title' => '你的请假单审批通过',
'description' => '单号:1928373, ....',
'url' => 'http://easywechat.com/oa/....'
]);
// 发送
$messenger->message($message)->toUser('overtrue')->send();
```
你也可以很方便的发送普通文本消息:
```php
$messenger->message('你的请假单(单号:1928373)已经审批通过!')->toUser('overtrue')->send();
// 或者写成
$messenger->toUser('overtrue')->send('你的请假单(单号:1928373)已经审批通过!');
```
## 接收消息
被动接收消息,与回复消息,请参考:[服务端](server)
================================================
FILE: docs/src/4.x/wework/oa.md
================================================
# OA
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxx',
//...
];
$app = Factory::work($config);
```
## 获取打卡数据
API:
```php
mixed checkinRecords(int $startTime, int $endTime, array $userList, int $type = 3)
```
> $type: 打卡类型 1:上下班打卡;2:外出打卡;3:全部打卡
```php
// 全部打卡数据
$app->oa->checkinRecords(1492617600, 1492790400, ["james","paul"]);
// 获取上下班打卡
$app->oa->checkinRecords(1492617600, 1492790400, ["james","paul"], 1);
// 获取外出打卡
$app->oa->checkinRecords(1492617600, 1492790400, ["james","paul"], 2);
```
## 获取审批数据
API:
```php
mixed approvalRecords(int $startTime, int $endTime, int $nextNumber = null)
```
> $nextNumber: 第一个拉取的审批单号,不填从该时间段的第一个审批单拉取
```php
$app->oa->approvalRecords(1492617600, 1492790400);
// 指定第一个拉取的审批单号,不填从该时间段的第一个审批单拉取
$app->oa->approvalRecords(1492617600, 1492790400, '201704240001');
```
================================================
FILE: docs/src/4.x/wework/oauth.md
================================================
# OAuth
> 此文档为企业微信内部应用开发的网页授权
[企业微信官方文档](https://work.weixin.qq.com/api/doc#90000/90135/91020)
创建实例:
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxx', // 应用的 secret
'agent_id' => 100001,
];
$app = Factory::work($config);
```
## 跳转授权
```php
// $callbackUrl 为授权回调地址
$callbackUrl = 'https://xxx.xxx'; // 需设置可信域名
// 返回一个 redirect 实例
$redirect = $app->oauth->redirect($callbackUrl);
// 获取企业微信跳转目标地址
$targetUrl = $redirect->getTargetUrl();
// 直接跳转到企业微信授权
$redirect->send();
```
## 获取授权用户信息
在回调页面中,你可以使用以下方式获取授权者信息:
```php
$user = $app->oauth->detailed()->user();
// 获取用户信息
$user->getId(); // 对应企业微信英文名(userid)
$user->getOriginal(); // 获取企业微信接口返回的原始信息
```
获取用户其他信息需调用通讯录接口,参考:[企业微信通讯录 API](https://github.com/EasyWeChat/docs/blob/master/wework/contacts.md)
```php
```
================================================
FILE: docs/src/4.x/wework/server.md
================================================
## 服务端
我们在企业微信应用开启接收消息的功能,将设置页面的 token 与 aes key 配置到 agents 下对应的应用内:
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'agent_id' => 100022,
'secret' => 'xxxxxxxxxx',
// server config
'token' => 'xxxxxxxxx',
'aes_key' => 'xxxxxxxxxxxxxxxxxx',
//...
];
$app = Factory::work($config);
```
接着配置服务端与公众号的服务端用法一样:
```php
$app->server->push(function(){
return 'Hello easywechat.';
});
$response = $app->server->serve();
$response->send();
```
`$response` 为 `Symfony\Component\HttpFoundation\Response` 实例,根据你的框架情况来决定如何处理响应。
================================================
FILE: docs/src/5.x/basic-services/content_security.md
================================================
# 内容安全接口
## 文本安全内容检测
用于校验一段文本是否含有违法内容。
### 频率限制
单个appid调用上限为2000次/分钟,1,000,000次/天
### 调用示例
```php
// 传入要检测的文本内容,长度不超过500K字节
$content = '你好';
$result = $app->content_security->checkText($content);
// 正常返回 0
{
"errcode": "0",
"errmsg": "ok"
}
//当 $content 内含有敏感信息,则返回 87014
{
"errcode": 87014,
"errmsg": "risky content"
}
```
## 图片安全内容检测
用于校验一张图片是否含有敏感信息。如涉黄、涉及敏感人脸(通常是政治人物)。
### 频率限制
单个appid调用上限为1000次/分钟,100,000次/天
### 调用示例
```php
// 所传参数为要检测的图片文件的绝对路径,图片格式支持PNG、JPEG、JPG、GIF, 像素不超过 750 x 1334,同时文件大小以不超过 300K 为宜,否则可能报错
$result = $app->content_security->checkImage('/path/to/the/image');
// 正常返回 0
{
"errcode": "0",
"errmsg": "ok"
}
// 当图片文件内含有敏感内容,则返回 87014
{
"errcode": 87014,
"errmsg": "risky content"
}
```
## 重要说明
目前上述两个接口仅支持在小程序中使用,示例中的 `$app` 表示小程序实例,即:
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'wx3cf0f39249eb0exx',
'secret' => 'f1c242f4f28f735d4687abb469072axx',
// 下面为可选项
// 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
'response_type' => 'array',
'log' => [
'level' => 'debug',
'file' => __DIR__.'/wechat.log',
],
];
$app = Factory::miniProgram($config);
```
================================================
FILE: docs/src/5.x/basic-services/jssdk.md
================================================
# JSSDK
微信 JSSDK 官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
## API
#### 获取JSSDK的配置数组
```php
$app->jssdk->buildConfig(array $APIs, $debug = false, $beta = false, $json = true, array $openTagList = []);
```
默认返回 JSON 字符串,当 `$json` 为 `false` 时返回数组,你可以直接使用到网页中。
#### 设置当前URL
```php
$app->jssdk->setUrl($url)
```
如果不想用默认读取的URL,可以使用此方法手动设置,通常不需要。
#### 示例
我们可以生成js配置文件:
```js
```
结果如下:
```js
```
================================================
FILE: docs/src/5.x/basic-services/media.md
================================================
# 临时素材
上传的临时多媒体文件有格式和大小限制,如下:
> - 图片(image): 2M,支持 `JPG` 格式
> - 语音(voice):2M,播放长度不超过 `60s`,支持 `AMR\MP3` 格式
> - 视频(video):10MB,支持 `MP4` 格式
> - 缩略图(thumb):64KB,支持 `JPG` 格式
## 上传图片
> 注意:微信图片上传服务有敏感检测系统,图片内容如果含有敏感内容,如色情,商品推广,虚假信息等,上传可能失败。
```php
$app->media->uploadImage($path);
```
## 上传声音
```php
$app->media->uploadVoice($path);
```
## 上传视频
```php
$app->media->uploadVideo($path, $title, $description);
```
## 上传缩略图
用于视频封面或者音乐封面。
```php
$app->media->uploadThumb($path);
```
## 上传群发视频
上传视频获取 `media_id` 用以创建群发消息用。
```php
$app->media->uploadVideoForBroadcasting($path, $title, $description);
//{
// "media_id": "rF4UdIMfYK3efUfyoddYRMU50zMiRmmt_l0kszupYh_SzrcW5Gaheq05p_lHuOTQ",
// "title": "TITLE",
// "description": "Description"
//}
```
## 创建群发消息
不要与上面 **上传群发视频** 搞混了,上面一个是上传视频得到 `media_id`,这个是使用该 `media_id` 加标题描述 **创建一条消息素材** 用来发送给用户。详情参见:[消息群发](../official-account/broadcasting.md)
```php
$app->media->createVideoForBroadcasting($mediaId, $title, $description);
//{
// "type":"video",
// "media_id":"IhdaAQXuvJtGzwwc0abfXnzeezfO0NgPK6AQYShD8RQYMTtfzbLdBIQkQziv2XJc",
// "created_at":1398848981
//}
```
## 获取临时素材内容
比如图片、语音等二进制流内容,响应为 `EasyWeChat\Kernel\Http\StreamResponse` 实例。
```php
$stream = $app->media->get($mediaId);
if ($stream instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
// 以内容 md5 为文件名存到本地
$stream->save('保存目录');
// 自定义文件名,不需要带后缀
$stream->saveAs('保存目录', '文件名');
}
```
## 获取 JSSDK 上传的高清语音
```php
$stream = $app->media->getJssdkMedia($mediaId);
$stream->saveAs('保存目录', 'custom-name.speex');
```
================================================
FILE: docs/src/5.x/basic-services/qrcode.md
================================================
# 二维码
目前有 2 种类型的二维码:
1. 临时二维码,是有过期时间的,最长可以设置为在二维码生成后的 **30天**后过期,但能够生成较多数量。临时二维码主要用于帐号绑定等不要求二维码永久保存的业务场景
2. 永久二维码,是无过期时间的,但数量较少(目前为最多10万个)。永久二维码主要用于适用于帐号绑定、用户来源统计等场景。
## 创建临时二维码
```php
$result = $app->qrcode->temporary('foo', 6 * 24 * 3600);
// Array
// (
// [ticket] => gQFD8TwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyTmFjVTRWU3ViUE8xR1N4ajFwMWsAAgS2uItZAwQA6QcA
// [expire_seconds] => 518400
// [url] => http://weixin.qq.com/q/02NacU4VSubPO1GSxj1p1k
// )
```
## 创建永久二维码
```php
$result = $app->qrcode->forever(56);// 或者 $app->qrcode->forever("foo");
// Array
// (
// [ticket] => gQFD8TwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyTmFjVTRWU3ViUE8xR1N4ajFwMWsAAgS2uItZAwQA6QcA
// [url] => http://weixin.qq.com/q/02NacU4VSubPO1GSxj1p1k
// )
```
## 获取二维码网址
```php
$url = $app->qrcode->url($ticket);
// https://api.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET
```
## 获取二维码内容
```php
$url = $app->qrcode->url($ticket);
$content = file_get_contents($url); // 得到二进制图片内容
file_put_contents(__DIR__ . '/code.jpg', $content); // 写入文件
```
================================================
FILE: docs/src/5.x/basic-services/url.md
================================================
# 短网址服务
主要使用场景: 开发者用于生成二维码的原链接(商品、支付二维码等)太长导致扫码速度和成功率下降,将原长链接通过此接口转成短链接再生成二维码将大大提升扫码速度和成功率。
## 长链接转短链接
```php
$shortUrl = $app->url->shorten('https://easywechat.com');
//
(
[errcode] => 0
[errmsg] => ok
[short_url] => https://w.url.cn/s/Aq7jWrd
)
```
================================================
FILE: docs/src/5.x/contributing.md
================================================
# 贡献代码
## 开发
我们欢迎广大开发者贡献大家的智慧,让我们共同让它变得更完美.
### 开始之前
请严格遵循以下代码标准:
> - [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md).
> - 使用 4 个空格作为缩进。
### 流程
1. Fork [overtrue/wechat](https://github.com/overtrue/wechat) 到本地.
2. 创建新的分支:
```shell
$ git checkout -b new_feature
```
3. 编写代码。
4. Push 到你的分支:
```shell
$ git push origin new_feature
```
5. 创建 Pull Request 并描述你完成的功能或者做出的修改。
> 注意:注释请使用英文
## 更新文档
我们的文档也是开源的,源代码在 [w7corp/EasyWeChat/docs](https://github.com/w7corp/easywechat/tree/master/docs)。
### 流程
1. Fork [w7corp/EasyWeChat](https://github.com/w7corp/easywechat)
2. Clone 到你的电脑:
```shell
$ git clone https://github.com//site.git
$ cd docs
```
3. 创建新的分支,编辑文档
4. Push 到你的分支。
5. 创建 Pull Request 并描述你完成的功能或者做出的修改。
## 报告 Bug
当你在使用过程中遇到问题,请查阅 [疑难解答](troubleshooting.html) 或者在这里提问 [GitHub](https://github.com/overtrue/wechat/issues). 如果还是不能解决你的问题,请到 GitHub 联系我们。
[overtrue/wechat]: https://github.com/overtrue/wechat
================================================
FILE: docs/src/5.x/customize/access_token.md
================================================
# Access Token
我们一个 SDK 应用在初始化以后,你可以在任何时机从应用中拿到该配置下的 Access Token 实例:
```php
use EasyWeChat\Factory;
$config = [
//...
];
$app = Factory::officialAccount($config);
// 获取 access token 实例
$accessToken = $app->access_token;
$token = $accessToken->getToken(); // token 数组 token['access_token'] 字符串
$token = $accessToken->getToken(true); // 强制重新从微信服务器获取 token.
```
## 修改 `$app` 的 Access Token
```php
$app['access_token']->setToken($newAccessToken, 7200);
```
例如:
```php
$app['access_token']->setToken('ccfdec35bd7ba359f6101c2da321d675');
// 或者指定过期时间
$app['access_token']->setToken('ccfdec35bd7ba359f6101c2da321d675', 3600); // 单位:秒
```
================================================
FILE: docs/src/5.x/customize/cache.md
================================================
# 缓存
本项目使用 [symfony/cache](https://github.com/symfony/cache) 来完成缓存工作,它支持基本目前所有的缓存引擎。
在我们的 SDK 中的所有缓存默认使用文件缓存,缓存路径取决于 PHP 的临时目录,如果你需要自定义缓存,那么你需要做如下的事情:
你可以参考[symfony/cache官方文档](https://symfony.com/doc/current/components/cache.html) 来替换掉应用中默认的缓存配置:
## 以 redis 为例
### Symfony 4.3 +
> 请先安装 redis 拓展:`composer require predis/predis`
```php
use Symfony\Component\Cache\Adapter\RedisAdapter;
// 创建 redis 实例
$client = new \Predis\Client('tcp://10.0.0.1:6379');
// 创建缓存实例
$cache = new RedisAdapter($client);
// 替换应用中的缓存
$app->rebind('cache', $cache);
```
### Symfony 3.4 +
> 请先安装 redis 拓展:https://github.com/phpredis/phpredis
```php
use Symfony\Component\Cache\Simple\RedisCache;
// 创建 redis 实例
$redis = new Redis();
$redis->connect('redis_host', 6379);
// 创建缓存实例
$cache = new RedisCache($redis);
// 替换应用中的缓存
$app->rebind('cache', $cache);
```
### Laravel 中使用
在 Laravel 中框架使用 [predis/predis](https://github.com/nrk/predis):
### Symfony 4.3 +
> 请先安装 redis 拓展:`composer require predis/predis`
```php
use Symfony\Component\Cache\Adapter\RedisAdapter;
// 创建缓存实例
$cache = new RedisAdapter(app('redis')->connection()->client());
$app->rebind('cache', $cache);
```
### Symfony 3.4 +
```php
use Symfony\Component\Cache\Simple\RedisCache;
$predis = app('redis')->connection()->client(); // connection($name), $name 默认为 `default`
$cache = new RedisCache($predis);
$app->rebind('cache', $cache);
```
> 上面提到的 `app('redis')->connection($name)`, 这里的 `$name` 是 laravel 项目中配置文件 `database.php` 中 `redis` 配置名 `default`:https://github.com/laravel/laravel/blob/master/config/database.php#L118
> 如果你使用的其它连接,对应传名称就好了。
## 使用自定义的缓存方式
如果你发现 symfony 提供的十几种缓存方式都满足不了你的需求的话,那么你可以自己建立一个类来完成缓存操作,前提这个类得实现接口:[PSR-16](http://www.php-fig.org/psr/psr-16/)
该接口有以下方法需要实现:
```php
public function get($key, $default = null);
public function set($key, $value, $ttl = null);
public function delete($key);
public function clear();
public function getMultiple($keys, $default = null);
public function setMultiple($values, $ttl = null);
public function deleteMultiple($keys);
public function has($key);
```
下面为一个示例:
```php
rebind('cache', new MyCustomCache());
```
OK,这样就完成了自定义缓存的操作。
================================================
FILE: docs/src/5.x/customize/replace-service.md
================================================
# 自定义服务模块
由于使用了容器模式来组织各模块的实例,意味着你可以比较容易的替换掉已经有的服务,以公众号服务为例:
```php
<...>
$app = Factory::officialAccount($config);
$app->rebind('request', new MyCustomRequest(...));
```
这里的 `request` 为 SDK 内部服务名称。
================================================
FILE: docs/src/5.x/index.md
================================================
> 👋🏼 您当前浏览的文档为 5.x,其它版本的文档请参考:[6.x](/6.x/)、[4.x](/4.x/)、[3.x](/3.x/)
# EasyWeChat
EasyWeChat 是一个开源的 [微信](http://www.wechat.com) 非官方 SDK。安装非常简单,因为它是一个标准的 [Composer](https://getcomposer.org/) 包,这意味着任何满足下列安装条件的 PHP 项目支持 Composer 都可以使用它。
## 环境要求
> - PHP >= 7.4
> - [PHP cURL 扩展](http://php.net/manual/en/book.curl.php)
> - [PHP OpenSSL 扩展](http://php.net/manual/en/book.openssl.php)
> - [PHP SimpleXML 扩展](http://php.net/manual/en/book.simplexml.php)
> - [PHP fileinfo 拓展](http://php.net/manual/en/book.fileinfo.php)
Laravel 5 拓展包: [overtrue/laravel-wechat](https://github.com/overtrue/laravel-wechat)
# 参与贡献
1. fork 当前库到你的名下
2. 选择你想要修改的语言版本,`zh-CN` 或者 `en`
3. 在你的本地修改完成审阅过后提交到你的仓库
4. 提交 PR 并描述你的修改,等待合并
# License
MIT
================================================
FILE: docs/src/5.x/installation.md
================================================
# 安装
## 环境要求
> - PHP >= 7.4
> - [PHP cURL 扩展](http://php.net/manual/en/book.curl.php)
> - [PHP OpenSSL 扩展](http://php.net/manual/en/book.openssl.php)
> - [PHP SimpleXML 扩展](http://php.net/manual/en/book.simplexml.php)
> - [PHP fileinfo 拓展](http://php.net/manual/en/book.fileinfo.php)
Laravel 5 拓展包: [overtrue/laravel-wechat](https://github.com/overtrue/laravel-wechat)
## 安装
使用 [composer](http://getcomposer.org/):
```shell
$ composer require overtrue/wechat:~5.0 -vvv
```
================================================
FILE: docs/src/5.x/integration.md
================================================
# 在框架中使用
EasyWeChat 是一个通用的 Composer 包,所以不需要对框架单独做修改,只要支持 Composer 就能直接使用,当然了,为了更方便的使用,我们收集了以下框架单独提供的拓展包:
## Laravel
> - [overtrue/laravel-wechat](https://github.com/overtrue/laravel-wechat)
## Symfony
> - [lilocon/WechatBundle](https://github.com/lilocon/WechatBundle)
## Yii
> - [jianyan74/yii2-easy-wechat](https://github.com/jianyan74/yii2-easy-wechat) 适用于 EasyWeChat 4.x
> - [max-wen/yii2-easy-wechat](https://github.com/max-wen/yii2-easy-wechat) 适用于 EasyWeChat 3.x
## ThinkPHP
> - [naixiaoxin/think-wechat](https://github.com/qiqizjl/think-wechat) 适用于 EasyWeChat 4.x
> - [zyan/think-wechat](https://github.com/aa24615/think-wechat) 适用于 EasyWeChat 4.x/5.x
## CI
TODO
## Phalcon
TODO
... more
================================================
FILE: docs/src/5.x/micro-merchant/certficates.md
================================================
# 获取平台证书
调用获取平台证书接口之前,请前往微信支付商户平台升级API证书,升级后才可成功调用本接口。
```php
// 获取到证书后可以做缓存处理,无需每次重新获取
$response = $app->certficates->get(bool $returnRaw = false);
// 获取到平台证书后,可以直接使用 setCertificate 方法把证书配置追加到配置项里面去
$app->setCertificate(string $certificate, string $serialNo);
```
> $returnRaw 不填默认为false时,请确保你的PHP已安装了sodium扩展
> 返回值:固定array格式的解密后的证书信息
> $returnRaw 传入true时
> 返回值:Response对象`$response->getBody()->getContents();`获取到微信返回xml原始数据
================================================
FILE: docs/src/5.x/micro-merchant/index.md
================================================
# 小微商户
你在阅读本文之前确认你已经仔细阅读了:[微信小微商户专属接口文档](https://pay.weixin.qq.com/wiki/doc/api/xiaowei.php?chapter=19_2)。
## 配置
小微商户整体接口调用方式相对于其他微信接口略有不同,配置时请勿填错,相关配置如下:
```php
use EasyWeChat\Factory;
$config = [
// 必要配置
'mch_id' => 'your-mch-id', // 服务商的商户号
'key' => 'key-for-signature', // API 密钥
'apiv3_key' => 'APIv3-key-for-signature', // APIv3 密钥
// API 证书路径(登录商户平台下载 API 证书)
'cert_path' => 'path/to/your/cert.pem', // XXX: 绝对路径!!!!
'key_path' => 'path/to/your/key', // XXX: 绝对路径!!!!
// 以下两项配置在获取证书接口时可为空,在调用入驻接口前请先调用获取证书接口获取以下两项配置,如果获取过证书可以直接在这里配置,也可参照本文档获取平台证书章节中示例
// 'serial_no' => '获取证书接口获取到的平台证书序列号',
// 'certificate' => '获取证书接口获取到的证书内容'
// 以下为可选项
// 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
'response_type' => 'array'
'appid' => 'wx931386123456789e' // 服务商的公众账号 ID
];
$app = Factory::microMerchant($config);
```
`$app` 在所有相关小微商户的文档都是指 `Factory::microMerchant` 得到的实例,就不在每个页面单独写了。
## 使用时值得注意的地方:
1、小微商户所有接口中以下列出参数 `version`, `mch_id`, `nonce_str`, `sign`, `sign_type`, `cert_sn` 可不用传入。
2、所有敏感信息无需手动加密,sdk会在调用接口前自动完成加密
3、在调用入驻等需要敏感信息加密的接口前请先调用获取证书接口然后把配置填入配置项
4、入驻成功获取到子商户号后需帮助子商户调用配置修改等接口可以先调用以下方法,方便调用修改等接口时无需再次传入子商户号
```php
// $subMchId 为子商户号
// $appid 服务商的公众账号 ID
$app->setSubMchId(string $subMchId, string $appId = '');
```
================================================
FILE: docs/src/5.x/micro-merchant/material.md
================================================
# 商户信息修改
## 修改结算银行卡
```php
$response = $app->material->setSettlementCard([
// 'sub_mch_id' => '1230000109',
'account_number' => '银行卡号',
'bank_name' => '开户银行全称(含支行)',
'account_bank' => '开户银行',
'bank_address_code' => '开户银行省市编码',
]);
```
## 修改联系信息
```php
$response = $app->material->updateContact([
// 'sub_mch_id' => '1230000109',
'mobile_phone' => '手机号',
'email' => '邮箱',
'merchant_name' => '商户简称',
]);
```
> 以上接口调用过 `setSubMchId` 方法则无需传入 `sub_mch_id` 参数
================================================
FILE: docs/src/5.x/micro-merchant/media.md
================================================
# 图片上传
上传证件照片。支持 jpeg、jpg、bmp、png 格式,图片大小不超过2M。
```php
// $path string 图片路径
$response = $app->media->upload($path);
```
================================================
FILE: docs/src/5.x/micro-merchant/merchant-config.md
================================================
# 小微商户配置
## 关注功能配置
```php
$response = $app->merchantConfig->setFollowConfig(string $subAppId, string $subscribeAppId, string $receiptAppId = '', string $subMchId = '');
```
> 注意:`subscribe_appid`,`receipt_appid` 两个参数二选一,两个都填的话SDK默认选第一个,具体请参考小微商户专属文档
## 开发配置新增支付目录
```php
$response = $app->merchantConfig->addPath(string $jsapiPath, string $appId = '', string $subMchId = '');
```
## 新增对应APPID关联
```php
$response = $app->merchantConfig->bindAppId(string $subAppId, string $appId = '', string $subMchId = '');
```
## 开发配置查询
```php
$response = $app->merchantConfig->getConfig(string $subMchId = '', string $appId = '');
```
> 以上接口调用过 `setSubMchId` 方法并且两个参数都传入过 则无需传入 `sub_mch_id` 和 `appid` 参数
================================================
FILE: docs/src/5.x/micro-merchant/submit-application.md
================================================
# 商户入驻
## 申请入驻
使用申请入驻接口提交你的小微商户资料。
```php
$result = $app->submitApplication([
'business_code' => '123456', // 业务申请编号
'id_card_copy' => 'media_id', // 身份证人像面照片
// ...
// 参数太多就不一一列出,自行根据 (小微商户专属文档 -> 申请入驻api) 填写
]);
```
## 查询申请状态
使用申请入驻接口提交小微商户资料后,一般5分钟左右可以通过该查询接口查询具体的申请结果。
```php
$applymentId = '商户申请单号(applyment_id 申请入驻接口返回)';
$businessCode = '业务申请编号(business_code)';
$app->getStatus(string $applymentId, string $businessCode = '');
```
> 商户申请单号和业务申请编号填写一个就行了,当 `applyment_id` 已填写时,`business_code` 字段无效。
当查询申请状态为待签约,接口会一并返回签约二维码,服务商需引导商户使用本人微信扫码完成协议签署。
================================================
FILE: docs/src/5.x/micro-merchant/upgrade.md
================================================
# 商户升级
## 提交升级申请单
使用“提交升级申请单”接口为小微商户发起升级流程,根据商户实际情况可升级为个体户、企业、党政、机关及事业单位、其他组织。。
```php
$result = $app->upgrade([
'organization_type' => '2', // 主体类型
'business_license_copy' => 'media_id', // 营业执照扫描件
// ...
// 参数太多就不一一列出,自行根据 (小微商户专属文档 -> 提交升级申请单API) 填写
]);
```
## 查询升级申请单状态
使用“提交升级申请单”接口后,可不定期调用此接口查询申请单状态(建议提交申请后1分钟查询),直至申请单为“完成”状态。
1)若申请状态为待账户验证,请按接口中的指引完成账户验证
2)若申请状态为审核中,微信支付会在2个工作日内完成资料审核
3)若申请状态为待签约,接口会返回签约二维码
```php
$app->getUpgradeStatus(string $subMchId = '');
```
> 调用该接口前调用过 `setSubMchId` 方法则无需传入 `$subMchId` 参数
================================================
FILE: docs/src/5.x/micro-merchant/withdraw.md
================================================
# 提现相关
## 查询提现状态
```php
$response = $app->withdraw->queryWithdrawalStatus($date, $subMchId = '');
```
## 重新发起提现
```php
$response = $app->withdraw->requestWithdraw($date, $subMchId = '');
```
> 以上接口调用过 `setSubMchId` 方法则无需传入 `sub_mch_id` 参数
================================================
FILE: docs/src/5.x/mini-program/activity_message.md
================================================
# 动态消息
小程序动态消息功能允许开发者创建可变更的消息内容,在特定条件下更新消息显示内容。
## 获取实例
```php
$activityMessage = $app->activity_message;
```
## 基础功能
### 创建动态消息活动ID
创建用于发送动态消息的活动ID:
```php
$result = $activityMessage->createActivityId();
```
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"activity_id": "xxx",
"expiration_time": 1635724800
}
```
**参数说明:**
- `activity_id` string 活动ID,用于后续消息更新
- `expiration_time` int 活动过期时间戳
### 更新动态消息
更新已发送的动态消息内容:
```php
$params = [
'member_count' => 2, // 参与人数
'room_limit' => 4, // 房间人数上限
'path' => 'pages/room?room_id=123', // 页面路径
'version_type' => 'develop' // 版本类型:develop, trial, release
];
$result = $activityMessage->updateMessage(
'activity_id_xxx', // 活动ID
1, // 目标状态:0-参与前 1-参与后
$params // 更新参数
);
```
**参数说明:**
- `activityId` string 活动ID
- `state` int 目标状态:0-参与前状态 1-参与后状态
- `params` array 消息参数
- `member_count` int 参与人数
- `room_limit` int 房间人数上限
- `path` string 小程序页面路径
- `version_type` string 版本类型
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok"
}
```
## 使用场景
### 游戏房间动态消息
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'your-app-id',
'secret' => 'your-app-secret',
// ...
];
$app = Factory::miniProgram($config);
$activityMessage = $app->activity_message;
// 1. 创建活动ID
$activity = $activityMessage->createActivityId();
if ($activity['errcode'] === 0) {
$activityId = $activity['activity_id'];
echo "活动ID创建成功: {$activityId}\n";
// 2. 用户发送消息时附带活动ID
// 在发送消息接口中使用 activity_id
// 3. 当房间状态变化时更新消息
// 例如:有新用户加入房间
$updateParams = [
'member_count' => 3, // 当前3人
'room_limit' => 4, // 最多4人
'path' => 'pages/game/room?id=room_123'
];
$updateResult = $activityMessage->updateMessage($activityId, 1, $updateParams);
if ($updateResult['errcode'] === 0) {
echo "消息更新成功,房间现在有3人\n";
}
}
```
### 拼团活动动态消息
```php
// 创建拼团活动的动态消息
$activity = $activityMessage->createActivityId();
if ($activity['errcode'] === 0) {
$activityId = $activity['activity_id'];
// 模拟拼团过程中的状态更新
$groupBuyingStates = [
['member_count' => 1, 'room_limit' => 5, 'state' => 0], // 发起拼团
['member_count' => 3, 'room_limit' => 5, 'state' => 0], // 3人参与
['member_count' => 5, 'room_limit' => 5, 'state' => 1], // 拼团成功
];
foreach ($groupBuyingStates as $index => $stateData) {
$params = [
'member_count' => $stateData['member_count'],
'room_limit' => $stateData['room_limit'],
'path' => 'pages/group-buy/detail?group_id=gb_123'
];
$result = $activityMessage->updateMessage($activityId, $stateData['state'], $params);
if ($result['errcode'] === 0) {
echo "拼团状态更新: {$stateData['member_count']}/{$stateData['room_limit']}人\n";
}
// 模拟时间间隔
sleep(1);
}
}
```
### 实时竞赛动态消息
```php
// 创建竞赛活动的动态消息
$activity = $activityMessage->createActivityId();
if ($activity['errcode'] === 0) {
$activityId = $activity['activity_id'];
// 竞赛报名阶段
$registrationParams = [
'member_count' => 8, // 已报名8人
'room_limit' => 20, // 最多20人
'path' => 'pages/contest/detail?contest_id=c_123'
];
$activityMessage->updateMessage($activityId, 0, $registrationParams);
echo "竞赛报名中: 8/20人\n";
// 竞赛开始阶段
$startParams = [
'member_count' => 20, // 满员开始
'room_limit' => 20,
'path' => 'pages/contest/live?contest_id=c_123'
];
$activityMessage->updateMessage($activityId, 1, $startParams);
echo "竞赛开始: 20/20人 已开始\n";
}
```
### 直播间动态消息
```php
// 直播间观众数量变化
$activity = $activityMessage->createActivityId();
if ($activity['errcode'] === 0) {
$activityId = $activity['activity_id'];
// 模拟直播间观众数量变化
$viewerCounts = [10, 25, 50, 100, 250];
foreach ($viewerCounts as $count) {
$params = [
'member_count' => $count,
'room_limit' => 1000, // 直播间容量
'path' => 'pages/live/room?live_id=live_123'
];
// 根据观众数量决定状态
$state = $count >= 100 ? 1 : 0; // 超过100人为热门状态
$result = $activityMessage->updateMessage($activityId, $state, $params);
if ($result['errcode'] === 0) {
$status = $state ? '🔥热门' : '📺直播中';
echo "直播间更新: {$status} {$count}人观看\n";
}
sleep(2); // 模拟时间间隔
}
}
```
### 队伍组建动态消息
```php
function updateTeamMessage($activityMessage, $activityId, $currentMembers, $maxMembers, $teamId) {
$params = [
'member_count' => $currentMembers,
'room_limit' => $maxMembers,
'path' => "pages/team/detail?team_id={$teamId}"
];
// 队伍满员时切换到完成状态
$state = ($currentMembers >= $maxMembers) ? 1 : 0;
$result = $activityMessage->updateMessage($activityId, $state, $params);
if ($result['errcode'] === 0) {
$status = $state ? '✅已满员' : '🚀招募中';
echo "队伍状态: {$status} {$currentMembers}/{$maxMembers}人\n";
return true;
}
return false;
}
// 使用示例
$activity = $activityMessage->createActivityId();
if ($activity['errcode'] === 0) {
$activityId = $activity['activity_id'];
// 模拟队伍成员逐渐加入
for ($i = 1; $i <= 5; $i++) {
updateTeamMessage($activityMessage, $activityId, $i, 5, 'team_abc123');
sleep(1);
}
}
```
## 注意事项
1. **活动ID有效期**:活动ID有过期时间,过期后无法更新消息
2. **更新频率限制**:消息更新有频率限制,不要过于频繁调用
3. **状态一致性**:确保传递的参数与实际业务状态一致
4. **页面路径有效性**:确保path参数指向的页面存在且可访问
5. **版本类型**:根据小程序发布状态选择正确的version_type
## 最佳实践
1. **合理使用场景**:动态消息适用于多人协作、实时状态变化的场景
2. **状态管理**:清晰定义参与前后的状态差异
3. **用户体验**:确保消息更新能够提供有价值的信息
4. **错误处理**:做好活动ID过期和更新失败的处理
5. **数据同步**:保持消息内容与实际业务数据同步
## 错误码说明
| 错误码 | 说明 |
|--------|------|
| 0 | 成功 |
| -1 | 系统繁忙,此时请开发者稍候再试 |
| 40001 | 获取access_token时AppSecret错误 |
| 40013 | 不合法的AppID |
| 41001 | 缺少access_token参数 |
| 45009 | 接口调用超过限额 |
| 47001 | 参数错误 |
| 47501 | 一天只能创建100个活动ID |
| 47502 | 活动ID已过期 |
| 47503 | 状态值错误 |
================================================
FILE: docs/src/5.x/mini-program/app_code.md
================================================
# 小程序码
## 获取小程序码
### 接口A: 适用于需要的码数量较少的业务场景
API:
```
$app->app_code->get(string $path, array $optional = []);
```
其中 `$optional` 为以下可选参数:
> - **width** Int - 默认 430 二维码的宽度
> - **auto_color** 默认 false 自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调
> - **line_color** 数组,`auto_color` 为 `false` 时生效,使用 rgb 设置颜色 例如 ,示例:`["r" => 0,"g" => 0,"b" => 0]`。
示例代码:
```php
$response = $app->app_code->get('path/to/page');
// 或者
$response = $app->app_code->get('path/to/page', [
'width' => 600,
//...
]);
// 或者指定颜色
$response = $app->app_code->get('path/to/page', [
'width' => 600,
'line_color' => [
'r' => 105,
'g' => 166,
'b' => 134,
],
]);
// $response 成功时为 EasyWeChat\Kernel\Http\StreamResponse 实例,失败时为数组或者你指定的 API 返回格式
// 保存小程序码到文件
if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
$filename = $response->save('/path/to/directory');
}
// 或
if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
$filename = $response->saveAs('/path/to/directory', 'appcode.png');
}
```
### 接口B:适用于需要的码数量极多,或仅临时使用的业务场景
API:
```
$app->app_code->getUnlimit(string $scene, array $optional = []);
```
> 其中 $scene 必填,$optinal 与 get 方法一致,多一个 page 参数。
示例代码:
```php
$response = $app->app_code->getUnlimit('scene-value', [
'page' => 'path/to/page',
'width' => 600,
]);
// $response 成功时为 EasyWeChat\Kernel\Http\StreamResponse 实例,失败为数组或你指定的 API 返回类型
// 保存小程序码到文件
if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
$filename = $response->save('/path/to/directory');
}
// 或
if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
$filename = $response->saveAs('/path/to/directory', 'appcode.png');
}
```
## 获取小程序二维码
API:
```
$app->app_code->getQrCode(string $path, int $width = null);
```
> 其中 $path 必填,其余参数可留空。
示例代码:
```php
$response = $app->app_code->getQrCode('/path/to/page');
// $response 成功时为 EasyWeChat\Kernel\Http\StreamResponse 实例,失败为数组或你指定的 API 返回类型
// 保存小程序码到文件
if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
$filename = $response->save('/path/to/directory');
}
// 或
if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
$filename = $response->saveAs('/path/to/directory', 'appcode.png');
}
```
##
================================================
FILE: docs/src/5.x/mini-program/auth.md
================================================
# 微信登录
## 根据 jsCode 获取用户 session 信息
API:
```php
$app->auth->session(string $code);
```
================================================
FILE: docs/src/5.x/mini-program/business.md
================================================
# 商户功能
小程序商户功能允许小程序接入商户能力,为小程序提供商户服务相关的接口。
## 获取实例
```php
$business = $app->business;
```
## 商户注册
注册商户账号:
```php
$result = $business->register('商户账号名', '商户昵称', '头像媒体ID');
```
**参数说明:**
- `accountName` string 商户账号名
- `nickname` string 商户昵称
- `iconMediaId` string 头像媒体ID
## 获取商户信息
可以通过商户ID或账号名获取商户信息:
```php
// 通过商户ID获取
$result = $business->getBusiness($businessId);
// 通过账号名获取
$result = $business->getBusiness(0, 'account_name');
```
**参数说明:**
- `businessId` int 商户ID
- `accountName` string 商户账号名
## 获取商户列表
获取商户列表,支持分页:
```php
$result = $business->list($offset, $count);
```
**参数说明:**
- `offset` int 偏移量,默认为0
- `count` int 返回数量,默认为10
## 更新商户信息
更新商户昵称和头像:
```php
$result = $business->update($businessId, '新昵称', '新头像媒体ID');
```
**参数说明:**
- `businessId` int 商户ID
- `nickname` string 新昵称(可选)
- `iconMediaId` string 新头像媒体ID(可选)
## 发送消息
### 构建消息
```php
$message = $business->message('消息内容');
```
### 发送消息
```php
$message = [
'touser' => 'openid',
'msgtype' => 'text',
'text' => [
'content' => '消息内容'
],
'business_id' => $businessId
];
$result = $business->send($message);
```
## 设置输入状态
显示"正在输入"状态:
```php
$result = $business->typing($businessId, $toUser);
```
**参数说明:**
- `businessId` int 商户ID
- `toUser` string 用户openid
## 完整示例
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'your-app-id',
'secret' => 'your-app-secret',
// ...
];
$app = Factory::miniProgram($config);
$business = $app->business;
// 注册商户
$result = $business->register('test_merchant', '测试商户', 'media_id_123');
if ($result['errcode'] === 0) {
$businessId = $result['business_id'];
// 发送消息
$message = [
'touser' => 'user_openid',
'msgtype' => 'text',
'text' => [
'content' => '欢迎使用商户服务!'
],
'business_id' => $businessId
];
$business->send($message);
}
```
================================================
FILE: docs/src/5.x/mini-program/customer_service.md
================================================
# 客服消息
## 获取实例
```php
$service = $app->customer_service;
```
> 使用方法详看公众号-客服消息章节。
================================================
FILE: docs/src/5.x/mini-program/data_cube.md
================================================
# 数据统计与分析
获取小程序概况趋势:
```php
$app->data_cube->summaryTrend('20170313', '20170313')
```
开始日期与结束日期的格式为 yyyymmdd。
## API
> - `summaryTrend(string $from, string $to);` 概况趋势
> - `dailyVisitTrend(string $from, string $to);` 访问日趋势
> - `weeklyVisitTrend(string $from, string $to);` 访问周趋势
> - `monthlyVisitTrend(string $from, string $to);` 访问月趋势
> - `visitDistribution(string $from, string $to);` 访问分布
> - `dailyRetainInfo(string $from, string $to);` 访问日留存
> - `weeklyRetainInfo(string $from, string $to);` 访问周留存
> - `monthlyRetainInfo(string $from, string $to);` 访问月留存
> - `visitPage(string $from, string $to);` 访问页面
> - `userPortrait(string $from, string $to);` 用户画像分布数据
================================================
FILE: docs/src/5.x/mini-program/decrypt.md
================================================
# 微信小程序消息解密
## 比如获取电话等功能,信息是加密的,需要解密。
API:
```php
$decryptedData = $app->encryptor->decryptData($session, $iv, $encryptedData);
```
================================================
FILE: docs/src/5.x/mini-program/express.md
================================================
# 物流助手 电子面单
## 获取支持的快递公司列表
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/express/by-business/logistics.getAllDelivery.html
```php
$app->express->listProviders();
{
"count": 8,
"data": [
{
"delivery_id": "BEST",
"delivery_name": "百世快递"
},
...
]
}
```
## 生成运单
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/express/by-business/logistics.addOrder.html
```php
$app->express->createWaybill($data);
// 成功返回
{
"order_id": "01234567890123456789",
"waybill_id": "123456789",
"waybill_data": [
{
"key": "SF_bagAddr",
"value": "广州"
},
{
"key": "SF_mark",
"value": "101- 07-03 509"
}
]
}
// 失败返回
{
"errcode": 9300501,
"errmsg": "delivery logic fail",
"delivery_resultcode": 10002,
"delivery_resultmsg": "客户密码不正确"
}
```
## 取消运单
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/express/by-business/logistics.cancelOrder.html
```php
$app->express->deleteWaybill($data);
```
## 获取运单数据
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/express/by-business/logistics.getOrder.html
```php
$app->express->getWaybill($data);
```
## 查询运单轨迹
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/express/by-business/logistics.getPath.html
```php
$app->express->getWaybillTrack($data);
```
## 获取电子面单余额。
仅在使用加盟类快递公司时,才可以调用。
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/express/by-business/logistics.getQuota.html
```php
$app->express->getBalance($deliveryId, $bizId);
// 例如:
$app->express->getBalance('YTO', 'xyz');
```
## 绑定打印员
若需要使用微信打单 PC 软件,才需要调用。
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/express/by-business/logistics.updatePrinter.html
```php
$app->express->bindPrinter($openid);
```
## 解绑打印员
若需要使用微信打单 PC 软件,才需要调用。
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/express/by-business/logistics.updatePrinter.html
```php
$app->express->unbindPrinter($openid);
```
================================================
FILE: docs/src/5.x/mini-program/index.md
================================================
# 小程序
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'wx3cf0f39249eb0exx',
'secret' => 'f1c242f4f28f735d4687abb469072axx',
// 下面为可选项
// 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
'response_type' => 'array',
'log' => [
'level' => 'debug',
'file' => __DIR__.'/wechat.log',
],
];
$app = Factory::miniProgram($config);
```
`$app` 在所有相关小程序的文档都是指 `Factory::miniProgram` 得到的实例,就不在每个页面单独写了。
================================================
FILE: docs/src/5.x/mini-program/live.md
================================================
# 订阅消息
> 微信文档:https://developers.weixin.qq.com/miniprogram/dev/framework/liveplayer/live-player-plugin.html
> tips:微信规定以下两个接口调用限制共享 **500次/天** 建议开发者自己做缓存,合理分配调用频次。
## 获取直播房间列表
```php
$app->live->getRooms();
```
## 获取回放源视频
```php
$roomId = 1; //直播房间id
$app->live->getPlaybacks($roomId);
```
================================================
FILE: docs/src/5.x/mini-program/mall.md
================================================
# 微信小商店
微信小商店是微信官方提供的电商能力,小程序可以通过相关接口管理商品、订单等。
## 获取实例
```php
$mall = $app->mall;
```
## 商品管理
### 导入或更新商品
批量导入或更新商品信息:
```php
$products = [
[
'product_id' => 'product_001',
'title' => '商品标题',
'sub_title' => '商品副标题',
'head_imgs' => ['图片URL1', '图片URL2'],
'category_id' => 1234,
'brand_id' => 5678,
'model' => '型号',
'third_cat_id' => 9012,
'product_type' => 1,
'qualification_pics' => ['资质图片URL'],
'src_wxapp_path' => 'pages/product/detail?id=123',
'skus' => [
[
'sku_id' => 'sku_001',
'price' => 9900, // 以分为单位
'original_price' => 12900,
'status' => 1, // 1:上架 0:下架
'stock_num' => 100,
'sku_attrs' => [
['attr_key' => '颜色', 'attr_value' => '红色'],
['attr_key' => '尺寸', 'attr_value' => 'L']
]
]
]
]
];
$result = $mall->product->import($products, false); // false表示正式环境
```
### 查询商品信息
查询商品详细信息:
```php
$params = [
'product_id' => 'product_001',
'need_edit_spu' => 1
];
$result = $mall->product->query($params);
```
### 获取商品状态
```php
$result = $mall->product->getStatus(['product_001', 'product_002']);
```
### 更新商品状态
```php
$result = $mall->product->updateStatus([
['product_id' => 'product_001', 'status' => 1], // 1:上架 0:下架
['product_id' => 'product_002', 'status' => 0]
]);
```
## 购物车管理
### 添加商品到购物车
```php
$params = [
'user_open_id' => 'user_openid',
'sku_product_id' => 'product_001',
'sku_id' => 'sku_001',
'num' => 2
];
$result = $mall->cart->add($params);
```
### 获取购物车商品
```php
$params = [
'user_open_id' => 'user_openid'
];
$result = $mall->cart->get($params);
```
### 删除购物车商品
```php
$params = [
'user_open_id' => 'user_openid',
'sku_product_id' => 'product_001',
'sku_id' => 'sku_001'
];
$result = $mall->cart->delete($params);
```
## 订单管理
### 生成订单
```php
$orderData = [
'create_time' => time(),
'type' => 1,
'order_id' => 'order_' . time(),
'openid' => 'user_openid',
'union_id' => 'user_unionid',
'product_infos' => [
[
'product_id' => 'product_001',
'sku_id' => 'sku_001',
'product_cnt' => 2,
'sale_price' => 9900,
'head_img' => '商品图片URL',
'title' => '商品标题',
'path' => 'pages/product/detail?id=123'
]
],
'pay_info' => [
'pay_method' => '微信支付',
'pay_method_type' => 1,
'prepay_id' => 'prepay_id_xxx',
'prepay_time' => time()
],
'price_info' => [
'order_price' => 19800,
'freight' => 1000,
'discounted_price' => 0,
'additional_price' => 0,
'additional_remarks' => ''
],
'delivery_info' => [
'delivery_type' => 1,
'receiver_name' => '张三',
'detailed_address' => '详细地址',
'tel_number' => '13800138000',
'country' => '中国',
'province' => '北京市',
'city' => '北京市',
'town' => '朝阳区'
]
];
$result = $mall->order->add($orderData);
```
### 更新订单状态
```php
$params = [
'order_id' => 'order_123',
'status' => 2, // 订单状态
'action_type' => 1, // 操作类型
'action_remark' => '操作备注'
];
$result = $mall->order->updateStatus($params);
```
### 批量获取订单
```php
$params = [
'start_create_time' => strtotime('-30 days'),
'end_create_time' => time(),
'last_index' => '', // 分页标识
'page_size' => 10
];
$result = $mall->order->list($params);
```
## 媒体文件管理
### 上传图片
```php
$result = $mall->media->uploadImg('/path/to/image.jpg');
```
### 获取图片
```php
$result = $mall->media->getImg('media_id');
```
## 完整示例
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'your-app-id',
'secret' => 'your-app-secret',
// ...
];
$app = Factory::miniProgram($config);
$mall = $app->mall;
// 导入商品
$products = [
[
'product_id' => 'test_product_001',
'title' => '测试商品',
'sub_title' => '这是一个测试商品',
'head_imgs' => ['https://example.com/img1.jpg'],
'category_id' => 1234,
'skus' => [
[
'sku_id' => 'sku_001',
'price' => 9900,
'original_price' => 12900,
'status' => 1,
'stock_num' => 100
]
]
]
];
$result = $mall->product->import($products);
if ($result['errcode'] === 0) {
echo "商品导入成功\n";
// 查询商品信息
$productInfo = $mall->product->query(['product_id' => 'test_product_001']);
print_r($productInfo);
}
```
## 注意事项
1. 商品价格以分为单位
2. 图片需要先上传到微信服务器获取media_id或使用HTTPS URL
3. 商品分类ID需要从微信官方获取
4. 订单状态变更需要按照微信规范进行
5. API调用频率有限制,请合理控制调用频次
================================================
FILE: docs/src/5.x/mini-program/nearby_poi.md
================================================
# 附近的小程序
> 微信文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/nearby-poi/nearbyPoi.add.html
## 添加地点
```php
$params = [
'kf_info' => '{"open_kf":true,"kf_headimg":"http://mmbiz.qpic.cn/mmbiz_jpg/kKMgNtnEfQzDKpLXYhgo3W3Gndl34gITqmP914zSwhajIEJzUPpx40P7R8fRe1QmicneQMhFzpZNhSLjrvU1pIA/0?wx_fmt=jpeg","kf_name":"Harden"}',
'pic_list' => '{"list":["http://mmbiz.qpic.cn/mmbiz_jpg/kKMgNtnEfQzDKpLXYhgo3W3Gndl34gITqmP914zSwhajIEJzUPpx40P7R8fRe1QmicneQMhFzpZNhSLjrvU1pIA/0?wx_fmt=jpeg","http://mmbiz.qpic.cn/mmbiz_jpg/kKMgNtnEfQzDKpLXYhgo3W3Gndl34gITRneE5FS9uYruXGMmrtmhsBySwddEWUGOibG8Ze2NT5E3Dyt79I0htNg/0?wx_fmt=jpeg"]}',
'service_infos' => '{"service_infos":[{"id":2,"type":1,"name":"快递","appid":"wx1373169e494e0c39","path":"index"},{"id":0,"type":2,"name":"自定义","appid":"wx1373169e494e0c39","path":"index"}]}',
'store_name' => '羊村小马烧烤',
'contract_phone' => '111111111',
'hour' => '00:00-11:11',
'company_name' => '深圳市腾讯计算机系统有限公司',
'credential' => '156718193518281',
'address' => '新疆维吾尔自治区克拉玛依市克拉玛依区碧水路15-1-8号(碧水云天广场)',
'qualification_list' => '3LaLzqiTrQcD20DlX_o-OV1-nlYMu7sdVAL7SV2PrxVyjZFZZmB3O6LPGaYXlZWq',
];
$app->nearby_poi->add($params);
```
## 更新地点
```php
$poiId = 'xxxxxxxx';
$params = [
'kf_info' => '{"open_kf":true,"kf_headimg":"http://mmbiz.qpic.cn/mmbiz_jpg/kKMgNtnEfQzDKpLXYhgo3W3Gndl34gITqmP914zSwhajIEJzUPpx40P7R8fRe1QmicneQMhFzpZNhSLjrvU1pIA/0?wx_fmt=jpeg","kf_name":"Harden"}',
'pic_list' => '{"list":["http://mmbiz.qpic.cn/mmbiz_jpg/kKMgNtnEfQzDKpLXYhgo3W3Gndl34gITqmP914zSwhajIEJzUPpx40P7R8fRe1QmicneQMhFzpZNhSLjrvU1pIA/0?wx_fmt=jpeg","http://mmbiz.qpic.cn/mmbiz_jpg/kKMgNtnEfQzDKpLXYhgo3W3Gndl34gITRneE5FS9uYruXGMmrtmhsBySwddEWUGOibG8Ze2NT5E3Dyt79I0htNg/0?wx_fmt=jpeg"]}',
'service_infos' => '{"service_infos":[{"id":2,"type":1,"name":"快递","appid":"wx1373169e494e0c39","path":"index"},{"id":0,"type":2,"name":"自定义","appid":"wx1373169e494e0c39","path":"index"}]}',
'contract_phone' => '111111111',
'hour' => '00:00-11:11',
'company_name' => '深圳市腾讯计算机系统有限公司',
'credential' => '156718193518281',
'address' => '新疆维吾尔自治区克拉玛依市克拉玛依区碧水路15-1-8号(碧水云天广场)',
'qualification_list' => '3LaLzqiTrQcD20DlX_o-OV1-nlYMu7sdVAL7SV2PrxVyjZFZZmB3O6LPGaYXlZWq',
];
$app->nearby_poi->update($poiId, $params);
```
## 删除地点
```php
$poiId = 'xxxxxxxx';
$app->nearby_poi->delete($poiId);
```
## 地点列表
```php
$page = 1;
$pageRows = 10;
$app->nearby_poi->list($page, $pageRows);
```
## 设置地点展示状态
```php
$poiId = 'xxxxxxxx';
$status = 0; // 0: 不展示,1:展示
$app->nearby_poi->setVisibility($poiId, $status);
```
================================================
FILE: docs/src/5.x/mini-program/ocr.md
================================================
# OCR 文字识别
小程序OCR功能提供各种文字识别能力,包括身份证、银行卡、驾驶证等证件识别以及通用文字识别。
## 获取实例
```php
$ocr = $app->ocr;
```
## 身份证识别
识别身份证正反面信息:
```php
// 身份证正面
$result = $ocr->idcard($mediaId, 'photo');
// 身份证反面
$result = $ocr->idcard($mediaId, 'reverse');
```
**参数说明:**
- `mediaId` string 图片的媒体ID
- `type` string 识别类型:'photo'(正面) 或 'reverse'(反面)
**返回结果(正面):**
```json
{
"type": "身份证正面",
"name": "张三",
"id": "110101199001011234",
"addr": "北京市东城区...",
"gender": "男",
"nationality": "汉"
}
```
## 银行卡识别
识别银行卡信息:
```php
$result = $ocr->bankcard($mediaId);
```
**返回结果:**
```json
{
"number": "6225881234567890"
}
```
## 驾驶证识别
识别驾驶证信息:
```php
$result = $ocr->driving($mediaId);
```
**返回结果:**
```json
{
"id_num": "110101199001011234",
"name": "张三",
"nationality": "中国",
"sex": "男",
"address": "北京市...",
"birth_date": "1990-01-01",
"issue_date": "2020-01-01",
"car_class": "C1",
"valid_from": "2020-01-01",
"valid_to": "2026-01-01"
}
```
## 行驶证识别
识别行驶证信息:
```php
$result = $ocr->drivingLicense($mediaId);
```
**返回结果:**
```json
{
"vehicle_type": "小型汽车",
"owner": "张三",
"addr": "北京市...",
"use_character": "非营运",
"model": "长安牌SC1019...",
"plate_num": "京A12345",
"vin": "LDC613P23A1050312",
"engine_num": "0123456",
"register_date": "2020-01-01",
"issue_date": "2020-01-01"
}
```
## 营业执照识别
识别营业执照信息:
```php
$result = $ocr->businessLicense($mediaId);
```
**返回结果:**
```json
{
"reg_num": "91110101MA01A1B2C3",
"serial": "12345678",
"legal_representative": "张三",
"enterprise_name": "北京测试公司",
"type_of_organization": "有限责任公司",
"address": "北京市...",
"type_of_enterprise": "私营",
"business_scope": "技术开发...",
"registered_capital": "100万人民币",
"paid_in_capital": "100万人民币",
"valid_period": "2020-01-01至长期",
"registered_date": "2020-01-01",
"cert_position": {
"pos": {
"left_top": {"x": 155, "y": 191},
"right_top": {"x": 725, "y": 157},
"right_bottom": {"x": 743, "y": 512},
"left_bottom": {"x": 164, "y": 539}
}
},
"img_size": {"w": 966, "h": 728}
}
```
## 通用印刷体识别
识别图片中的印刷体文字:
```php
$result = $ocr->printedText($mediaId);
```
**返回结果:**
```json
{
"items": [
{
"text": "腾讯",
"pos": {
"left_top": {"x": 575, "y": 519},
"right_top": {"x": 744, "y": 519},
"right_bottom": {"x": 744, "y": 532},
"left_bottom": {"x": 575, "y": 532}
}
}
],
"img_size": {"w": 1280, "h": 720}
}
```
## 完整示例
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'your-app-id',
'secret' => 'your-app-secret',
// ...
];
$app = Factory::miniProgram($config);
$ocr = $app->ocr;
// 识别身份证正面
$result = $ocr->idcard('media_id_123', 'photo');
if ($result['errcode'] === 0) {
$name = $result['name'];
$idNumber = $result['id'];
$address = $result['addr'];
echo "姓名:{$name}\n";
echo "身份证号:{$idNumber}\n";
echo "地址:{$address}\n";
}
// 识别银行卡
$result = $ocr->bankcard('media_id_456');
if ($result['errcode'] === 0) {
$cardNumber = $result['number'];
echo "银行卡号:{$cardNumber}\n";
}
```
## 注意事项
1. 图片要求:格式支持PNG、JPG、JPEG、BMP,大小不超过1M
2. 证件图片要求清晰,避免模糊、反光、阴影等情况
3. 每个小程序每天有一定的免费识别额度,超出部分按量收费
4. 建议在客户端先对图片进行预处理,如裁剪、旋转等,以提高识别准确率
================================================
FILE: docs/src/5.x/mini-program/phone_number.md
================================================
# 手机号
> 微信文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/phonenumber/phonenumber.getPhoneNumber.html
## 获取手机号
```php
$app->phone_number->getUserPhoneNumber(string $code);
```
================================================
FILE: docs/src/5.x/mini-program/plugin.md
================================================
# 插件管理
> 微信文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/plugin-management/pluginManager.applyPlugin.html
## 申请使用插件
```php
$pluginAppId = 'xxxxxxxxx';
$app->plugin->apply($pluginAppId);
```
## 删除已添加的插件
```php
$pluginAppId = 'xxxxxxxxx';
$app->plugin->unbind($pluginAppId);
```
## 查询已添加的插件
```php
$app->plugin->list();
```
## 获取当前所有插件使用方
```php
$page = 1;
$size = 10;
$app->plugin_dev->getUsers($page, $size);
```
## 同意插件使用申请
```php
$appId = 'wxxxxxxxxxxxxxx';
$app->plugin_dev->agree($appId);
```
## 拒绝插件使用申请
```php
$app->plugin_dev->refuse('拒绝理由');
```
## 删除已拒绝的申请者
```php
$app->plugin_dev->delete();
```
================================================
FILE: docs/src/5.x/mini-program/realtime_log.md
================================================
# 实时日志
小程序实时日志功能允许开发者查询小程序的实时运行日志,帮助定位和解决线上问题。
## 获取实例
```php
$realtimeLog = $app->realtime_log;
```
## 查询实时日志
查询指定时间段内的实时日志:
```php
$result = $realtimeLog->search(
'20230601', // 日期,格式:yyyymmdd
1685577600, // 开始时间戳(秒)
1685581200, // 结束时间戳(秒)
[
'module' => 'default', // 模块名,可选
'keyword' => 'error', // 关键词过滤,可选
'level' => 'error', // 日志级别过滤,可选
'page_size' => 20, // 每页数量,默认20,最大100
'page_num' => 1 // 页码,从1开始
]
);
```
**参数说明:**
- `date` string 查询日期,格式:yyyymmdd
- `beginTime` int 开始时间戳(秒)
- `endTime` int 结束时间戳(秒)
- `options` array 可选参数
- `module` string 模块名过滤
- `keyword` string 关键词过滤
- `level` string 日志级别过滤(info、warn、error)
- `page_size` int 每页数量,默认20,最大100
- `page_num` int 页码,从1开始
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"data": [
{
"timestamp": 1685577660,
"level": "error",
"module": "default",
"message": "网络请求失败",
"stack": "Error: request timeout\n at ...",
"page": "pages/index/index",
"function": "onLoad",
"line": 25
}
],
"total": 156,
"page_num": 1,
"page_size": 20
}
```
## 使用示例
### 查询错误日志
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'your-app-id',
'secret' => 'your-app-secret',
// ...
];
$app = Factory::miniProgram($config);
$realtimeLog = $app->realtime_log;
// 查询最近1小时的错误日志
$endTime = time();
$beginTime = $endTime - 3600; // 1小时前
$date = date('Ymd', $endTime);
$result = $realtimeLog->search($date, $beginTime, $endTime, [
'level' => 'error',
'page_size' => 50
]);
if ($result['errcode'] === 0) {
echo "总共找到 {$result['total']} 条错误日志\n";
foreach ($result['data'] as $log) {
echo "时间:" . date('Y-m-d H:i:s', $log['timestamp']) . "\n";
echo "页面:{$log['page']}\n";
echo "消息:{$log['message']}\n";
echo "堆栈:{$log['stack']}\n";
echo "---\n";
}
}
```
### 查询特定关键词日志
```php
// 查询包含"支付"关键词的日志
$result = $realtimeLog->search($date, $beginTime, $endTime, [
'keyword' => '支付',
'page_size' => 30
]);
if ($result['errcode'] === 0) {
foreach ($result['data'] as $log) {
echo "级别:{$log['level']}\n";
echo "消息:{$log['message']}\n";
echo "页面:{$log['page']}\n";
echo "---\n";
}
}
```
### 分页查询日志
```php
$pageNum = 1;
$pageSize = 20;
do {
$result = $realtimeLog->search($date, $beginTime, $endTime, [
'page_num' => $pageNum,
'page_size' => $pageSize
]);
if ($result['errcode'] === 0 && !empty($result['data'])) {
echo "第 {$pageNum} 页:\n";
foreach ($result['data'] as $log) {
echo "- {$log['message']}\n";
}
$pageNum++;
// 检查是否还有更多页
$hasMore = ($pageNum - 1) * $pageSize < $result['total'];
} else {
$hasMore = false;
}
} while ($hasMore);
```
### 查询特定模块日志
```php
// 查询自定义模块的日志
$result = $realtimeLog->search($date, $beginTime, $endTime, [
'module' => 'payment', // 假设你在小程序中定义了payment模块
'level' => 'warn'
]);
if ($result['errcode'] === 0) {
echo "支付模块警告日志:\n";
foreach ($result['data'] as $log) {
echo "时间:" . date('Y-m-d H:i:s', $log['timestamp']) . "\n";
echo "函数:{$log['function']}\n";
echo "行号:{$log['line']}\n";
echo "消息:{$log['message']}\n\n";
}
}
```
## 小程序端配置
要使用实时日志功能,需要在小程序端进行相应配置:
### 1. 开启实时日志
在小程序的 `app.js` 中:
```javascript
App({
onLaunch() {
// 开启实时日志
const logger = wx.getRealtimeLogManager();
// 设置日志级别
logger.setFilterMsg('test');
// 记录日志
logger.info('应用启动');
}
});
```
### 2. 记录日志
在需要记录日志的地方:
```javascript
const logger = wx.getRealtimeLogManager();
// 记录信息日志
logger.info('用户操作', { action: 'click', button: 'submit' });
// 记录警告日志
logger.warn('网络慢', { latency: 2000 });
// 记录错误日志
logger.error('请求失败', error);
```
## 注意事项
1. **时间范围限制**:单次查询时间范围不能超过1天
2. **查询频率限制**:API调用有频率限制,请合理控制调用频次
3. **日志保留期**:实时日志通常保留7天
4. **数据量限制**:单次查询最多返回100条日志
5. **权限要求**:需要小程序管理员权限才能查询日志
6. **模块名规范**:模块名建议使用英文,避免特殊字符
## 最佳实践
1. **合理设置查询时间范围**:避免查询过长时间段的日志
2. **使用关键词过滤**:通过关键词快速定位问题日志
3. **分级查询**:先查询error级别,再查询warn和info
4. **结合监控告警**:可以定期查询错误日志,实现简单的监控告警
5. **日志结构化**:在小程序端记录日志时,使用结构化的数据格式
================================================
FILE: docs/src/5.x/mini-program/risk_control.md
================================================
# 风险控制
小程序风险控制功能提供用户安全等级评估能力,帮助开发者识别和防范风险用户。
## 获取实例
```php
$riskControl = $app->risk_control;
```
## 获取用户安全等级
评估用户的安全风险等级:
```php
$params = [
'openid' => 'user_openid', // 用户的openid
'scene' => 1, // 场景值
'mobile_no' => '13800138000', // 手机号(可选)
'client_ip' => '192.168.1.1', // 客户端IP(可选)
'email_address' => 'user@test.com', // 邮箱地址(可选)
'extended_info' => '{"key":"value"}' // 扩展信息(可选)
];
$result = $riskControl->getUserRiskRank($params);
```
**参数说明:**
- `openid` string 用户的openid,必填
- `scene` int 场景值,必填
- `1` 注册
- `2` 营销活动
- `3` 发布信息
- `4` 支付行为
- `5` 其他高风险行为
- `mobile_no` string 用户手机号,可选,有助于提高评估准确性
- `client_ip` string 用户客户端IP,可选
- `email_address` string 用户邮箱,可选
- `extended_info` string 扩展信息,JSON字符串,可选
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"risk_rank": 1,
"unoin_id": "user_union_id"
}
```
**风险等级说明:**
- `0` 风险等级未知
- `1` 风险等级较低
- `2` 风险等级中等
- `3` 风险等级较高
- `4` 风险等级高
## 使用示例
### 注册场景风险评估
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'your-app-id',
'secret' => 'your-app-secret',
// ...
];
$app = Factory::miniProgram($config);
$riskControl = $app->risk_control;
// 用户注册时进行风险评估
$params = [
'openid' => 'oABC123DEF456GHI789',
'scene' => 1, // 注册场景
'mobile_no' => '13800138000',
'client_ip' => '192.168.1.100'
];
$result = $riskControl->getUserRiskRank($params);
if ($result['errcode'] === 0) {
$riskRank = $result['risk_rank'];
switch ($riskRank) {
case 1:
echo "用户风险等级较低,允许注册\n";
// 正常注册流程
break;
case 2:
echo "用户风险等级中等,需要额外验证\n";
// 要求手机号验证
break;
case 3:
case 4:
echo "用户风险等级较高,拒绝注册\n";
// 拒绝注册或要求人工审核
break;
default:
echo "风险等级未知,采用默认策略\n";
break;
}
} else {
echo "风险评估失败:{$result['errmsg']}\n";
// 采用默认安全策略
}
```
### 营销活动风险评估
```php
// 营销活动参与时进行风险评估
$params = [
'openid' => 'user_openid',
'scene' => 2, // 营销活动场景
'client_ip' => $userIp,
'extended_info' => json_encode([
'activity_id' => 'activity_123',
'prize_type' => 'coupon',
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? ''
])
];
$result = $riskControl->getUserRiskRank($params);
if ($result['errcode'] === 0 && $result['risk_rank'] <= 2) {
// 风险等级可接受,允许参与活动
echo "允许参与营销活动\n";
} else {
// 风险等级过高,禁止参与
echo "风险等级过高,禁止参与活动\n";
}
```
### 支付行为风险评估
```php
// 支付前进行风险评估
$params = [
'openid' => 'user_openid',
'scene' => 4, // 支付行为场景
'mobile_no' => $userMobile,
'client_ip' => $userIp,
'extended_info' => json_encode([
'order_amount' => 10000, // 订单金额(分)
'order_id' => 'order_123456',
'payment_method' => 'wechat_pay'
])
];
$result = $riskControl->getUserRiskRank($params);
if ($result['errcode'] === 0) {
$riskRank = $result['risk_rank'];
if ($riskRank <= 1) {
// 低风险,正常支付流程
echo "支付风险低,进入正常支付流程\n";
} elseif ($riskRank == 2) {
// 中等风险,要求额外验证
echo "支付风险中等,要求短信验证\n";
} else {
// 高风险,拒绝支付或人工审核
echo "支付风险高,需要人工审核\n";
}
}
```
### 发布信息风险评估
```php
// 用户发布内容时进行风险评估
$params = [
'openid' => 'user_openid',
'scene' => 3, // 发布信息场景
'client_ip' => $userIp,
'extended_info' => json_encode([
'content_type' => 'text',
'content_length' => 500,
'has_image' => true,
'publish_frequency' => 5 // 今日发布次数
])
];
$result = $riskControl->getUserRiskRank($params);
if ($result['errcode'] === 0) {
if ($result['risk_rank'] <= 2) {
echo "允许发布内容\n";
// 正常发布流程
} else {
echo "发布风险较高,内容需要审核\n";
// 内容进入审核队列
}
}
```
## 最佳实践
### 1. 合理选择场景值
根据实际业务场景选择合适的场景值,不同场景的风险评估策略可能不同。
### 2. 提供充足的用户信息
提供更多的用户信息(如手机号、IP地址等)有助于提高风险评估的准确性。
### 3. 建立分级处理策略
```php
function handleUserRisk($riskRank, $scene) {
switch ($scene) {
case 1: // 注册
return handleRegistrationRisk($riskRank);
case 2: // 营销活动
return handleMarketingRisk($riskRank);
case 4: // 支付
return handlePaymentRisk($riskRank);
default:
return handleDefaultRisk($riskRank);
}
}
function handleRegistrationRisk($riskRank) {
if ($riskRank <= 1) {
return ['action' => 'allow', 'message' => '允许注册'];
} elseif ($riskRank == 2) {
return ['action' => 'verify', 'message' => '需要手机验证'];
} else {
return ['action' => 'deny', 'message' => '拒绝注册'];
}
}
```
### 4. 异常处理
```php
try {
$result = $riskControl->getUserRiskRank($params);
if ($result['errcode'] === 0) {
// 处理正常响应
handleUserRisk($result['risk_rank'], $params['scene']);
} else {
// API调用失败,使用默认策略
logger()->warning('风险评估API调用失败', [
'errcode' => $result['errcode'],
'errmsg' => $result['errmsg']
]);
// 采用保守的默认策略
}
} catch (Exception $e) {
// 网络异常等,使用默认策略
logger()->error('风险评估异常', ['exception' => $e->getMessage()]);
// 采用保守的默认策略
}
```
## 注意事项
1. **API调用频率限制**:请合理控制API调用频率,避免超出限制
2. **用户隐私保护**:确保用户数据的安全传输和存储
3. **结果缓存**:可以对评估结果进行短期缓存,避免重复调用
4. **降级策略**:当API不可用时,应有合理的降级策略
5. **业务适配**:根据具体业务需求调整风险处理策略
6. **监控告警**:建议对高风险用户行为进行监控和告警
## 错误码说明
| 错误码 | 说明 |
|--------|------|
| 0 | 成功 |
| -1 | 系统繁忙,此时请开发者稍候再试 |
| 40003 | touser字段openid为空或者不正确 |
| 45009 | 接口调用超过限额 |
| 47001 | 参数错误 |
================================================
FILE: docs/src/5.x/mini-program/safety_control.md
================================================
# 安全风控
> 微信文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/safety-control-capability/riskControl.getUserRiskRank.html
> tips: 根据提交的用户信息数据获取用户的安全等级 risk_rank,无需用户授权。
## 获取用户的安全等级
```php
$app->risk_control->getUserRiskRank([
'appid' => 'wx311232323',
'openid' => 'oahdg535ON6vtkUXLdaLVKvzJdmM',
'scene' => 1,
'client_ip' => '12.234.134.2',
]);
```
================================================
FILE: docs/src/5.x/mini-program/search.md
================================================
# 搜索功能
小程序搜索功能允许开发者向微信提交小程序页面信息,提升小程序在微信搜索中的展现效果。
## 获取实例
```php
$search = $app->search;
```
## 提交页面信息
### 提交页面URL
向微信提交小程序页面URL和参数信息,用于搜索收录:
```php
$pages = [
[
'path' => 'pages/product/detail',
'query' => 'id=123&category=electronics'
],
[
'path' => 'pages/article/view',
'query' => 'article_id=456'
],
[
'path' => 'pages/user/profile',
'query' => 'uid=789'
]
];
$result = $search->submitPage($pages);
```
**参数说明:**
- `path` string 页面路径(不包含参数)
- `query` string 页面参数(URL查询字符串格式)
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok"
}
```
## 使用场景
### 电商小程序商品页面提交
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'your-app-id',
'secret' => 'your-app-secret',
// ...
];
$app = Factory::miniProgram($config);
$search = $app->search;
// 批量提交商品页面
function submitProductPages($search, $products) {
$pages = [];
foreach ($products as $product) {
$pages[] = [
'path' => 'pages/product/detail',
'query' => http_build_query([
'id' => $product['id'],
'category' => $product['category'],
'brand' => $product['brand']
])
];
}
// 微信建议每次提交不超过1000个页面
$chunks = array_chunk($pages, 1000);
foreach ($chunks as $chunk) {
$result = $search->submitPage($chunk);
if ($result['errcode'] === 0) {
echo "成功提交 " . count($chunk) . " 个商品页面\n";
} else {
echo "提交失败: {$result['errmsg']}\n";
}
// 避免频率限制
sleep(1);
}
}
// 示例商品数据
$products = [
[
'id' => 'prod_001',
'category' => 'electronics',
'brand' => 'apple'
],
[
'id' => 'prod_002',
'category' => 'clothing',
'brand' => 'nike'
],
[
'id' => 'prod_003',
'category' => 'books',
'brand' => 'penguin'
]
];
submitProductPages($search, $products);
```
### 内容平台页面提交
```php
// 提交文章和视频页面
function submitContentPages($search) {
// 文章页面
$articlePages = [
[
'path' => 'pages/article/detail',
'query' => 'id=1001&category=technology'
],
[
'path' => 'pages/article/detail',
'query' => 'id=1002&category=lifestyle'
]
];
// 视频页面
$videoPages = [
[
'path' => 'pages/video/player',
'query' => 'vid=v001&playlist=tech'
],
[
'path' => 'pages/video/player',
'query' => 'vid=v002&playlist=entertainment'
]
];
// 用户页面
$userPages = [
[
'path' => 'pages/user/profile',
'query' => 'uid=user001'
],
[
'path' => 'pages/user/profile',
'query' => 'uid=user002'
]
];
// 合并所有页面
$allPages = array_merge($articlePages, $videoPages, $userPages);
$result = $search->submitPage($allPages);
if ($result['errcode'] === 0) {
echo "内容页面提交成功,共提交 " . count($allPages) . " 个页面\n";
} else {
echo "提交失败: {$result['errmsg']}\n";
}
}
submitContentPages($search);
```
### 服务类小程序页面提交
```php
// 餐厅预订小程序
function submitRestaurantPages($search) {
$pages = [
// 餐厅详情页
[
'path' => 'pages/restaurant/detail',
'query' => 'restaurant_id=rest001&city=beijing'
],
[
'path' => 'pages/restaurant/detail',
'query' => 'restaurant_id=rest002&city=shanghai'
],
// 菜品页面
[
'path' => 'pages/menu/dish',
'query' => 'dish_id=dish001&restaurant_id=rest001'
],
// 预订页面
[
'path' => 'pages/booking/form',
'query' => 'restaurant_id=rest001&date=2023-12-01'
],
// 活动页面
[
'path' => 'pages/promotion/detail',
'query' => 'promo_id=promo001&type=discount'
]
];
$result = $search->submitPage($pages);
if ($result['errcode'] === 0) {
echo "餐厅页面提交成功\n";
}
}
submitRestaurantPages($search);
```
### 动态页面提交
```php
// 根据业务数据动态生成页面提交
function submitDynamicPages($search, $database) {
$pages = [];
// 从数据库获取最新商品
$latestProducts = $database->getLatestProducts(100);
foreach ($latestProducts as $product) {
$pages[] = [
'path' => 'pages/product/detail',
'query' => http_build_query([
'id' => $product['id'],
'category' => $product['category'],
'keywords' => $product['keywords'],
'price_range' => $product['price_range']
])
];
}
// 获取热门分类页面
$popularCategories = $database->getPopularCategories(20);
foreach ($popularCategories as $category) {
$pages[] = [
'path' => 'pages/category/list',
'query' => http_build_query([
'category_id' => $category['id'],
'sort' => 'popular',
'filter' => json_encode($category['filters'])
])
];
}
// 获取活动页面
$activePromotions = $database->getActivePromotions();
foreach ($activePromotions as $promo) {
$pages[] = [
'path' => 'pages/promotion/detail',
'query' => http_build_query([
'promo_id' => $promo['id'],
'type' => $promo['type'],
'start_time' => $promo['start_time'],
'end_time' => $promo['end_time']
])
];
}
// 分批提交
$batches = array_chunk($pages, 500);
foreach ($batches as $index => $batch) {
$result = $search->submitPage($batch);
if ($result['errcode'] === 0) {
echo "批次 " . ($index + 1) . " 提交成功,包含 " . count($batch) . " 个页面\n";
} else {
echo "批次 " . ($index + 1) . " 提交失败: {$result['errmsg']}\n";
}
// 控制频率
sleep(2);
}
}
// 模拟数据库类
class MockDatabase {
public function getLatestProducts($limit) {
// 返回模拟商品数据
return array_map(function($i) {
return [
'id' => "prod_{$i}",
'category' => ['electronics', 'clothing', 'books'][rand(0, 2)],
'keywords' => "product,item,buy",
'price_range' => rand(1, 5) * 100
];
}, range(1, $limit));
}
public function getPopularCategories($limit) {
return array_map(function($i) {
return [
'id' => "cat_{$i}",
'filters' => ['brand' => 'all', 'price' => 'any']
];
}, range(1, $limit));
}
public function getActivePromotions() {
return [
[
'id' => 'promo_001',
'type' => 'discount',
'start_time' => strtotime('-1 day'),
'end_time' => strtotime('+7 days')
]
];
}
}
$database = new MockDatabase();
submitDynamicPages($search, $database);
```
### 定期更新页面信息
```php
// 定期提交页面信息的任务
function schedulePageSubmission($search) {
// 每日提交新增页面
$dailyNewPages = [
// 今日新增商品
[
'path' => 'pages/product/detail',
'query' => 'id=new_prod_' . date('Ymd') . '&new=true'
],
// 今日文章
[
'path' => 'pages/article/detail',
'query' => 'id=article_' . date('Ymd') . '&date=' . date('Y-m-d')
],
// 今日活动
[
'path' => 'pages/daily/activity',
'query' => 'date=' . date('Y-m-d') . '&type=daily'
]
];
$result = $search->submitPage($dailyNewPages);
if ($result['errcode'] === 0) {
echo date('Y-m-d H:i:s') . " - 每日页面提交成功\n";
} else {
echo date('Y-m-d H:i:s') . " - 提交失败: {$result['errmsg']}\n";
}
}
// 可以放在定时任务中执行
schedulePageSubmission($search);
```
## 注意事项
1. **提交频率限制**:避免短时间内大量调用接口
2. **页面有效性**:确保提交的页面路径真实存在且可访问
3. **参数准确性**:确保query参数与实际页面逻辑匹配
4. **数量限制**:单次提交页面数量有限制
5. **权限要求**:需要小程序管理员权限
## 最佳实践
1. **合理规划提交**:根据业务重要性确定页面提交优先级
2. **参数优化**:在query中包含有助于搜索的关键参数
3. **定期更新**:定期提交新增和更新的页面信息
4. **监控效果**:关注提交后的搜索展现效果
5. **批量处理**:合理分批提交大量页面
## 搜索优化建议
1. **页面标题优化**:确保页面有清晰的标题
2. **关键词布局**:在参数中包含相关关键词
3. **分类标识**:通过参数明确页面分类
4. **时效性信息**:包含时间相关参数提升时效性
5. **用户体验**:确保搜索进入的页面体验良好
## 错误码说明
| 错误码 | 说明 |
|--------|------|
| 0 | 成功 |
| -1 | 系统繁忙,此时请开发者稍候再试 |
| 40001 | 获取access_token时AppSecret错误 |
| 40013 | 不合法的AppID |
| 41001 | 缺少access_token参数 |
| 45009 | 接口调用超过限额 |
| 47001 | 参数错误 |
| 85064 | pages参数错误 |
| 85065 | 单次提交页面数超过限制 |
================================================
FILE: docs/src/5.x/mini-program/shipping.md
================================================
# 小程序发货信息管理
> 微信文档 https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/order-shipping/order-shipping.html
## 发货信息录入接口
```php
$data = [
'order_key' => [
'order_number_type' => 1,
'mchid' => '',
'out_trade_no' => ''
],
'logistics_type' => 4,
'delivery_mode' => 1,
'shipping_list' => [
[
'tracking_no' => '323244567777',
'express_company' => 'DHL',
'item_desc' => '微信红包抱枕*1个',
'contact' => [
'consignor_contact' => '189****1234',
'receiver_contact' => '189****1234'
],
],
],
'upload_time' => '2022-12-15T13:29:35.120+08:00',
'payer' => [
'openid' => 'oUpF8uMuAJO_M2pxb1Q9zNjWeS6o'
]
];
$app->shipping->uploadShippingInfo($data);
```
## 发货信息合单录入接口
```php
$data = [
'order_key' => [
'order_number_type' => 1,
'mchid' => '',
'out_trade_no' => ''
],
'sub_orders' => [
'order_key' => [
'order_number_type' => 1,
'transaction_id' => '',
'mchid' => '',
'out_trade_no' => ''
],
'logistics_type' => 4,
'delivery_mode' => 1,
'shipping_list' => [
[
'tracking_no' => '323244567777',
'express_company' => 'DHL',
'item_desc' => '微信红包抱枕*1个',
'contact' => [
'consignor_contact' => '189****1234',
'receiver_contact' => '189****1234'
],
],
],
],
'upload_time' => '2022-12-15T13:29:35.120+08:00',
'payer' => [
'openid' => 'oUpF8uMuAJO_M2pxb1Q9zNjWeS6o'
]
];
$app->shipping->uploadCombineShippingInfo($data);
```
## 查询订单发货状态
```php
$data = $app->shipping->getOrder([
'transaction_id' => 'xxx'
]);
```
## 查询订单列表
```php
$data = $app->shipping->getOrderList();
```
## 确认收货提醒接口
```php
$data = [
'transaction_id' => '42000020212023112332159214xx',
'received_time' => ''
];
$app->shipping->notifyConfirmReceive($data);
```
## 消息跳转路径设置接口
```php
$data = [
'path' => 'pages/goods/order_detail?id=xxxx',
];
$app->shipping->setMsgJumpPath($data);
```
## 查询小程序是否已开通发货信息管理服务
```php
$app->shipping->isTradeManaged();
```
## 查询小程序是否已完成交易结算管理确认
```php
$app->shipping->isTradeCompleted();
```
================================================
FILE: docs/src/5.x/mini-program/short_link.md
================================================
# Short Link
> 微信文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/short-link/shortlink.generate.html
## 获取小程序 Short Link
```php
$app->short_link->getShortLink(string $pageUrl, string $pageTitle, bool $isPermanent = false);
```
================================================
FILE: docs/src/5.x/mini-program/soter.md
================================================
# 生物认证
## 生物认证秘钥签名验证
> https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/soter/soter.verifySignature.html
```php
$app->soter->verifySignature($openid, $json, $signature);
```
返回值示例:
```json
{
"is_ok": true
}
```
参数说明:
> - string $openid - 用户 openid
> - string $json - 通过 [wx.startSoterAuthentication](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/soter/wx.startSoterAuthentication.html) 成功回调获得的 resultJSON 字段
> - string $signature - 通过 [wx.startSoterAuthentication](https://developers.weixin.qq.com/miniprogram/dev/api/open-api/soter/wx.startSoterAuthentication.html) 成功回调获得的 resultJSONSignature 字段
================================================
FILE: docs/src/5.x/mini-program/subscribe_message.md
================================================
# 订阅消息
> 微信文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.addTemplate.html
## 组合模板并添加至帐号下的个人模板库
```php
$tid = 563; // 模板标题 id,可通过接口获取,也可登录小程序后台查看获取
$kidList = [1, 2]; // 开发者自行组合好的模板关键词列表,可以通过 `getTemplateKeywords` 方法获取
$sceneDesc = '提示用户图书到期'; // 服务场景描述,非必填
$app->subscribe_message->addTemplate($tid, $kidList, $sceneDesc);
```
## 删除帐号下的个人模板
```php
$templateId = 'bDmywsp2oEHjwAadTGKkUHpC0RgBVPvfAM7Cu1s03z8';
$app->subscribe_message->deleteTemplate($templateId);
```
## 获取小程序账号的类目
```php
$app->subscribe_message->getCategory();
```
## 获取模板标题的关键词列表
```php
$tid = 563; // 模板标题 id,可通过接口获取,也可登录小程序后台查看获取
$app->subscribe_message->getTemplateKeywords($tid);
```
## 获取帐号所属类目下的公共模板标题
```php
$ids = [612, 613]; // 类目 id
$start = 0; // 用于分页,表示从 start 开始。从 0 开始计数。
$limit = 30; // 用于分页,表示拉取 limit 条记录。最大为 30。
$app->subscribe_message->getTemplateTitles($ids, $start, $limit);
```
## 获取当前帐号下的个人模板列表
```php
$app->subscribe_message->getTemplates();
```
## 发送订阅消息
```php
$data = [
'template_id' => 'bDmywsp2oEHjwAadTGKkUJ-eJEiMiOf7H-dZ7wjdw80', // 所需下发的订阅模板id
'touser' => 'oSyZp5OBNPBRhG-7BVgWxbiNZm', // 接收者(用户)的 openid
'page' => '', // 点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。
'data' => [ // 模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } }
'date01' => [
'value' => '2019-12-01',
],
'number01' => [
'value' => 10,
],
],
];
$app->subscribe_message->send($data);
```
================================================
FILE: docs/src/5.x/mini-program/template_message.md
================================================
# 模板消息
## 获取小程序模板库标题列表
```
$app->template_message->list($offset, $count);
```
## 获取模板库某个模板标题下关键词库
```
$app->template_message->get($id);
```
## 组合模板并添加至帐号下的个人模板库
```
$app->template_message->add($id, $keywordIdList);
```
## 获取帐号下已存在的模板列表
```
$app->template_message->getTemplates($offset, $count);
```
## 删除帐号下的某个模板
```
$app->template_message->delete($templateId);
```
## 发送模板消息
```php
$app->template_message->send([
'touser' => 'user-openid',
'template_id' => 'template-id',
'page' => 'index',
'form_id' => 'form-id',
'data' => [
'keyword1' => 'VALUE',
'keyword2' => 'VALUE2',
// ...
],
]);
```
================================================
FILE: docs/src/5.x/mini-program/union.md
================================================
# 联盟推广
小程序联盟推广功能允许开发者管理推广计划,通过推广获得佣金收益。
## 获取实例
```php
$union = $app->union;
```
## 推广计划管理
### 创建推广计划
创建新的推广计划:
```php
$result = $union->createPromotion('推广计划名称');
```
**参数说明:**
- `promotionSourceName` string 推广计划名称
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"promotionSourcePid": "10000123",
"promotionSourceName": "推广计划名称"
}
```
### 删除推广计划
删除指定的推广计划:
```php
$result = $union->deletePromotion('10000123', '推广计划名称');
```
**参数说明:**
- `promotionSourcePid` string 推广计划ID
- `promotionSourceName` string 推广计划名称
### 更新推广计划
更新推广计划信息:
```php
$result = $union->updatePromotion('10000123', '新的推广计划名称');
```
**参数说明:**
- `promotionSourcePid` string 推广计划ID
- `promotionSourceName` string 新的推广计划名称
### 获取推广计划列表
获取所有推广计划:
```php
$result = $union->getPromotions();
```
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"promotionList": [
{
"promotionSourcePid": "10000123",
"promotionSourceName": "推广计划1",
"createTime": 1635724800,
"status": 1
}
]
}
```
## 推广商品管理
### 添加推广商品
将商品添加到推广计划:
```php
$result = $union->addProduct('10000123', [
'productId' => 'product_001',
'commissionRate' => 1500 // 佣金比例,单位为万分之一,1500表示15%
]);
```
### 移除推广商品
从推广计划中移除商品:
```php
$result = $union->removeProduct('10000123', 'product_001');
```
### 获取推广商品列表
获取推广计划下的所有商品:
```php
$result = $union->getProducts('10000123', $page, $pageSize);
```
**参数说明:**
- `promotionSourcePid` string 推广计划ID
- `page` int 页码,从1开始
- `pageSize` int 每页数量,最大50
## 订单与佣金
### 获取推广订单
查询推广产生的订单:
```php
$result = $union->getOrders([
'promotionSourcePid' => '10000123',
'startTime' => strtotime('-30 days'),
'endTime' => time(),
'page' => 1,
'pageSize' => 20
]);
```
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"orderList": [
{
"orderId": "order_123456",
"productId": "product_001",
"productName": "商品名称",
"orderAmount": 10000,
"commissionAmount": 1500,
"orderTime": 1635724800,
"status": 2,
"buyerOpenid": "buyer_openid"
}
],
"totalCount": 156
}
```
### 获取佣金明细
查询佣金收益明细:
```php
$result = $union->getCommissions([
'promotionSourcePid' => '10000123',
'startTime' => strtotime('-30 days'),
'endTime' => time(),
'page' => 1,
'pageSize' => 20
]);
```
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"commissionList": [
{
"orderId": "order_123456",
"commissionAmount": 1500,
"commissionTime": 1635724800,
"status": 1,
"settleTime": 1635811200
}
],
"totalAmount": 15000,
"totalCount": 10
}
```
## 推广数据统计
### 获取推广数据概览
```php
$result = $union->getOverview('10000123', [
'startTime' => strtotime('-30 days'),
'endTime' => time()
]);
```
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"data": {
"clickCount": 1520,
"orderCount": 156,
"orderAmount": 1560000,
"commissionAmount": 234000,
"conversionRate": 10.26
}
}
```
### 获取推广趋势数据
```php
$result = $union->getTrend('10000123', [
'startTime' => strtotime('-7 days'),
'endTime' => time(),
'granularity' => 'day' // day, hour
]);
```
## 使用示例
### 完整推广流程示例
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'your-app-id',
'secret' => 'your-app-secret',
// ...
];
$app = Factory::miniProgram($config);
$union = $app->union;
// 1. 创建推广计划
$promotion = $union->createPromotion('春季促销推广');
if ($promotion['errcode'] === 0) {
$pid = $promotion['promotionSourcePid'];
echo "推广计划创建成功,ID: {$pid}\n";
// 2. 添加推广商品
$addProduct = $union->addProduct($pid, [
'productId' => 'spring_product_001',
'commissionRate' => 2000 // 20%佣金
]);
if ($addProduct['errcode'] === 0) {
echo "商品添加成功\n";
// 3. 获取推广链接
$promotionUrl = "https://your-mini-program.com?pid={$pid}&product_id=spring_product_001";
echo "推广链接: {$promotionUrl}\n";
// 4. 查询推广数据
sleep(1); // 模拟等待一段时间后查询
$overview = $union->getOverview($pid, [
'startTime' => strtotime('-1 day'),
'endTime' => time()
]);
if ($overview['errcode'] === 0) {
$data = $overview['data'];
echo "点击数: {$data['clickCount']}\n";
echo "订单数: {$data['orderCount']}\n";
echo "订单金额: " . ($data['orderAmount'] / 100) . "元\n";
echo "佣金收益: " . ($data['commissionAmount'] / 100) . "元\n";
echo "转化率: {$data['conversionRate']}%\n";
}
}
}
```
### 佣金结算示例
```php
// 查询待结算佣金
$commissions = $union->getCommissions([
'promotionSourcePid' => $pid,
'status' => 0, // 0:待结算 1:已结算
'page' => 1,
'pageSize' => 50
]);
if ($commissions['errcode'] === 0) {
$totalPendingCommission = 0;
foreach ($commissions['commissionList'] as $commission) {
$totalPendingCommission += $commission['commissionAmount'];
}
echo "待结算佣金总额: " . ($totalPendingCommission / 100) . "元\n";
echo "待结算订单数: " . count($commissions['commissionList']) . "\n";
}
```
### 推广效果分析
```php
// 获取最近7天的推广趋势
$trend = $union->getTrend($pid, [
'startTime' => strtotime('-7 days'),
'endTime' => time(),
'granularity' => 'day'
]);
if ($trend['errcode'] === 0) {
echo "最近7天推广趋势:\n";
foreach ($trend['data'] as $dayData) {
$date = date('Y-m-d', $dayData['timestamp']);
echo "{$date}: 点击{$dayData['clickCount']}次, 订单{$dayData['orderCount']}个\n";
}
}
// 计算推广ROI
$overview = $union->getOverview($pid, [
'startTime' => strtotime('-30 days'),
'endTime' => time()
]);
if ($overview['errcode'] === 0) {
$data = $overview['data'];
$roi = $data['orderAmount'] > 0 ? ($data['commissionAmount'] / $data['orderAmount']) * 100 : 0;
echo "推广ROI: {$roi}%\n";
}
```
## 注意事项
1. **推广计划限制**:每个小程序的推广计划数量有限制
2. **佣金结算周期**:佣金通常有一定的结算周期,不是实时到账
3. **商品资质要求**:推广的商品需要符合平台规范
4. **数据统计延迟**:推广数据可能有一定延迟
5. **API调用限制**:注意API调用频率限制
## 最佳实践
1. **合理设置佣金比例**:根据商品利润合理设置佣金,既要有吸引力又要保证盈利
2. **数据监控**:定期监控推广数据,及时调整推广策略
3. **推广渠道多样化**:通过多个推广计划覆盖不同的推广渠道
4. **效果追踪**:建立完善的推广效果追踪机制
5. **合规经营**:确保推广活动符合相关法律法规
## 错误码说明
| 错误码 | 说明 |
|--------|------|
| 0 | 成功 |
| -1 | 系统繁忙 |
| 40001 | 获取access_token时AppSecret错误 |
| 40013 | 不合法的AppID |
| 41001 | 缺少access_token参数 |
| 45009 | 接口调用超过限额 |
| 48001 | api功能未授权 |
================================================
FILE: docs/src/5.x/mini-program/url_link.md
================================================
# URL Link
> 微信文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/url-link/urllink.generate.html
> tips: 目前仅针对国内非个人主体的小程序开放.
## 获取小程序 URL Link
```php
$app->url_link->generate(array $params);
```
================================================
FILE: docs/src/5.x/mini-program/url_scheme.md
================================================
# URL Scheme
> 微信文档:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/url-scheme/urlscheme.generate.html
> tips: 目前仅针对国内非个人主体的小程序开放.
## 获取小程序scheme码
```php
$app->url_scheme->generate();
```
================================================
FILE: docs/src/5.x/miscellaneous.md
================================================
# 其它
### 其它
================================================
FILE: docs/src/5.x/official-account/accounts.md
================================================
# 多账号接入
如果你想使用本项目接入多个公众号,在本程序中,您可以为每个帐号都设置一个 id,此 id 对应了该帐号的 appid、token 等信息。
如下表
| id | appId | secret | 其它... |
| ---- | -------------------- | ---------------------------------- | ----- |
| 1 | `wx3cf0f39249eb0e60` | `f28f735d4f1c242f4687abb469072a29` | ... |
| 2 | `wx49eb0e63cf0f39s2` | `8f735d4687abb469f1c2422a29f4f207` | ... |
| N | `wx5cfeb0e60f392490` | `35f8f27d46f1c242f487a9072a29bb46` | ... |
在微信公众平台的设置中,您可以将您帐号中平台的 `url` 设置为 `您的网址/?id=xxx`,如:
```
http://easywechat.com/wechat?id=1
```
而在程序入口处,根据 `id` 查找对应帐号的 `appid` 和 其它信息来创建配置数组创建实例即可。
================================================
FILE: docs/src/5.x/official-account/base.md
================================================
# 基础接口
## 清理接口调用次数
> 此接口官方有每月调用限制,不可随意调用
```php
$app->base->clearQuota();
```
## 获取微信服务器 IP (或IP段)
```php
$app->base->getValidIps();
```
================================================
FILE: docs/src/5.x/official-account/broadcasting.md
================================================
# 群发
微信的群发消息接口有各种乱七八糟的注意事项及限制,具体请阅读微信官方文档。
## 发送消息
以下所有方法均有第二个参数 `$to` 用于指定接收对象:
> - 当 `$to` 为整型时为标签 id
> - 当 `$to` 为数组时为用户的 openid 列表(至少两个用户的 openid)
> - 当 `$to` 为 `null` 时表示全部用户
```php
$app->broadcasting->sendMessage(Message $message, array | int $to = null);
```
下面的别名方法 `sendXXX` 都是基于上面 `sendMessage` 方法的封装。
### 文本消息
```php
$app->broadcasting->sendText("大家好!欢迎使用 EasyWeChat。");
// 指定目标用户
// 至少两个用户的 openid,必须是数组。
$app->broadcasting->sendText("大家好!欢迎使用 EasyWeChat。", [$openid1, $openid2]);
// 指定标签组用户
$app->broadcasting->sendText("大家好!欢迎使用 EasyWeChat。", $tagId); // $tagId 必须是整型数字
```
### 图文消息
```php
$app->broadcasting->sendNews($mediaId);
$app->broadcasting->sendNews($mediaId, [$openid1, $openid2]);
$app->broadcasting->sendNews($mediaId, $tagId);
```
### 图片消息
```php
$app->broadcasting->sendImage($mediaId);
$app->broadcasting->sendImage($mediaId, [$openid1, $openid2]);
$app->broadcasting->sendImage($mediaId, $tagId);
```
### 语音消息
```php
$app->broadcasting->sendVoice($mediaId);
$app->broadcasting->sendVoice($mediaId, [$openid1, $openid2]);
$app->broadcasting->sendVoice($mediaId, $tagId);
```
### 视频消息
用于群发的视频消息,需要先创建消息对象,
```php
// 1. 先上传视频素材用于群发:
$video = '/path/to/video.mp4';
$videoMedia = $app->media->uploadVideoForBroadcasting($video, '视频标题', '视频描述');
// 结果如下:
//{
// "type":"video",
// "media_id":"IhdaAQXuvJtGzwwc0abfXnzeezfO0NgPK6AQYShD8RQYMTtfzbLdBIQkQziv2XJc",
// "created_at":1398848981
//}
// 2. 使用上面得到的 media_id 群发视频消息
$app->broadcasting->sendVideo($videoMedia['media_id']);
```
### 卡券消息
```php
$app->broadcasting->sendCard($cardId);
$app->broadcasting->sendCard($cardId, [$openid1, $openid2]);
$app->broadcasting->sendCard($cardId, $tagId);
```
### 发送预览群发消息给指定的 `openId` 用户
```php
$app->broadcasting->previewText($text, $openId);
$app->broadcasting->previewNews($mediaId, $openId);
$app->broadcasting->previewVoice($mediaId, $openId);
$app->broadcasting->previewImage($mediaId, $openId);
$app->broadcasting->previewVideo($message, $openId);
$app->broadcasting->previewCard($cardId, $openId);
```
### 发送预览群发消息给指定的微信号用户
> $wxanme 是用户的微信号,比如:notovertrue
```php
$app->broadcasting->previewTextByName($text, $wxname);
$app->broadcasting->previewNewsByName($mediaId, $wxname);
$app->broadcasting->previewVoiceByName($mediaId, $wxname);
$app->broadcasting->previewImageByName($mediaId, $wxname);
$app->broadcasting->previewVideoByName($message, $wxname);
$app->broadcasting->previewCardByName($cardId, $wxname);
```
### 删除群发消息
```php
$app->broadcasting->delete($msgId);
```
### 查询群发消息发送状态
```php
$app->broadcasting->status($msgId);
```
================================================
FILE: docs/src/5.x/official-account/card.md
================================================
# 卡券
-
## 获取实例
```php
$card = $app->card;
```
## 通用功能
### 获取卡券颜色
```php
$card->colors();
```
### 卡券开放类目查询
```php
$card->categories();
```
### 创建卡券
创建卡券接口是微信卡券的基础接口,用于创建一类新的卡券,获取 card_id,创建成功并通过审核后,商家可以通过文档提供的其他接口将卡券下发给用户,每次成功领取,库存数量相应扣除。
```php
$card->create($cardType = 'member_card', array $attributes);
```
> - `attributes` array 卡券信息
示例:
```php
[
'brand_name' => '微信餐厅',
'code_type' => 'CODE_TYPE_TEXT',
'title' => '132元双人火锅套餐',
//...
],
'advanced_info' => [
'use_condition' => [
'accept_category' => '鞋类',
'reject_category' => '阿迪达斯',
'can_use_with_other_discount' => true,
],
//...
],
];
$result = $card->create($cardType, $attributes);
```
### 获取卡券详情
```php
$cardInfo = $card->get($cardId);
```
### 批量查询卡列表
```php
$card->list($offset = 0, $count = 10, $statusList = 'CARD_STATUS_VERIFY_OK');
```
> - `offset` int - 查询卡列表的起始偏移量,从 0 开始
> - `count` int - 需要查询的卡片的数量
> - `statusList` - 支持开发者拉出指定状态的卡券列表,详见 example
示例:
```php
// CARD_STATUS_NOT_VERIFY, 待审核;
// CARD_STATUS_VERIFY_FAIL, 审核失败;
// CARD_STATUS_VERIFY_OK, 通过审核;
// CARD_STATUS_USER_DELETE,卡券被商户删除;
// CARD_STATUS_DISPATCH,在公众平台投放过的卡券;
$result = $card->list($offset, $count, 'CARD_STATUS_NOT_VERIFY');
```
### 更改卡券信息接口
支持更新所有卡券类型的部分通用字段及特殊卡券中特定字段的信息。
```php
$card->update($cardId, $type, $attributes = []);
```
> - `type` string - 卡券类型
示例:
```php
$cardId = 'pdkJ9uCzKWebwgNjxosee0ZuO3Os';
$type = 'groupon';
$attributes = [
'base_info' => [
'logo_url' => 'http://mmbiz.qpic.cn/mmbiz/2aJY6aCPatSeibYAyy7yct9zJXL9WsNVL4JdkTbBr184gNWS6nibcA75Hia9CqxicsqjYiaw2xuxYZiaibkmORS2oovdg/0',
'center_title' => '顶部居中按钮',
'center_sub_title' => '按钮下方的wording',
'center_url' => 'http://easywechat.com',
'custom_url_name' => '立即使用',
'custom_url' => 'http://www.qq.com',
'custom_url_sub_title' => '6个汉字tips',
'promotion_url_name' => '更多优惠',
'promotion_url' => 'http://www.qq.com',
],
//...
];
$result = $card->update($cardId, $type, $attributes);
```
### 删除卡券
```php
$card->delete($cardId);
```
### 创建二维码
开发者可调用该接口生成一张卡券二维码供用户扫码后添加卡券到卡包。
自定义 Code 码的卡券调用接口时,POST 数据中需指定 code,非自定义 code 不需指定,指定 openid 同理。指定后的二维码只能被用户扫描领取一次。
```php
$card->createQrCode($cards);
```
> - `cards` array - 卡券相关信息
示例:
```php
// 领取单张卡券
$cards = [
'action_name' => 'QR_CARD',
'expire_seconds' => 1800,
'action_info' => [
'card' => [
'card_id' => 'pdkJ9uFS2WWCFfbbEfsAzrzizVyY',
'is_unique_code' => false,
'outer_id' => 1,
],
],
];
$result = $card->createQrCode($cards);
```
```php
// 领取多张卡券
$cards = [
'action_name' => 'QR_MULTIPLE_CARD',
'action_info' => [
'multiple_card' => [
'card_list' => [
['card_id' => 'pdkJ9uFS2WWCFfbbEfsAzrzizVyY'],
],
],
],
];
$result = $card->createQrCode($cards);
```
请求成功返回值示例:
```json
{
"errcode": 0,
"errmsg": "ok",
"ticket": "gQHB8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL0JIV3lhX3psZmlvSDZmWGVMMTZvAAIEsNnKVQMEIAMAAA==", //获取ticket后需调用换取二维码接口获取二维码图片,详情见字段说明。
"expire_seconds": 1800,
"url": "http://weixin.qq.com/q/BHWya_zlfioH6fXeL16o ",
"show_qrcode_url": "https://mp.weixin.qq.com/cgi-bin/showqrcode? ticket=gQH98DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL0czVzRlSWpsamlyM2plWTNKVktvAAIE6SfgVQMEgDPhAQ%3D%3D"
}
```
### ticket 换取二维码图片
获取二维码 ticket 后,开发者可用 ticket 换取二维码图片。
```php
$card->getQrCode($ticket);
```
> - `ticket` string> - 获取的二维码 ticket,凭借此 ticket 可以在有效时间内换取二维码。
示例:
```php
$ticket = 'gQFF8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL01VTzN0T0hsS1BwUlBBYUszbVN5AAIEughxVwMEAKd2AA==';
$result = $card->getQrCode($ticket);
```
### ticket 换取二维码链接
```php
$card->getQrCodeUrl($ticket);
```
示例:
```php
$ticket = 'gQFF8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL01VTzN0T0hsS1BwUlBBYUszbVN5AAIEughxVwMEAKd2AA==';
$card->getQrCodeUrl($ticket);
```
### 创建货架接口
开发者需调用该接口创建货架链接,用于卡券投放。创建货架时需填写投放路径的场景字段。
```php
$card->createLandingPage($banner, $pageTitle, $canShare, $scene, $cards);
```
> - `banner` string -页面的 banner 图;
> - `pageTitle` string - 页面的 title
> - `canShare` bool - 页面是不是可以分享,true 或 false
> - `scene` string - 投放页面的场景值,具体值请参考下面的 example
> - `cards` array - 卡券列表,每个元素有两个字段
示例:
```php
$banner = 'http://mmbiz.qpic.cn/mmbiz/iaL1LJM1mF9aRKPZJkmG8xXhiaHqkKSVMMWeN3hLut7X7hicFN';
$pageTitle = '惠城优惠大派送';
$canShare = true;
//SCENE_NEAR_BY 附近
//SCENE_MENU 自定义菜单
//SCENE_QRCODE 二维码
//SCENE_ARTICLE 公众号文章
//SCENE_H5 h5页面
//SCENE_IVR 自动回复
//SCENE_CARD_CUSTOM_CELL 卡券自定义cell
$scene = 'SCENE_NEAR_BY';
$cardList = [
['card_id' => 'pdkJ9uLRSbnB3UFEjZAgUxAJrjeY', 'thumb_url' => 'http://test.digilinx.cn/wxApi/Uploads/test.png'],
['card_id' => 'pdkJ9uJ37aU-tyRj4_grs8S45k1c', 'thumb_url' => 'http://test.digilinx.cn/wxApi/Uploads/aa.jpg'],
];
$result = $card->createLandingPage($banner, $pageTitle, $canShare, $scene, $cardList);
```
### 图文消息群发卡券
> 特别注意:目前该接口仅支持填入非自定义 code 的卡券,自定义 code 的卡券需先进行 code 导入后调用。
```php
$card->getHtml($cardId);
```
示例:
```php
$cardId = 'pdkJ9uLCEF_HSKO7JdQOUcZ-PUzo';
$result = $card->getHtml($cardId);
```
### 设置测试白名单
同时支持“openid”、“username”两种字段设置白名单,总数上限为 10 个。
```php
$card->setTestWhitelist($openids); // 使用 openid
$card->setTestWhitelistByName($usernames); // 使用 username
```
> - `openids` array - 测试的 openid 列表
> - `usernames` array> - 测试的微信号列表
示例:
```php
// by openid
$openids = [$openId, $openId2, $openid3...];
$result = $card->setTestWhitelist($openids);
// by username
$usernames = ['tianye0327', 'iovertrue'];
$result = $card->setTestWhitelistByName($usernames);
```
### 获取用户已领取卡券接口
用于获取用户卡包里的,属于该 appid 下所有**可用卡券,包括正常状态和未生效状态**。
```php
$card->getUserCards($openid, $cardId);
```
示例:
```php
$openid = 'odkJ9uDUz26RY-7DN1mxkznfo9xU';
$cardId = ''; // 卡券ID。不填写时默认查询当前 appid 下的卡券。
$result = $card->getUserCards($openid, $cardId);
```
### 设置微信买单接口
```php
$card->setPayCell($cardId, $isOpen = true);
```
> - `isOpen` string - 是否开启买单功能,填 true/false,不填默认 true
示例:
```php
$cardId = 'pdkJ9uH7u11R-Tu1kilbaW_zDFow';
$result = $card->setPayCell($cardId); // isOpen = true
$result = $card->setPayCell($cardId, $isOpen);
```
### 修改库存接口
```php
$card->increaseStock($cardId, $amount); // 增加库存
$card->reductStock($cardId, $amount); // 减少库存
```
> - `cardId` string - 卡券 ID
> - `amount` int - 修改多少库存
示例:
```php
$cardId = 'pdkJ9uLRSbnB3UFEjZAgUxAJrjeY';
$result = $card->increaseStock($cardId, 100);
```
## 卡券 Code
### 导入 code 接口
在自定义 code 卡券成功创建并且通过审核后,必须将自定义 code 按照与发券方的约定数量调用导入 code 接口导入微信后台。
```php
$card->code->deposit($cardId, $codes);
```
> - `cardId` string - 要导入 code 的卡券 ID
> - `codes` array - 要导入微信卡券后台的自定义 code,最多 100 个
示例:
```php
$cardId = 'pdkJ9uLCEF_HSKO7JdQOUcZ-PUzo';
$codes = ['11111', '22222', '33333'];
$result = $card->code->deposit($cardId, $codes);
```
### 查询导入 code 数目
```php
$card->code->getDepositedCount($cardId); // 要导入 code 的卡券 ID
```
示例:
```php
$cardId = 'pdkJ9uLCEF_HSKO7JdQOUcZ-PUzo';
$result = $card->code->getDepositedCount($cardId);
```
### 核查 code 接口
为了避免出现导入差错,强烈建议开发者在查询完 code 数目的时候核查 code 接口校验 code 导入微信后台的情况。
```php
$card->code->check($cardId, $codes);
```
示例:
```php
$cardId = 'pdkJ9uLCEF_HSKO7JdQOUcZ-PUzo';
$codes = ['807732265476', '22222', '33333'];
$result = $card->code->check($cardId, $codes);
```
### 查询 Code 接口
```php
$card->code->get($code, $cardId, $checkConsume = true);
```
> - checkConsume 是否校验 code 核销状态,true 和 false
示例:
```php
$code = '736052543512';
$cardId = 'pdkJ9uDgnm0pKfrTb1yV0dFMO_Gk';
$result = $card->code->get($code, $cardId);
$result = $card->code->get($code, $cardId, false); // check_consume = false
```
### 核销 Code 接口
```php
$card->code->consume($code);
// 或者指定 cardId
$card->code->consume($code, $cardId);
```
示例:
```php
$code = '789248558333';
$cardId = 'pdkJ9uDmhkLj6l5bm3cq9iteQBck';
$result = $card->code->consume($code);
// 或
$result = $card->code->consume($code, $cardId);
```
### Code 解码接口
```php
$card->code->decrypt($encryptedCode);
```
示例:
```php
$encryptedCode = 'XXIzTtMqCxwOaawoE91+VJdsFmv7b8g0VZIZkqf4GWA60Fzpc8ksZ/5ZZ0DVkXdE';
$result = $card->code->decrypt($encryptedCode);
```
### 更改 Code 接口
```php
$card->code->update($code, $newCode, $cardId);
```
> - `newCode` string - 变更后的有效 Code 码
示例:
```php
$code = '148246271394';
$newCode = '659266965266';
$cardId = '';
$result = $card->code->update($code, $newCode, $cardId);
```
### 设置卡券失效
```php
$card->code->disable($code, $cardId);
```
示例:
```php
$code = '736052543512';
$cardId = '';
$result = $card->code->disable($code, $cardId);
```
## 通用卡券
## 卡券激活
```php
$result = $card->general_card->activate($info);
```
## 撤销激活
```php
$result = $card->general_card->deactivate(string $cardId, string $code);
```
## 更新用户信息
```php
$result = $card->general_card->updateUser(array $info);
```
## 会员卡
### 会员卡激活
```php
$result = $card->member_card->activate($info);
```
> - `info` - 需要激活的会员卡信息
示例:
```php
$info = [
'membership_number' => '357898858', //会员卡编号,由开发者填入,作为序列号显示在用户的卡包里。可与Code码保持等值。
'code' => '916679873278', //创建会员卡时获取的初始code。
'activate_begin_time' => '1397577600', //激活后的有效起始时间。若不填写默认以创建时的 data_info 为准。Unix时间戳格式
'activate_end_time' => '1422724261', //激活后的有效截至时间。若不填写默认以创建时的 data_info 为准。Unix时间戳格式。
'init_bonus' => '持白金会员卡到店消费,可享8折优惠。', //初始积分,不填为0。
'init_balance' => '持白金会员卡到店消费,可享8折优惠。', //初始余额,不填为0。
'init_custom_field_value1' => '白银', //创建时字段custom_field1定义类型的初始值,限制为4个汉字,12字节。
'init_custom_field_value2' => '9折', //创建时字段custom_field2定义类型的初始值,限制为4个汉字,12字节。
'init_custom_field_value3' => '200', //创建时字段custom_field3定义类型的初始值,限制为4个汉字,12字节。
];
$result = $card->member_card->activate($info);
```
### 设置开卡字段
```php
$card->member_card->setActivationForm($cardId, $settings);
```
> - `settings` array - 会员卡激活时的选项
示例:
```php
$cardId = 'pdkJ9uJYAyfLXsUCwI2LdH2Pn1AU';
$settings = [
'required_form' => [
'common_field_id_list' => [
'USER_FORM_INFO_FLAG_MOBILE',
'USER_FORM_INFO_FLAG_LOCATION',
'USER_FORM_INFO_FLAG_BIRTHDAY',
],
'custom_field_list' => [
'喜欢的食物',
],
],
'optional_form' => [
'common_field_id_list' => [
'USER_FORM_INFO_FLAG_EMAIL',
],
'custom_field_list' => [
'喜欢的食物',
],
],
];
$result = $card->member_card->setActivationForm($cardId, $settings);
```
### 拉取会员信息
```php
$card->member_card->getUser($cardId, $code);
```
示例:
```php
$cardId = 'pbLatjtZ7v1BG_ZnTjbW85GYc_E8';
$code = '916679873278';
$result = $card->member_card->getUser($cardId, $code);
```
### 更新会员信息
```php
$card->member_card->updateUser($info);
```
> - `info` array - 可以更新的会员信息
示例:
```php
$info = [
'code' => '916679873278', //卡券Code码。
'card_id' => 'pbLatjtZ7v1BG_ZnTjbW85GYc_E8', //卡券ID。
'record_bonus' => '消费30元,获得3积分', //商家自定义积分消耗记录,不超过14个汉字。
'bonus' => '100', //需要设置的积分全量值,传入的数值会直接显示,如果同时传入add_bonus和bonus,则前者无效。
'balance' => '持白金会员卡到店消费,可享8折优惠。', //需要设置的余额全量值,传入的数值会直接显示,如果同时传入add_balance和balance,则前者无效。
'record_balance' => '持白金会员卡到店消费,可享8折优惠。', //商家自定义金额消耗记录,不超过14个汉字。
'custom_field_value1' => '100', //创建时字段custom_field1定义类型的最新数值,限制为4个汉字,12字节。
'custom_field_value2' => '200', //创建时字段custom_field2定义类型的最新数值,限制为4个汉字,12字节。
'custom_field_value3' => '300', //创建时字段custom_field3定义类型的最新数值,限制为4个汉字,12字节。
];
$result = $card->member_card->updateUser($info);
```
## 子商户
### 添加子商户
```php
$card->sub_merchant->create(array $attributes);
```
示例:
```php
$attributes = [
'brand_name' => 'overtrue',
'logo_url' => 'http://mmbiz.qpic.cn/mmbiz/iaL1LJM1mF9aRKPZJkmG8xXhiaHqkKSVMMWeN3hLut7X7hicFNjakmxibMLGWpXrEXB33367o7zHN0CwngnQY7zb7g/0',
'protocol' => 'qIqwTfzAdJ_1-VJFT0fIV53DSY4sZY2WyhkzZzbV498Qgdp-K5HJtZihbHLS0Ys0',
'end_time' => '1438990559',
'primary_category_id' => 1,
'secondary_category_id' => 101,
'agreement_media_id' => '',
'operator_media_id' => '',
'app_id' => '',
];
$result = $card->sub_merchant->create($attributes);
```
### 更新子商户
```php
$card->sub_merchant->update(int $merchantId, array $info);
```
> - `$merchantId` int - 子商户 ID
> - `$info` array - 参数与创建子商户参数一样
示例:
```php
$info = [
//...
];
$result = $card->sub_merchant->update('12', $info);
```
## 特殊票券
### 机票值机
```php
$card->boarding_pass->checkin(array $params);
```
### 更新会议门票 - 更新用户
```php
$card->meeting_ticket->updateUser(array $params);
```
### 更新电影门票 - 更新用户
```php
$card->movie_ticket->updateUser(array $params);
```
## JSAPI
### 卡券批量下发到用户
```php
$cards = [
['card_id' => 'pdkJ9uLRSbnB3UFEjZAgUxAJrjeY', 'outer_id' => 2],
['card_id' => 'pdkJ9uJ37aU-tyRj4_grs8S45k1c', 'outer_id' => 3],
];
$json = $card->jssdk->assign($cards); // 返回 json 格式
```
返回 json,在模板里的用法:
```html
wx.addCard({ cardList:
= $json ?>, // 需要打开的卡券列表 success: function (res) { var cardList = res.cardList; // 添加的卡券列表信息 } });
```
### 获取 Ticket
```php
$card->jssdk->getTicket();
// 强制刷新
$card->jssdk->getTicket(true);
```
================================================
FILE: docs/src/5.x/official-account/comment.md
================================================
# 评论数据管理
## 打开已群发文章评论
```php
$app->comment->open($msgId, $index = null);
```
## 关闭已群发文章评论
```php
$app->comment->close($msgId, $index = null);
```
## 查看指定文章的评论数据
```php
$app->comment->list(string $msgId, int $index, int $begin, int $count, int $type = 0);
```
## 将评论标记精选
```php
$app->comment->markElect(string $msgId, int $index, int $commentId);
```
## 将评论取消精选
```php
$app->comment->unmarkElect(string $msgId, int $index, int $commentId);
```
## 删除评论
```php
$app->comment->delete(string $msgId, int $index, int $commentId);
```
## 回复评论
```php
$app->comment->reply(string $msgId, int $index, int $commentId, string $content);
```
## 删除回复
```php
$app->comment->deleteReply(string $msgId, int $index, int $commentId);
```
================================================
FILE: docs/src/5.x/official-account/configuration.md
================================================
# 配置
常用的配置参数会比较少,因为除非你有特别的定制,否则基本上默认值就可以了:
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'wx3cf0f39249eb0exx',
'secret' => 'f1c242f4f28f735d4687abb469072axx',
// 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
'response_type' => 'array',
//...
];
$app = Factory::officialAccount($config);
```
下面是一个完整的配置样例:
> 不建议你在配置的时候弄这么多,用到啥就配置啥才是最好的,因为大部分用默认值即可。
```php
'your-app-id', // AppID
'secret' => 'your-app-secret', // AppSecret
'token' => 'your-token', // Token
'aes_key' => '', // EncodingAESKey,兼容与安全模式下请一定要填写!!!
/**
* 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
* 使用自定义类名时,构造函数将会接收一个 `EasyWeChat\Kernel\Http\Response` 实例
*/
'response_type' => 'array',
/**
* 日志配置
*
* level: 日志级别, 可选为:
* debug/info/notice/warning/error/critical/alert/emergency
* path:日志文件位置(绝对路径!!!),要求可写权限
*/
'log' => [
'default' => 'dev', // 默认使用的 channel,生产环境可以改为下面的 prod
'channels' => [
// 测试环境
'dev' => [
'driver' => 'single',
'path' => '/tmp/easywechat.log',
'level' => 'debug',
],
// 生产环境
'prod' => [
'driver' => 'daily',
'path' => '/tmp/easywechat.log',
'level' => 'info',
],
],
],
/**
* 接口请求相关配置,超时时间等,具体可用参数请参考:
* http://docs.guzzlephp.org/en/stable/request-config.html
*
* - retries: 重试次数,默认 1,指定当 http 请求失败时重试的次数。
* - retry_delay: 重试延迟间隔(单位:ms),默认 500
* - log_template: 指定 HTTP 日志模板,请参考:https://github.com/guzzle/guzzle/blob/master/src/MessageFormatter.php
*/
'http' => [
'max_retries' => 1,
'retry_delay' => 500,
'timeout' => 5.0,
// 'base_uri' => 'https://api.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用,根据不同的模块配置不同的 uri
],
/**
* OAuth 配置
*
* scopes:公众平台(snsapi_userinfo / snsapi_base),开放平台:snsapi_login
* callback:OAuth授权完成后的回调页地址
*/
'oauth' => [
'scopes' => ['snsapi_userinfo'],
'callback' => '/examples/oauth_callback.php',
],
];
```
> :heart: 安全模式下请一定要填写 `aes_key`
## 日志配置
你可以配置多个日志的 channel,每个 channel 里的 `driver` 对应不同的日志驱动,内置可用的 `driver` 如下表:
名称 | 描述
------------- | -------------
`stack` | 复合型,可以包含下面多种驱动的混合模式
`single` | 基于 `StreamHandler` 的单一文件日志,参数有 `path`,`level`
`daily` | 基于 `RotatingFileHandler` 按日期生成日志文件,参数有 `path`,`level`,`days`(默认 7 天)
`slack` | 基于 `SlackWebhookHandler` 的 Slack 组件,参数请参考源码:[LogManager.php](https://github.com/overtrue/wechat/blob/master/src/Kernel/Log/LogManager.php#L247)
`syslog` | 基于 `SyslogHandler` Monolog 驱动,参数有 `facility` 默认为 `LOG_USER`,`level`
`errorlog` | 记录日志到系统错误日志,基于 `ErrorLogHandler`,参数有 `type`,默认为 `ErrorLogHandler::OPERATING_SYSTEM`
### 自定义日志驱动
由于日志使用的是 [Monolog](https://github.com/Seldaek/monolog),所以,除了默认的文件式日志外,你可以自定义日志处理器:
```php
use Monolog\Logger;
use Monolog\Handler\RotatingFileHandler;
// 注册自定义日志
$app->logger->extend('mylog', function($app, $config){
return new Logger($this->parseChannel($config), [
$this->prepareHandler(new RotatingFileHandler(
$config['path'], $config['days'], $this->level($config)
)),
]);
});
```
> 在你自定义的闭包函数中,可以使用 `EasyWeChat\Kernel\Log\LogManager` 中的方法,具体请查看 SDK 源代码。
配置文件中在 `driver` 部分即可使用你自定义的驱动了:
```php
'log' => [
'default' => 'dev', // 默认使用的 channel,生产环境可以改为下面的 prod
'channels' => [
// 测试环境
'dev' => [
'driver' => 'mylog',
'path' => '/tmp/easywechat.log',
'level' => 'debug',
'days' => 5,
],
//...
],
],
```
================================================
FILE: docs/src/5.x/official-account/customer_service.md
================================================
# 客服
使用客服系统可以向用户发送消息以及群发消息,客服的管理等功能。
## 客服管理
### 获取所有客服
```php
$app->customer_service->list();
```
### 获取所有在线的客服
```php
$app->customer_service->online();
```
### 添加客服
```php
$app->customer_service->create('foo@test', '客服1');
```
### 修改客服
```php
$app->customer_service->update('foo@test', '客服1');
```
### 删除账号
```php
$app->customer_service->delete('foo@test');
```
### 设置客服头像
```php
$app->customer_service->setAvatar('foo@test', $avatarPath); // $avatarPath 为本地图片路径,非 URL
```
### 获取客服与客户聊天记录
```php
$app->customer_service->messages($startTime, $endTime, $msgId = 1, $number = 10000);
```
示例:
```php
$records = $app->customer_service->messages('2015-06-07', '2015-06-21', 1, 20000);
```
### 主动发送消息给用户
```php
$app->customer_service->message($message)->to($openId)->send();
```
> `$message` 为消息对象或文本,请参考:[消息](messages)
示例:
```php
$app->customer_service->message('hello')
> ->to('oV-gpwdOIwSI958m9osAhGBFxxxx')
> ->send();
```
### 指定客服发送消息
```php
$app->customer_service->message($message)
> ->from('account@test')
> ->to($openId)
> ->send();
```
> `$message` 为消息对象或文本,请参考:[消息](messages.html)
示例:
```php
$app->customer_service->message('hello')
> ->from('kf2001@gh_176331xxxx')
> ->to('oV-gpwdOIwSI958m9osAhGBFxxxx')
> ->send();
```
### 邀请微信用户加入客服
以账号 `foo@test` 邀请 微信号 为 `xxxx` 的微信用户加入客服。
```php
$app->customer_service->invite('foo@test', 'xxxx');
```
## 客服会话控制
## 创建会话
```php
$app->customer_service_session->create('test1@test', 'OPENID');
```
### 关闭会话
```php
$app->customer_service_session->close('test1@test', 'OPENID');
```
### 获取客户会话状态
```php
$app->customer_service_session->get('OPENID');
```
### 获取客服会话列表
```php
$app->customer_service_session->list('test1@test');
```
### 获取未接入会话列表
```php
$app->customer_service_session->waiting();
```
================================================
FILE: docs/src/5.x/official-account/data_cube.md
================================================
# 数据统计与分析
通过数据接口,开发者可以获取与公众平台官网统计模块类似但更灵活的数据,还可根据需要进行高级处理。
>
> 1. 接口侧的公众号数据的数据库中仅存储了 **2014年12月1日之后**的数据,将查询不到在此之前的日期,即使有查到,也是不可信的脏数据;
> 2. 请开发者在调用接口获取数据后,将数据保存在自身数据库中,即加快下次用户的访问速度,也降低了微信侧接口调用的不必要损耗。
> 3. 额外注意,获取图文群发每日数据接口的结果中,只有**中间页阅读人数+原文页阅读人数+分享转发人数+分享转发次数+收藏次数 >=3** 的结果才会得到统计,过小的阅读量的图文消息无法统计。
## 示例
```php
$userSummary = $app->data_cube->userSummary('2014-12-07', '2014-12-08');
var_dump($userSummary);
//
//[
// {
// "ref_date": "2014-12-07",
// "user_source": 0,
// "new_user": 0,
// "cancel_user": 0
// }
// //后续还有ref_date在begin_date和end_date之间的数据
// ]
```
## API
$from 示例: `2014-02-13` 获取数据的起始日期
$to 示例: `2014-02-18` 获取数据的结束日期,`$to`允许设置的最大值为昨日
`$from` 和 `$to` 的差值需小于 “最大时间跨度”(比如最大时间跨度为 1 时,`$from` 和 `$to` 的差值只能为 0,才能小于 1 ),否则会报错
+ `array userSummary(string $from, string $to)` 获取用户增减数据, 最大时间跨度:**7**;
+ `array userCumulate(string $from, string $to)` 获取累计用户数据, 最大时间跨度:**7**;
+ `array articleSummary(string $from, string $to)` 获取图文群发每日数据, 最大时间跨度:**1**;
+ `array articleTotal(string $from, string $to)` 获取图文群发总数据, 最大时间跨度:**1**;
+ `array userReadSummary(string $from, string $to)` 获取图文统计数据, 最大时间跨度:**3**;
+ `array userReadHourly(string $from, string $to)` 获取图文统计分时数据, 最大时间跨度:**1**;
+ `array userShareSummary(string $from, string $to)` 获取图文分享转发数据, 最大时间跨度:**7**;
+ `array userShareHourly(string $from, string $to)` 获取图文分享转发分时数据, 最大时间跨度:**1**;
+ `array upstreamMessageSummary(string $from, string $to)` 获取消息发送概况数据, 最大时间跨度:**7**;
+ `array upstreamMessageHourly(string $from, string $to)` 获取消息发送分时数据, 最大时间跨度:**1**;
+ `array upstreamMessageWeekly(string $from, string $to)` 获取消息发送周数据, 最大时间跨度:**30**;
+ `array upstreamMessageMonthly(string $from, string $to)` 获取消息发送月数据, 最大时间跨度:**30**;
+ `array upstreamMessageDistSummary(string $from, string $to)` 获取消息发送分布数据, 最大时间跨度:**15**;
+ `array upstreamMessageDistWeekly(string $from, string $to)` 获取消息发送分布周数据, 最大时间跨度:**30**;
+ `array upstreamMessageDistMonthly(string $from, string $to)` 获取消息发送分布月数据, 最大时间跨度:**30**;
+ `array interfaceSummary(string $from, string $to)` 获取接口分析数据, 最大时间跨度:**30**;
+ `array interfaceSummaryHourly(string $from, string $to)` 获取接口分析分时数据, 最大时间跨度:**1**;
+ `array cardSummary(string $from, string $to, int $condSource = 0)` 获取普通卡券分析分时数据, 最大时间跨度:**1**;
+ `array freeCardSummary(string $from, string $to, int $condSource = 0, string $cardId = '')` 获取免费券分析分时数据, 最大时间跨度:**1**;
+ `array memberCardSummary(string $from, string $to, int $condSource = 0)` 获取会员卡分析分时数据, 最大时间跨度:**1**;
================================================
FILE: docs/src/5.x/official-account/draft.md
================================================
# 草稿箱
草稿箱提供了公众号文章的草稿管理功能,你可以通过草稿箱 API 添加、获取或删除草稿。
### 添加草稿
```php
use EasyWeChat\Kernel\Messages\Article;
// 添加单篇图文草稿
$article = new Article([
'title' => 'xxx',
'thumb_media_id' => $mediaId,
'author' => 'overtrue',
'show_cover' => 1,
'digest' => '文章摘要',
'content' => '文章内容',
'source_url' => 'https://www.easywechat.com',
//...
]);
$app->draft->add($article);
// 添加多篇图文草稿
$app->draft->add([$article, $article2, ...]);
```
### 获取草稿
```php
$app->draft->get($mediaId);
```
### 删除草稿
```php
$app->draft->delete($mediaId);
```
### 更新草稿
有三个参数:
> - `$mediaId` 要更新的草稿的 `mediaId`
> - `$article` 文章内容,`Article` 实例或者全字段数组
> - `$index` 要更新的文章在图文消息中的位置(多图文消息时,此字段才有意义,单图片忽略此参数),第一篇为 0
```php
$result = $app->draft->update($mediaId, new Article([
'title' => 'EasyWeChat 5.x 发布了!',
'thumb_media_id' => 'qQFxUQGO21Li4YrSn3MhnrqtRp9Zi3cbM9uBsepvDmE', // 封面图片 mediaId
'author' => 'overtrue', // 作者
'show_cover' => 1, // 是否在文章内容显示封面图片
'digest' => '这里是文章摘要',
'content' => '这里是文章内容,你可以放很长的内容',
'source_url' => 'https://easywechat.com',
]));
// 指定更新多图文中的第 2 篇
$result = $app->draft->update($mediaId, new Article([...]), 1); // 第 2 篇
```
### 获取草稿总数
```php
$app->draft->count();
```
### 获取草稿列表
```php
$app->draft->batchGet($offset, $count, $noContent = 0);
```
> - `$offset` - 从全部素材的该偏移位置开始返回,可选,默认 `0`,0 表示从第一个素材返回
> - `$count` - 返回素材的数量,可选,默认 `20`,取值在 1 到 20 之间
> - `$noContent` - 1 表示不返回 content 字段,0 表示正常返回,默认为 0
================================================
FILE: docs/src/5.x/official-account/events.md
================================================
# 事件
更多请参考:[服务端](server.html)
关于事件类型请参考微信官方文档:http://mp.weixin.qq.com/wiki/
================================================
FILE: docs/src/5.x/official-account/goods.md
================================================
# 返佣商品
> 微信文档:https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&key=11533749572M9ODP&version=1&lang=zh_CN&platform=2
## 导入商品
每次调用支持批量导入不超过1000条的商品信息。每分钟单个商户全局调用次数不得超过200次。每天调用次数不得超过100万次。每次请求包大小不超过2M。
```php
$data = [
[
'pid' => 'pid001',
'image_info' => [
'main_image_list' => [
[
'url' => 'http://www.google.com/a.jpg',
],
[
'url' => 'http://www.google.com/b.jpg',
],
],
],
//...
],
//...
];
$result = $app->goods->add($data);
// $result:
//{
// "errcode": 0,
// "errmsg": "ok",
// "status_ticket": "115141102647330200"
//}
```
`status_ticket` 用于获取此次导入的详细结果。
## 更新商品
更新时,字段不填代表不更新该字段(此处的字段不填,代表无此字段,而不是把字段的值设为空,设为空即代表更新该字段为空)。
对于字符串类型的选填字段,如副标题,若清空不展示,则可设置为空;对于数字类型的选填字段,如原价,若清空不展示,则需设置为0。
> 基本字段更新中 `pid` 为必填字段,且无法修改
```php
$data = [
[
'pid' => 'pid001',
'image_info' => [
'main_image_list' => [
[
'url' => 'http://www.baidu.com/c.jpg',
],
[
'url' => 'http://www.baidu.com/d.jpg',
],
],
],
//...
],
//...
];
$result = $app->goods->update($data);
// $result:
//{
// "errcode": 0,
// "errmsg": "ok",
// "status_ticket": "115141102647330200"
//}
```
> 说明:导入商品和更新商品使用的是同一个接口。
## 查询导入/更新商品状态
用于查询导入或更新商品的结果,当导入或更新商品失败时,若为系统错误可进行重试;若为其他错误,请排查解决后进行重试。
```php
$status_ticket = '115141102647330200';
$result = $app->goods->status($status_ticket);
// $result:
//{
// "errcode": 0,
// "errmsg": "ok",
// "result": {
// "succ_cnt": 2,
// "fail_cnt": 0,
// "total_cnt": 2,
// "progress": "100.00%",
// "statuses": [
// {
// "pid": "pid001",
// "ret": 0,
// "err_msg": "success",
// "err_msg_zh_cn": "成功"
// },
// {
// "pid": "pid002",
// "ret": 0,
// "err_msg": "success",
// "err_msg_zh_cn": "成功"
// }
// ]
// }
//}
```
## 获取单个商品信息
使用该接口获取已导入的商品信息,供验证信息及抽查导入情况使用。
```php
$pid = 'pid001';
$app->goods->get($pid);
```
> 返回结果中的 `product` 字段内容与 `导入商品接口` 字段一致,导入时未设置的值有可能获取时仍会返回,但显示为空
## 分页获取商品信息
使用该接口可获取已导入的全量商品信息,供全量验证信息使用。
```php
$context = ''; // page 为 1 时传空即可。当 page 大于 1 时必填,填入上一次访问本接口返回的 page_context。
$page = 1; // 页码
$size = 10; // 每页数据大小,目前限制为100以内,注意一次全量验证过程中该参数的值需保持不变
$app->goods->list($context, $page, $size);
```
> 返回结果中的 `product` 字段内容与 `导入商品接口` 字段一致,导入时未设置的值有可能获取时仍会返回,但显示为空。
> `page_context` 字段用于获取下一页数据时使用。
================================================
FILE: docs/src/5.x/official-account/index.md
================================================
## 公众号
公众号的各模块相对比较统一,用法如下:
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'wx3cf0f39249eb0exx',
'secret' => 'f1c242f4f28f735d4687abb469072axx',
// 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
'response_type' => 'array',
//...
];
$app = Factory::officialAccount($config);
```
`$app` 在所有相关公众号的文档都是指 `Factory::officialAccount` 得到的实例,就不在每个页面单独写了。
================================================
FILE: docs/src/5.x/official-account/material.md
================================================
# 素材管理
在微信里的图片,音乐,视频等等都需要先上传到微信服务器作为素材才可以在消息中使用。
### 上传图片
> 注意:微信图片上传服务有敏感检测系统,图片内容如果含有敏感内容,如色情,商品推广,虚假信息等,上传可能失败。
```php
$result = $app->material->uploadImage("/path/to/your/image.jpg");
// {
// "media_id":MEDIA_ID,
// "url":URL
// }
```
> `url` 只有上传图片素材有返回值。
### 上传语音
语音 **大小不超过 5M**,**长度不超过 60 秒**,支持 `mp3/wma/wav/amr` 格式。
```php
$result = $app->material->uploadVoice("/path/to/your/voice.mp3");
// {
// "media_id":MEDIA_ID,
// }
```
### 上传视频
```php
$result = $app->material->uploadVideo("/path/to/your/video.mp4", "视频标题", "视频描述");
// {
// "media_id":MEDIA_ID,
// }
```
### 上传缩略图
用于视频封面或者音乐封面。
```php
$result = $app->material->uploadThumb("/path/to/your/thumb.jpg");
// {
// "media_id":MEDIA_ID,
// }
```
### 上传图文消息
```php
use EasyWeChat\Kernel\Messages\Article;
// 上传单篇图文
$article = new Article([
'title' => 'xxx',
'thumb_media_id' => $mediaId,
//...
]);
$app->material->uploadArticle($article);
// 或者多篇图文
$app->material->uploadArticle([$article, $article2, ...]);
```
### 修改图文消息
有三个参数:
> - `$mediaId` 要更新的文章的 `mediaId`
> - `$article` 文章内容,`Article` 实例或者 全字段数组
> - `$index` 要更新的文章在图文消息中的位置(多图文消息时,此字段才有意义,单图片忽略此参数),第一篇为 0;
```php
$result = $app->material->updateArticle($mediaId, new Article(...));
// or
$result = $app->material->updateArticle($mediaId, [
'title' => 'EasyWeChat 4.0 发布了!',
'thumb_media_id' => 'qQFxUQGO21Li4YrSn3MhnrqtRp9Zi3cbM9uBsepvDmE', // 封面图片 mediaId
'author' => 'overtrue', // 作者
'show_cover' => 1, // 是否在文章内容显示封面图片
'digest' => '这里是文章摘要',
'content' => '这里是文章内容,你可以放很长的内容',
'source_url' => 'https://easywechat.com',
]);
// 指定更新多图文中的第 2 篇
$result = $app->material->updateArticle($mediaId, new Article(...), 1); // 第 2 篇
```
### 上传图文消息图片
返回值中 url 就是上传图片的 URL,可用于后续群发中,放置到图文消息中。
```php
$result = $app->material->uploadArticleImage($path);
//{
// "url": "http://mmbiz.qpic.cn/mmbiz/gLO17UPS6FS2xsypf378iaNhWacZ1G1UplZYWEYfwvuU6Ont96b1roYsCNFwaRrSaKTPCUdBK9DgEHicsKwWCBRQ/0"
//}
```
### 获取永久素材
```php
$resource = $app->material->get($mediaId);
```
如果请求的素材为图文消息,则响应如下:
```json
{
"news_item": [
{
"title":TITLE,
"thumb_media_id"::THUMB_MEDIA_ID,
"show_cover_pic":SHOW_COVER_PIC(0/1),
"author":AUTHOR,
"digest":DIGEST,
"content":CONTENT,
"url":URL,
"content_source_url":CONTENT_SOURCE_URL
},
//多图文消息有多篇文章
]
}
```
如果返回的是视频消息素材,则内容如下:
```json
{
"title": TITLE,
"description": DESCRIPTION,
"down_url": DOWN_URL
}
```
其他类型的素材消息,则响应为 `EasyWeChat\Kernel\Http\StreamResponse` 实例,开发者可以自行保存为文件。例如
```php
$stream = $app->material->get($mediaId);
if ($stream instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
// 以内容 md5 为文件名
$stream->save('保存目录');
// 自定义文件名,不需要带后缀
$stream->saveAs('保存目录', '文件名');
}
```
### 获取永久素材列表
> - `$type` 素材的类型,图片(`image`)、视频(`video`)、语音 (`voice`)、图文(`news`)
> - `$offset` 从全部素材的该偏移位置开始返回,可选,默认 `0`,0 表示从第一个素材 返回
> - `$count` 返回素材的数量,可选,默认 `20`, 取值在 1 到 20 之间
```php
$app->material->list($type, $offset, $count);
```
示例:
```php
$list = $app->material->list('image', 0, 10);
```
图片、语音、视频 等类型的返回如下
```json
{
"total_count": TOTAL_COUNT,
"item_count": ITEM_COUNT,
"item": [
{
"media_id": MEDIA_ID,
"name": NAME,
"update_time": UPDATE_TIME,
"url": URL
}
//可能会有多个素材
]
}
```
永久图文消息素材列表的响应如下:
```json
{
"total_count": TOTAL_COUNT,
"item_count": ITEM_COUNT,
"item": [
{
"media_id": MEDIA_ID,
"content": {
"news_item": [
{
"title": TITLE,
"thumb_media_id": THUMB_MEDIA_ID,
"show_cover_pic": SHOW_COVER_PIC(0 / 1),
"author": AUTHOR,
"digest": DIGEST,
"content": CONTENT,
"url": URL,
"content_source_url": CONTETN_SOURCE_URL
}
//多图文消息会在此处有多篇文章
]
},
"update_time": UPDATE_TIME
}
//可能有多个图文消息item结构
]
}
```
### 获取素材计数
```php
$stats = $app->material->stats();
// {
// "voice_count":COUNT,
// "video_count":COUNT,
// "image_count":COUNT,
// "news_count":COUNT
// }
```
### 删除永久素材
```php
$app->material->delete($mediaId);
```
### 文章预览
文章预览请参阅 “消息群发” 章节。
================================================
FILE: docs/src/5.x/official-account/menu.md
================================================
# 自定义菜单
## 读取(查询)已设置菜单
```php
$list = $app->menu->list();
```
## 获取当前菜单
```php
$current = $app->menu->current();
```
## 添加菜单
### 添加普通菜单
```php
$buttons = [
[
"type" => "click",
"name" => "今日歌曲",
"key" => "V1001_TODAY_MUSIC"
],
[
"name" => "菜单",
"sub_button" => [
[
"type" => "view",
"name" => "搜索",
"url" => "http://www.soso.com/"
],
[
"type" => "view",
"name" => "视频",
"url" => "http://v.qq.com/"
],
[
"type" => "click",
"name" => "赞一下我们",
"key" => "V1001_GOOD"
],
],
],
];
$app->menu->create($buttons);
```
以上将会创建一个普通菜单。
### 添加个性化菜单
与创建普通菜单不同的是,需要在 `create()` 方法中将个性化匹配规则作为第二个参数传进去:
```php
$buttons = [
// ...
];
$matchRule = [
"tag_id" => "2",
"sex" => "1",
"country" => "中国",
"province" => "广东",
"city" => "广州",
"client_platform_type" => "2",
"language" => "zh_CN"
];
$app->menu->create($buttons, $matchRule);
```
## 删除菜单
有两种删除方式,一种是**全部删除**,另外一种是**根据菜单 ID 来删除**(删除个性化菜单时用,ID 从查询接口获取):
```php
$app->menu->delete(); // 全部
$app->menu->delete($menuId);
```
## 测试个性化菜单
```php
$app->menu->match($userId);
```
> `$userId` 可以是粉丝的 OpenID,也可以是粉丝的微信号。
返回 `$menu` 与指定的 `$userId` 匹配的菜单项。
================================================
FILE: docs/src/5.x/official-account/message-transfer.md
================================================
# 多客服消息转发
多客服的消息转发绝对是超级的简单,转发的消息类型为 `transfer`:
```php
use EasyWeChat\Kernel\Messages\Transfer;
// 转发收到的消息给客服
$app->server->push(function($message) {
return new Transfer();
});
$response = $app->server->serve();
```
当然,你也可以指定转发给某一个客服:
```php
use EasyWeChat\Kernel\Messages\Transfer;
$app->server->push(function($message) {
return new Transfer($account);
});
```
================================================
FILE: docs/src/5.x/official-account/messages.md
================================================
# 消息
我把微信的 API 里的所有“消息”都按类型抽象出来了,也就是说,你不用区分它是回复消息还是主动推送消息,免去了你去手动拼装微信的 XML 以及乱七八糟命名不统一的 JSON 了。
在阅读以下内容时请忽略是 **接收消息** 还是 **回复消息**,后面我会给你讲它们的区别。
## 消息类型
消息分为以下几种:`文本`、`图片`、`视频`、`声音`、`链接`、`坐标`、`图文`、`文章` 和一种特殊的 `原始消息`。
另外还有一种特殊的消息类型:**素材消息**,用于群发或者客服时发送已有素材用。
> 注意:回复消息与客服消息里的图文类型为:**图文**,群发与素材中的图文为**文章**
所有的消息类都在 `EasyWeChat\Kernel\Messages` 这个命名空间下, 下面我们来分开讲解:
### 文本消息
属性列表:
> - `content` 文本内容
```php
use EasyWeChat\Kernel\Messages\Text;
$text = new Text('您好!overtrue。');
// or
$text = new Text();
$text->content = '您好!overtrue。';
// or
$text = new Text();
$text->setAttribute('content', '您好!overtrue。');
```
### 图片消息
属性列表:
```
- media_id 媒体资源 ID
```
```php
use EasyWeChat\Kernel\Messages\Image;
$image = new Image($mediaId);
```
### 视频消息
属性列表:
> - `title` 标题
> - `description` 描述
> - `media_id` 媒体资源 ID
> - `thumb_media_id` 封面资源 ID
```php
use EasyWeChat\Kernel\Messages\Video;
$video = new Video($mediaId, [
'title' => $title,
'description' => '...',
]);
```
### 声音消息
属性列表:
> - `media_id` 媒体资源 ID
```php
use EasyWeChat\Kernel\Messages\Voice;
$voice = new Voice($mediaId);
```
### 链接消息
> 复链接消息
### 坐标消息
> 复坐标消息
### 图文消息
图文消息分为 `NewsItem` 与 `News`,`NewsItem` 为图文内容条目。
> ,被动回复消息与客服消息接口的图文消息类型中图文数目只能为一条](https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&announce_id=115383153198yAvN&version=&lang=zh_CN&token=)
`NewsItem` 属性:
> - `title` 标题
> - `description` 描述
> - `image` 图片链接
> - `url` 链接 URL
```php
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
$items = [
new NewsItem([
'title' => $title,
'description' => '...',
'url' => $url,
'image' => $image,
// ...
]),
];
$news = new News($items);
```
### 文章
属性列表:
> - `title` 标题
> - `author` 作者
> - `content` 具体内容
> - `thumb_media_id` 图文消息的封面图片素材 id(必须是永久 mediaID)
> - `digest` 图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空
> - `source_url` 来源 URL
> - `show_cover` 是否显示封面,0 为 false,即不显示,1 为 true,即显示
```php
use EasyWeChat\Kernel\Messages\Article;
$article = new Article([
'title' => 'EasyWeChat',
'author' => 'overtrue',
'content' => 'EasyWeChat 是一个开源的微信 SDK,它... ...',
// ...
]);
// or
$article = new Article();
$article->title = 'EasyWeChat';
$article->author = 'overtrue';
$article->content = '微信 SDK ...';
// ...
```
### 素材消息
素材消息用于群发与客服消息时使用。
> 素材消息不支持被动回复,如需被动回复素材消息,首先组装后,再 News 方法返回。
属性就一个:`media_id`。
在构造时有两个参数:
> - `$type` 素材类型,目前只支持:`mpnews`、 `mpvideo`、`voice`、`image` 等。
> - `$mediaId` 素材 ID,从接口查询或者上传后得到。
```php
use EasyWeChat\Kernel\Messages\Media;
$media = new Media($mediaId, 'mpnews');
```
以上呢,是所有微信支持的基本消息类型。
> 需要注意的是,你不需要关心微信的消息字段叫啥,因为这里我们使用了更标准的命名,然后最终在中间做了转换,所以你不需要关注。
### 原始消息
原始消息是一种特殊的消息,它的场景是:**你不想使用其它消息类型,你想自己手动拼消息**。比如,回复消息时,你想自己拼 XML,那么你就直接用它就可以了:
```php
use EasyWeChat\Kernel\Messages\Raw;
$message = new Raw('
12345678
');
```
比如,你要用于客服消息(客服消息是 JSON 结构):
```php
use EasyWeChat\Kernel\Messages\Raw;
$message = new Raw('{
"touser":"OPENID",
"msgtype":"text",
"text":
{
"content":"Hello World"
}
}');
```
总之,就是直接写微信接口要求的格式内容就好,此类型消息在 SDK 中不存在转换行为,所以请注意不要写错格式。
## 在 SDK 中使用消息
### 在服务端回复消息
在 [服务端](server) 一节中,我们讲了回复消息的写法:
```php
// ... 前面部分省略
$app->server->push(function ($message) {
return "您好!欢迎关注我!";
});
$response = $server->serve();
```
上面 `return` 了一句普通的文本内容,这里只是为了方便大家,实际上最后会有一个隐式转换为 `Text` 类型的动作。
如果你要回复其它类型的消息,就需要返回一个具体的实例了,比如回复一个图片类型的消息:
```php
use EasyWeChat\Kernel\Messages\Image;
// ...
$app->server->push(function ($message) {
return new Image('media-id');
});
// ...
```
#### 回复多图文消息
> ,被动回复消息与客服消息接口的图文消息类型中图文数目只能为一条](https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&announce_id=115383153198yAvN&version=&lang=zh_CN&token=)
多图文消息其实就是单图文消息的一个数组而已了:
```php
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
// ...
$app->server->push(function ($message) {
$news = new NewsItem(...);
return new News([$news]);
});
// ...
```
### 作为客服消息发送
在客服消息里的使用也一样,都是直接传入消息实例即可:
```php
use EasyWeChat\Kernel\Messages\Text;
$message = new Text('Hello world!');
$result = $app->customer_service->message($message)->to($openId)->send();
//...
```
#### 发送多图文消息
> ,被动回复消息与客服消息接口的图文消息类型中图文数目只能为一条](https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&announce_id=115383153198yAvN&version=&lang=zh_CN&token=)
多图文消息其实就是单图文消息组成的一个 News 对象而已:
```php
$news1 = new NewsItem(...);
$news = new News([$news1]);
$app->customer_service->message($news)->to($openId)->send();
```
### 群发消息
请参考:[群发消息](broadcasting)
## 消息转发给客服系统
参见:[多客服消息转发](message-transfer)
================================================
FILE: docs/src/5.x/official-account/oauth.md
================================================
# 网页授权
## 关于 OAuth2.0
OAuth 是一个关于授权(authorization)的开放网络标准,在全世界得到广泛应用,目前的版本是 2.0 版。
> 摘自:[RFC 6749](https://datatracker.ietf.org/doc/rfc6749/?include_text=1)
步骤解释:
(A)用户打开客户端以后,客户端要求用户给予授权。
(B)用户同意给予客户端授权。
(C)客户端使用上一步获得的授权,向认证服务器申请令牌。
(D)认证服务器对客户端进行认证以后,确认无误,同意发放令牌。
(E)客户端使用令牌,向资源服务器申请获取资源。
(F)资源服务器确认令牌无误,同意向客户端开放资源。
关于 OAuth 协议我们就简单了解到这里,如果还有不熟悉的同学,请 [Google 相关资料](https://www.google.com.hk/?gws_rd=ssl#safe=strict&q=OAuth2)
## 微信 OAuth
在微信里的 OAuth 其实有两种:[公众平台网页授权获取用户信息](http://mp.weixin.qq.com/wiki/9/01f711493b5a02f24b04365ac5d8fd95.html)、[开放平台网页登录](https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN)。
它们的区别有两处,授权地址不同,`scope` 不同。
> - **公众平台网页授权获取用户信息**
**授权 URL**: `https://open.weixin.qq.com/connect/oauth2/authorize`
**Scopes**: `snsapi_base` 与 `snsapi_userinfo`
> - **开放平台网页登录**
**授权 URL**: `https://open.weixin.qq.com/connect/qrconnect`
**Scopes**: `snsapi_login`
他们的逻辑都一样:
1. 用户尝试访问一个我们的业务页面,例如: `/user/profile`
2. 如果用户已经登录,则正常显示该页面
3. 系统检查当前访问的用户并未登录(从 session 或者其它方式检查),则跳转到**跳转到微信授权服务器**(上面的两种中一种**授权 URL** ),并告知微信授权服务器我的**回调 URL(redirect_uri=callback.php)**,此时用户看到蓝色的授权确认页面(`scope` 为 `snsapi_base` 时不显示)
4. 用户点击确定完成授权,浏览器跳转到**回调 URL**: `callback.php` 并带上 `code`: `?code=CODE&state=STATE`。
5. 在 `callback.php` 中得到 `code` 后,通过 `code` 再次向微信服务器请求得到 **网页授权 access_token** 与 `openid`
6. 你可以选择拿 `openid` 去请求 API 得到用户信息(可选)
7. 将用户信息写入 SESSION。
8. 跳转到第 3 步写入的 `target_url` 页面(`/user/profile`)。
> 看懵了?没事,使用 SDK,你不用管这么多。:smile:
>
> 注意,上面的第 3 步:redirect_uri=callback.php 实际上我们会在 `callback.php` 后面还会带上授权目标页面 `user/profile`,所以完整的 `redirect_uri` 应该是下面的这样的 PHP 去拼出来:`'redirect_uri='.urlencode('callback.php?target=user/profile')`
> 结果:redirect_uri=callback.php%3Ftarget%3Duser%2Fprofile
## 逻辑组成
从上面我们所描述的授权流程来看,我们至少有 3 个页面:
1. **业务页面**,也就是需要授权才能访问的页面。
2. **发起授权页**,此页面其实可以省略,可以做成一个中间件,全局检查未登录就发起授权。
3. **授权回调页**,接收用户授权后的状态,并获取用户信息,写入用户会话状态(SESSION)。
## 开始之前
在开始之前请一定要记住,先登录公众号后台,找到**边栏 “开发”** 模块下的 **“接口权限”**,点击 **“网页授权获取用户基本信息”** 后面的修改,添加你的网页授权域名。
> 如果你的授权地址为:`http://www.abc.com/xxxxx`,那么请填写 `www.abc.com`,也就是说请填写与网址匹配的域名,前者如果填写 `abc.com` 是通过不了的。
## SDK 中 OAuth 模块的 API
在 SDK 中,我们使用名称为 `oauth` 的模块来完成授权服务,我们主要用到以下两个 API:
### 发起授权
```php
// $redirectUrl 为跳转目标,请自行 302 跳转到目标地址
$redirectUrl = $app->oauth->scopes(['snsapi_userinfo'])
->redirect();
```
当然你也可以在发起授权的时候指定回调 URL,比如设置回调 URL 为当前页面:
```php
$redirectUrl = $app->oauth->scopes(['snsapi_userinfo'])
->redirect($request->fullUrl());
```
它的返回值 `$redirectUrl` 是一个字符串跳转地址,请自行使用框架的跳转方法实现跳转,PHP 原生写法:
```php
header("Location: {$redirectUrl}");
```
在 [Laravel](http://laravel.com) 框架中控制器方法是要求返回响应值的,那么你就直接:
```php
return \redirect($redirectUrl);
```
### 获取已授权用户
```php
$code = "微信回调URL携带的 code";
$user = $app->oauth->userFromCode($code);
```
返回的 `$user` 是 [Overtrue\Socialite\User](https://github.com/overtrue/socialite/blob/master/src/User.php) 对象,你可以从该对象拿到[更多的信息](https://github.com/overtrue/socialite#user-interface)。
#### $user 可以用的方法:
- `$user->getId(); ` 对应微信的 `openid`
- `$user->getNickname(); ` 对应微信的 `nickname`
- `$user->getName(); ` 对应微信的 `nickname`
- `$user->getAvatar(); ` 头像地址
- `$user->getRaw(); ` 原始 API 返回的结果
- `$user->getAccessToken(); ` `access_token`
- `$user->getRefreshToken(); ` `refresh_token`
- `$user->getExpiresIn(); ` `expires_in`,Access Token 过期时间
- `$user->getTokenResponse(); ` 返回 `access_token` 时的响应值
> r`里没有`openid`, `$user->id` 便是 `openid`.
> 如果你想拿微信返回给你的原样的全部信息,请使用:$user->getRaw();
当 `scope` 为 `snsapi_base` 时 `$oauth->userFromCode($code);` 对象里只有 `id`,没有其它信息。
## 网页授权实例
我们这里来用原生 PHP 写法举个例子,`oauth_callback` 是我们的授权回调 URL (未 urlencode 编码的 URL), `user/profile` 是我们需要授权才能访问的页面,它的 PHP 代码如下:
```php
// http://easywechat.com/user/profile
[
'scopes' => ['snsapi_userinfo'],
'callback' => '/oauth_callback',
],
// ..
];
$app = Factory::officialAccount($config);
$oauth = $app->oauth;
// 未登录
if (empty($_SESSION['wechat_user'])) {
$_SESSION['target_url'] = 'user/profile';
$redirectUrl = $oauth->redirect();
header("Location: {$redirectUrl}");
exit;
}
// 已经登录过
$user = $_SESSION['wechat_user'];
// ...
```
授权回调页:
```php
// http://easywechat.com/oauth_callback
oauth;
// 获取 OAuth 授权结果用户信息
$code = "微信回调URL携带的 code";
// 不少用户这里的 code 是来源于静默授权 如果这里你的 $oauth 没有配置 scopes 为 snsapi_base 调用 $oauth->userFromCode($code); 默认会走 snsapi_userinfo;
$oauth = $app->oauth->scopes(['snsapi_base'])
$user = $oauth->userFromCode($code);
$_SESSION['wechat_user'] = $user->toArray();
$targetUrl = empty($_SESSION['target_url']) ? '/' : $_SESSION['target_url'];
header('Location:'. $targetUrl); // 跳转到 user/profile
```
上面的例子呢都是基于 `$_SESSION` 来保持会话的,在微信客户端中,你可以结合 Cookies 来存储,但是有效期平台不一样时间也不一样,好像 Android 的失效会快一些,不过基本也够用了。
## 参考阅读
- 本模块基于 [overtrue/socialite](https://github.com/overtrue/socialite/) 实现,更多的使用请阅读该扩展包文档。
- state 参数的使用: [overtrue/socialite/#state](https://github.com/overtrue/socialite/#state)
================================================
FILE: docs/src/5.x/official-account/poi.md
================================================
# 门店
## 创建门店
用 POI 接口新建门店时所使用的图片 url 必须为微信自己域名的 url,因此需要先用上传图片接 口上传图片并获取 url,再创建门店。上传的图片限制文件大小限制 1MB,支持 JPG 格式,图片接口请参考:[临时素材](../basic-services/media.md)
```php
$app->poi->create($baseInfo);
```
> - `$baseInfo` 为门店的基本信息数组
示例:
```php
"33788392",
"business_name" => "麦当劳",
"branch_name" => "艺苑路店",
"province" => "广东省",
"city" => "广州市",
"district" => "海珠区",
"address" => "艺苑路 11 号",
"telephone" => "020-12345678",
"categories" => array("美食,快餐小吃"),
"offset_type" => 1,
"longitude" => 115.32375,
"latitude" => 25.097486,
"photo_list" => array(
array("photo_url" => "https://easywechat.com"),
array("photo_url" => "https://easywechat.com"),
),
"recommend" => "麦辣鸡腿堡套餐,麦乐鸡,全家桶",
"special" => "免费 wifi,外卖服务",
"introduction" => "麦当劳是全球大型跨国连锁餐厅,1940 年创立于美国,在世界上大约拥有 3 万间分店。主要售卖汉堡包,以及薯条、炸鸡、汽水、冰品、沙拉、水果等 快餐食品",
"open_time" => "8:00-20:00",
"avg_price" => 35,
);
$result = $app->poi->create($info); // true or exception
```
> 注意:新创建的门店在审核通过后,会以事件形式推送给商户填写的回调 URL
## 获取指定门店信息
```php
$app->poi->get($poiId);
```
> - `$poiId` 为门店 ID
示例:
```php
$info = $app->poi->get(271262077);
```
## 获取门店列表
```php
$app->poi->list($begin, $limit);// begin:0, limit:10
```
> - `$begin` 就是查询起点,`MySQL` 里的 `offset`;
> - `$limit` 查询条数,同 `MySQL` 里的 `limit`;
> 两参数均可选
示例:
```php
$pois = $app->poi->list(0, 2);// 取2条记录
//
//[
// {
// "sid": "100",
// "poi_id": "271864249",
// "business_name": "麦当劳",
// "branch_name": "艺苑路店",
// "address": "艺苑路 11 号",
// "available_state": 3
// },
// {
// "sid": "101",
// "business_name": "麦当劳",
// "branch_name": "赤岗路店",
// "address": "赤岗路 102 号",
// "available_state": 4
// }
//]
```
## 修改门店信息
商户可以通过该接口,修改门店的服务信息,包括:图片列表、营业时间、推荐、特色服务、简 介、人均价格、电话 7 个字段。目前基础字段包括(名称、坐标、地址等不可修改)。
```php
$app->poi->update($poiId, $data);
```
> - `$poiId` 为门店 ID
> - `$data` 需要更新的部分数据,**若有填写内容则为覆盖更新,若无内容则视为不 修改,维持原有内容。photo_list 字段为全列表覆盖,若需要增加图片,需将之前图片同样放入 list 中,在其后增加新增图片。如:已有 A、B、C 三张图片,又要增加 D、E 两张图,则需要调 用该接口,photo_list 传入 A、B、C、D、E 五张图片的链接。**
示例:
```php
$data = array(
"telephone" => "020-12345678",
"recommend" => "麦辣鸡腿堡套餐,麦乐鸡,全家桶",
//...
);
$res = $app->poi->update(271262077, $data); //true or exception
```
## 删除门店
```php
$app->poi->delete($poiId);
```
示例:
```php
$app->poi->delete(271262077);// true or exception
```
================================================
FILE: docs/src/5.x/official-account/reply.md
================================================
# 自动回复
## 获取当前设置的回复规则
```php
$app->auto_reply->current();
```
================================================
FILE: docs/src/5.x/official-account/semantic.md
================================================
# 语义理解
> 貌似此接口已经下线,调用无正确返回值
+ `query($keyword, $categories, $optional = [])` 语义理解:
+ `$keyword` 为关键字
+ `$categories` 需要使用的服务类型,多个用 “,” 隔开字符串,不能为空;
+ `$optional` 为其它属性:
+ `latitude` `float` 纬度坐标,与经度同时传入;与城市二选一传入
+ `longitude` `float` 经度坐标,与纬度同时传入;与城市二选一传入
+ `city` `string` 城市名称,与经纬度二选一传入
+ `region` `string` 区域名称,在城市存在的情况下可省;与经纬度二选一传入
+ `uid` `string` 用户唯一id(非开发者id),用户区分公众号下的不同用户(建议填入用户openid),如果为空,则无法使用上下文理解功能。appid和uid同时存在的情况下,才可以使用上下文理解功能。
> 注:单类别意图比较明确,识别的覆盖率比较大,所以如果只要使用特定某个类别,建议将 category 只设置为该类别。
示例:
```php
$result = $app->semantic->query('查一下明天从北京到上海的南航机票', "flight,hotel", array('city' => '北京', 'uid' => '123456'));
// 查询参数:
// {
// "query":"查一下明天从北京到上海的南航机票",
// "city":"北京",
// "category": "flight,hotel",
// "appid":"wxaaaaaaaaaaaaaaaa",
// "uid":"123456"
// }
```
返回值示例:
```json
{
"errcode":0,
"query":"查一下明天从北京到上海的南航机票",
"type":"flight",
"semantic":{
"details":{
"start_loc":{
"type":"LOC_CITY",
"city":"北京市",
"city_simple":"北京",
"loc_ori":"北京"
},
"end_loc": {
"type":"LOC_CITY",
"city":"上海市",
"city_simple":"上海",
"loc_ori":"上海"
},
"start_date": {
"type":"DT_ORI",
"date":"2014-03-05",
"date_ori":"明天"
},
"airline":"中国南方航空公司"
},
"intent":"SEARCH"
}
```
================================================
FILE: docs/src/5.x/official-account/server.md
================================================
# 服务端
我们在入门小教程一节以服务端为例讲解了一个基本的消息的处理,这里就不再讲服务器验证的流程了,请直接参考前面的入门实例即可。
服务端的作用呢,在整个微信开发中主要是负责 **[接收用户发送过来的消息](https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html)**,还有 **[用户触发的一系列事件](https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_event_pushes.html)**。
首先我们得理清消息与事件的回复逻辑,当你收到用户消息后(消息由微信服务器推送到你的服务器),在你对消息进行一些处理后,不管是选择回复一个消息还是什么不都回给用户,你也应该给微信服务器一个 “答复”,如果是选择回复一条消息,就直接返回一个消息xml就好,如果选择不作任何回复,你也得回复一个空字符串或者字符串 `SUCCESS`(不然用户就会看到 `该公众号暂时无法提供服务`)。
## 基本使用
在 SDK 中使用 `$app->server->push(callable $callback)` 来设置消息处理器:
```php
$app->server->push(function ($message) {
// $message['FromUserName'] // 用户的 openid
// $message['MsgType'] // 消息类型:event, text....
return "您好!欢迎使用 EasyWeChat";
});
// 在 laravel 中:
$response = $app->server->serve();
// $response 为 `Symfony\Component\HttpFoundation\Response` 实例
// 对于需要直接输出响应的框架,或者原生 PHP 环境下
$response->send();
// 而 laravel 中直接返回即可:
return $response;
```
这里我们使用 `push` 传入了一个 **闭包([Closure](http://php.net/manual/en/class.closure.php))**,该闭包接收一个参数 `$message` 为消息对象(类型取决于你的配置中 `response_type`),你可以在全局消息处理器中对消息类型进行筛选:
```php
$app->server->push(function ($message) {
switch ($message['MsgType']) {
case 'event':
return '收到事件消息';
break;
case 'text':
return '收到文字消息';
break;
case 'image':
return '收到图片消息';
break;
case 'voice':
return '收到语音消息';
break;
case 'video':
return '收到视频消息';
break;
case 'location':
return '收到坐标消息';
break;
case 'link':
return '收到链接消息';
break;
case 'file':
return '收到文件消息';
// ... 其它消息
default:
return '收到其它消息';
break;
}
// ...
});
```
当然,因为这里 `push` 接收一个 [`callable`](http://php.net/manual/zh/language.types.callable.php) 的参数,所以你不一定要传入一个 Closure 闭包,你可以选择传入一个函数名,一个 `[$class, $method]` 或者 `Foo::bar` 这样的类型。
某些情况,我们需要直接使用 `$message` 参数,那么怎么在 `push` 的闭包外调用呢?
```php
$message = $app->server->getMessage();
```
> 注意:`$message` 的类型取决于你的配置中 `response_type`
## 注册多个消息处理器
有时候你可能需要对消息记日志,或者一系列的自定义操作,你可以注册多个 handler:
```php
$app->server->push(MessageLogHandler::class);
$app->server->push(MessageReplyHandler::class);
$app->server->push(OtherHandler::class);
$app->server->push(...);
```
1. 最后一个非空返回值将作为最终应答给用户的消息内容,如果中间某一个 handler 返回值 false, 则将终止整个调用链,不会调用后续的 handlers。
2. 传入的自定义 Handler 类需要实现 `\EasyWeChat\Kernel\Contracts\EventHandlerInterface`。
## 注册指定消息类型的消息处理器
我们想对特定类型的消息应用不同的处理器,可以在第二个参数传入类型筛选:
> 注意,第二个参数必须是 `\EasyWeChat\Kernel\Messages\Message` 类的常量。
```php
use EasyWeChat\Kernel\Messages\Message;
$app->server->push(ImageMessageHandler::class, Message::IMAGE); // 图片消息
$app->server->push(TextMessageHandler::class, Message::TEXT); // 文本消息
// 同时处理多种类型的处理器
$app->server->push(MediaMessageHandler::class, Message::VOICE|Message::VIDEO|Message::SHORT_VIDEO); // 当消息为 三种中任意一种都可触发
```
## 请求消息的属性
当你接收到用户发来的消息时,可能会提取消息中的相关属性,参考:
请求消息基本属性(以下所有消息都有的基本属性):
>> - `ToUserName` 接收方帐号(该公众号 ID)
>> - `FromUserName` 发送方帐号(OpenID, 代表用户的唯一标识)
>> - `CreateTime` 消息创建时间(时间戳)
>> - `MsgId` 消息 ID(64位整型)
### 文本:
> - `MsgType` text
> - `Content` 文本消息内容
### 图片:
> - `MsgType` image
> - `MediaId` 图片消息媒体id,可以调用多媒体文件下载接口拉取数据。
> - `PicUrl` 图片链接
### 语音:
> - `MsgType` voice
> - `MediaId` 语音消息媒体id,可以调用多媒体文件下载接口拉取数据。
> - `Format` 语音格式,如 amr,speex 等
> - `Recognition` * 开通语音识别后才有
> 识别后,用户每次发送语音给公众号时,微信会在推送的语音消息XML数据包中,增加一个 `Recongnition` 字段
### 视频:
> - `MsgType` video
> - `MediaId` 视频消息媒体id,可以调用多媒体文件下载接口拉取数据。
> - `ThumbMediaId` 视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。
### 小视频:
> - `MsgType` shortvideo
> - `MediaId` 视频消息媒体id,可以调用多媒体文件下载接口拉取数据。
> - `ThumbMediaId` 视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。
### 事件:
> - `MsgType` event
> - `Event` 事件类型 (如:subscribe(订阅)、unsubscribe(取消订阅) ..., CLICK 等)
#### 扫描带参数二维码事件
> - `EventKey` 事件KEY值,比如:qrscene_123123,qrscene_为前缀,后面为二维码的参数值
> - `Ticket` 二维码的 ticket,可用来换取二维码图片
#### 上报地理位置事件
> - `Latitude` 23.137466 地理位置纬度
> - `Longitude` 113.352425 地理位置经度
> - `Precision` 119.385040 地理位置精度
#### 自定义菜单事件
> - `EventKey` 事件KEY值,与自定义菜单接口中KEY值对应,如:CUSTOM_KEY_001, www.qq.com
### 地理位置:
> - `MsgType` location
> - `Location_X` 地理位置纬度
> - `Location_Y` 地理位置经度
> - `Scale` 地图缩放大小
> - `Label` 地理位置信息
### 链接:
> - `MsgType` link
> - `Title` 消息标题
> - `Description` 消息描述
> - `Url` 消息链接
### 文件:
> - `MsgType` file
> - `Title` 文件名
> - `Description` 文件描述,可能为null
> - `FileKey` 文件KEY
> - `FileMd5` 文件MD5值
> - `FileTotalLen` 文件大小,单位字节
## 回复消息
回复的消息可以为 `null`,此时 SDK 会返回给微信一个 "SUCCESS",你也可以回复一个普通字符串,比如:`欢迎关注 overtrue.`,此时 SDK 会对它进行一个封装,产生一个 [`EasyWeChat\Kernel\Messages\Text`](https://github.com/EasyWeChat/message/blob/master/src/Kernel/Messages/Text.php) 类型的消息并在最后的 `$app->server->serve();` 时生成对应的消息 XML 格式。
如果你想返回一个自己手动拼的原生 XML 格式消息,请返回一个 [`EasyWeChat\Kernel\Messages\Raw`](https://github.com/EasyWeChat/message/blob/master/src/Kernel/Messages/Raw.php) 实例即可。
## 消息转发给客服系统
参见:[多客服消息转发](message-transfer)
关于消息的使用,请参考 [`消息`](messages) 章节。
================================================
FILE: docs/src/5.x/official-account/shake-around.md
================================================
# 摇一摇周边
摇一摇周边是微信在线下的全新功能, 为线下商户提供近距离连接用户的能力, 并支持线下商户向周边用户提供个性化营销、互动及信息推荐等服务。
## 获取实例
```php
$shakearound = $app->shake_around;
```
## 说明
> 特别提醒:
1、下述所有的接口调用的方法参数都要严格按照方法参数前的类型传入相应类型的实参,否则可能会得到非预期的结果。
2、涉及需要传入设备id($deviceIdentifier)的参数时,该参数是一个以 `device_id` 或包含 `uuid` `major` `minor` 为key的关联数组。
3、涉及需要传入设备id列表($deviceIdentifiers)的参数时,该参数是一个二维数组,第一层为索引类型,第二层为关联类型($deviceIdentifier)。
```php
// 参数 $deviceIdentifier 的实参形式:
['device_id' => 10097]
// 或
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12102,
]
// 参数$deviceIdentifiers的实参形式:
[
['device_id' => 10097],
['device_id' => 10098],
]
// 或
[
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12102,
],
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12103,
]
]
```
## 开通摇一摇周边
> 提示:
若不是做 [公众号第三方平台](https://open.weixin.qq.com/cgi-bin/frame?t=home/wx_plugin_tmpl&lang=zh_CN) 开发,建议直接在微信管理后台申请开通摇一摇周边功能。
### 申请开通
申请开通摇一摇周边功能。成功提交申请请求后,工作人员会在三个工作日内完成审核。若审核不通过,可以重新提交申请请求。若是审核中,请耐心等待工作人员审核,在审核中状态不能再提交申请请求。
方法
```php
$shakearound->register($data)
```
> 注意:
1、相关资质文件的图片是使用本页面下方的素材管理的接口上传的,切勿和另一个 [素材管理](material) 接口混淆。
2、行业代码请务必传入**字符串**类型的实参,否则以数字0开头的行业代码将会被当成八进制数处理(将转换为十进制数),这可能不是期望的。
### 查询审核状态
查询已经提交的开通摇一摇周边功能申请的审核状态。在申请提交后,工作人员会在三个工作日内完成审核。
方法
```php
$shakearound->status()
```
### 获取摇一摇的设备及用户信息
获取设备信息,包括UUID、major、minor,以及距离、openID等信息。
方法
```php
$shakearound->user($ticket);
// 或者需要返回门店poi_id
$shakearound->user($ticket, true);
```
## 设备管理
### 申请设备 ID
申请配置设备所需的UUID、Major、Minor。申请成功后返回批次ID,可用返回的批次ID通过“查询设备ID申请状态”接口查询目前申请的审核状态。
一个公众账号最多可申请100000个设备ID,如需申请的设备ID数超过最大限额,请邮件至zhoubian@tencent.com,邮件格式如下:
> 标题:申请提升设备ID额度
内容:
1、公众账号名称及appid(wx开头的字符串,在mp平台可查看)
2、用途
3、预估需要多少设备ID
方法
```php
$shakearound->device->apply($data)
```
### 查询设备 ID 申请审核状态
查询设备ID申请的审核状态。若单次申请的设备ID数量小于等于500个,系统会进行快速审核;若单次申请的设备ID数量大于500个,则在三个工作日内完成审核。
方法
```php
$shakearound->device->status($applyId) // $applyId 批次ID,申请设备ID时所返回的批次ID
```
### 编辑设备信息
> 仅能修改设备的备注信息。
方法
```php
$shakearound->device->update(array $deviceIdentifier, string $comment)
```
参数
> $deviceIdentifier 设备id,设备编号device_id或UUID、major、minor的关联数组,若二者都填,则以设备编号为优先
$comment 设备的备注信息,不超过15个汉字或30个英文字母
示例
```php
$result = $shakearound->device->update(['device_id' => 10011], 'test');
// 或
$result = $shakearound->device->update(['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
], 'test');
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result['errcode']) // 0
```
### 配置设备与门店/其他公众账号门店的关联关系
关联本公众账号门店时,支持创建门店后直接关联在设备上,无需为审核通过状态,摇周边后台自动更新门店的最新信息和状态。
关联其他公众账号门店时,支持设备关联其他公众账号的门店,门店需为审核通过状态。
> 因为第三方门店不归属本公众账号,所以未保存到设备详情中,查询设备列表接口与获取摇周边的设备及用户信息接口不会返回第三方门店。
方法
```php
$shakearound->device->bindPoi(array $deviceIdentifier, $poiId)
//或者 绑定第三方
$shakearound->device->bindThirdPoi(array $deviceIdentifier, $poiId, $poiAppId)
```
参数
> $deviceIdentifier 设备 id,设备编号 device_id 或 UUID、major、minor 的关联数组,若二者都填,则以设备编号为优先
$poiId 设备关联的门店 ID,关联门店后,在门店 1KM 的范围内有优先摇出信息的机会。当值为0时,将清除设备已关联的门店 ID
$poiAppId 关联门店所归属的公众账号的 APP ID
示例
```php
// 关联本公众账号门店
$result = $shakearound->device->bindLocation(['device_id' => 10011], 1231);
// 或
$result = $shakearound->device->bindLocation([
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
], 1231);
// 关联其他公众账号门店
// wxappid 为关联门店所归属的公众账号的 APP ID
$result = $shakearound->device->bindThirdPoi(['device_id' => 10011], 1231, 'wxappid');
// 或
$result = $shakearound->device->bindThirdPoi([
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
], 1231, 'wxappid');
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
```
## 查询设备列表
查询已有的设备 ID、UUID、Major、Minor、激活状态、备注信息、关联门店、关联页面等信息。
### 根据设备id批量取回设备数据
方法
> $shakearound->device->listByIds(array $deviceIdentifiers)
参数
> $deviceIdentifiers 设备id列表
示例
```php
$result = $shakearound->device->listByIds([
['device_id' => 10097],
['device_id' => 10098],
]);
// 或
$result = $shakearound->device->listByIds([
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12102,
],
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12103,
]
]);
/* 返回结果
{
"data": {
"devices": [
{
"comment": "",
"device_id": 10097,
"major": 10001,
"minor": 12102,
"status": 1,
"last_active_time":1437276018,
"poi_id": 0,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
},
{
"comment": "",
"device_id": 10098,
"major": 10001,
"minor": 12103,
"status": 1,
"last_active_time":1437276018,
"poi_appid":"wxe3813f5d8c546fc7"
"poi_id": 123,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
}
],
"total_count": 151
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 分页批量取回设备数据
方法
```php
$shakearound->device->list(int $lastId, int $count)
```
参数
> $lastId 前一次查询列表末尾的设备编号 device_id,第一次查询 lastId 为 0
$count 待查询的设备数量,不能超过50个
示例
```php
$result = $shakearound->device->list(10097, 3);
// 返回结果同上
```
### 根据申请时的批次 ID 分页批量取回设备数据
方法
> $shakearound->device->listByApplyId(int $applyId, int $lastId, int $count)
参数
> $applyId 批次ID,申请设备ID时所返回的批次ID
$lastId 前一次查询列表末尾的设备编号device_id,第一次查询 lastId 为 0
$count 待查询的设备数量,不能超过50个
示例
```php
$result = $shakearound->device->listByApplyId(1231, 10097, 3);
// 返回结果同上
```
## 页面管理
### 新增页面
新增摇一摇出来的页面信息,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。其中,图片必须为用素材管理接口上传至微信侧服务器后返回的链接。
>
图片是使用本页面下方的素材管理的接口上传的,切勿和另一个 [素材管理](material) 接口混淆。
方法
```php
$shakearound->page->create($data)
```
参数
> $title 在摇一摇页面展示的主标题,不超过6个汉字或12个英文字母
$description 在摇一摇页面展示的副标题,不超过7个汉字或14个英文字母
$pageUrl 点击进去的超链接
$iconUrl 在摇一摇页面展示的图片。图片需先上传至微信侧服务器,用“素材管理-上传图片素材”接口上传图片,返回的图片URL再配置在此处
$comment 可选,页面的备注信息,不超过15个汉字或30个英文字母
示例
```php
$result = $shakearound->page->create($data);
/* 返回结果
{
"data": {
"page_id": 28840
}
"errcode": 0,
"errmsg": "success."
}
*/
```
### 编辑页面信息
编辑摇一摇出来的页面信息,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。
方法
```php
$shakearound->page->update(int $pageId, array $data)
```
参数
> $pageId 摇周边页面唯一ID
$data 需要更新的信息
示例
```php
$result = $shakearound->page->update(28840, [
'title' => '主标题',
'description' => '副标题',
//...
]);
```
## 查询页面列表
查询已有的页面,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。
### 根据页面id批量取回页面数据
方法
```php
$shakearound->page->listByIds(array $pageIds)
```
参数
> $pageIds 页面的id列表,索引数组
示例
```php
$result = $shakearound->page->listByIds([28840, 28842]);
/* 返回结果
{
"data": {
"pages": [
{
"comment": "just for test",
"description": "test",
"icon_url": "https://www.baidu.com/img/bd_logo1",
"page_id": 28840,
"page_url": "http://xw.qq.com/testapi1",
"title": "测试1"
},
{
"comment": "just for test",
"description": "test",
"icon_url": "https://www.baidu.com/img/bd_logo1",
"page_id": 28842,
"page_url": "http://xw.qq.com/testapi2",
"title": "测试2"
}
],
"total_count": 2
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 分页批量取回页面数据
方法
```php
$shakearound->page->list(int $begin, int $count)
```
参数
> $begin 页面列表的起始索引值
$count 待查询的页面数量,不能超过50个
示例
```php
$result = $shakearound->page->list(0,2);
// 返回结果同上
```
### 删除页面
删除已有的页面,包括在摇一摇页面出现的主标题、副标题、图片和点击进去的超链接。
>
只有页面与设备没有关联关系时,才可被删除。
方法
```php
$shakearound->page->delete(int $pageId)
```
参数
> $pageId 页面的id
示例
```php
$result = $shakearound->page->delete(34567);
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 素材管理
上传在摇一摇功能中需使用到的图片素材,素材保存在微信侧服务器上。图片格式限定为:jpg,jpeg,png,gif。
若图片为在摇一摇页面展示的图片,则其素材为 `icon` 类型的图片,图片大小建议 `120px*120 px` ,限制不超过 `200 px *200 px` ,图片需为 `正方形` 。
若图片为申请开通摇一摇周边功能需要上传的资质文件图片,则其素材为 `license` 类型的图片,图片的文件大小不超过 `2MB` ,尺寸不限,形状不限。
方法
> $shakearound->material->uploadImage(string $path [, string $type = 'icon'])
参数
> $path 图片所在路径
$type 可选,值为icon或license
示例
```php
$result = $shakearound->material->uploadImage(__DIR__ . '/stubs/image.jpg');
/* 返回结果
{
"data": {
"pic_url": http://shp.qpic.cn/wechat_shakearound_pic/0/1428377032e9dd2797018cad79186e03e8c5aec8dc/120"
},
"errcode": 0,
"errmsg": "success."
}
*/
```
## 管理设备与页面的关系
通过接口申请的设备ID,需先配置页面,若未配置页面,则摇不出页面信息。
### 配置设备与页面的关联关系
配置完成后,在此设备的信号范围内,即可摇出关联的页面信息。
若设备配置多个页面,则随机出现页面信息。一个设备最多可配置30个关联页面。
>
1、配置时传入该设备需要关联的页面的id列表,该设备原有的关联关系将被直接清除。
2、页面的id列表允许为空(**传入空数组**),当页面的id列表为空时则会清除该设备的所有关联关系。
方法
> $shakearound->relation->bindPage(array $deviceIdentifier, array $pageIds)
参数
> $deviceIdentifier 设备id,设备编号device_id或UUID、major、minor的关联数组,若二者都填,则以设备编号为优先
$pageIds 页面的id列表,索引数组
示例
```php
$result = $shakearound->relation->bindPage(['device_id' => 10011], [12345, 23456, 334567]);
// 或
$result = $shakearound->relation->bindPage(['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
], [12345, 23456, 334567]);
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
var_dump($result->errcode) // 0
```
### 查询设备与页面的关联关系
#### 查询指定设备所关联的页面
根据设备ID或完整的UUID、Major、Minor查询该设备所关联的所有页面信息
方法
> $shakearound->relation->listByDeviceId(array $deviceIdentifier [, boolean $raw = false])
>
该方法默认对返回的数据进行处理后返回一个包含页面id的索引数组。若要返回和 `getDeviceByPageId` 方法类似的数据,请传入 `true` 作为第二个参数。
参数
> $deviceIdentifier 设备id,设备编号device_id或UUID、major、minor的关联数组,若二者都填,则以设备编号为优先
$raw 可选,当为true时,返回值和getDeviceByPageId方法类似,否则返回页面的id列表(索引数组,无关联时为空数组)
示例
```php
$result = $shakearound->relation->listByDeviceId(['device_id' => 10011]);
// 或
$result = $shakearound->relation->listByDeviceId([
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
]);
// 返回结果
var_dump($result) // [50054,50055]
```
##### 查询指定页面所关联的设备
指定页面ID分页查询该页面所关联的所有的设备信息
方法
> $shakearound->relation->listByPageId(int $pageId, int $begin, int $count)
参数
> $pageId 指定的页面id
$begin 关联关系列表的起始索引值
$count 待查询的关联关系数量,不能超过50个
示例
```php
$result = $shakearound->relation->listByPageId(50054, 0, 3);
/* 返回结果
{
"data": {
"relations": [
{
"device_id": 797994,
"major": 10001,
"minor": 10023,
"page_id": 50054,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
},
{
"device_id": 797995,
"major": 10001,
"minor": 10024,
"page_id": 50054,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
}
],
"total_count": 2
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 摇一摇数据统计
> 此接口无法获取当天的数据,最早只能获取前一天的数据。
由于系统在凌晨处理前一天的数据,太早调用此接口可能获取不到数据,建议在早上8:00之后调用此接口。
### 以设备为维度的数据统计
查询单个设备进行摇周边操作的人数、次数,点击摇周边消息的人数、次数。
>
查询的最长时间跨度为 30 天。只能查询最近 90 天的数据。
方法
> $shakearound->stats->deviceSummary(array $deviceIdentifier, int $beginDate, int $endDate)
参数
> $deviceIdentifier 设备id,设备编号device_id或UUID、major、minor的关联数组,若二者都填,则以设备编号为优先
$beginDate 起始日期时间戳,最长时间跨度为30天,单位为秒
$endDate 结束日期时间戳,最长时间跨度为30天,单位为秒
示例
```php
$result = $shakearound->stats->deviceSummary(['device_id' => 10011], 1425052800, 1425139200);
// 或
$result = $shakearound->stats->deviceSummary(['uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 1002,
'minor' => 1223,
], 1425052800, 1425139200);
/* 返回结果
{
"data": [
{
"click_pv": 0,
"click_uv": 0,
"ftime": 1425052800,
"shake_pv": 0,
"shake_uv": 0
},
{
"click_pv": 0,
"click_uv": 0,
"ftime": 1425139200,
"shake_pv": 0,
"shake_uv": 0
}
],
"errcode": 0,
"errmsg": "success."
}
*/
```
### 批量查询设备统计数据
查询指定时间商家帐号下的每个设备进行摇周边操作的人数、次数,点击摇周边消息的人数、次数。
> 只能查询最近90天内的数据,且一次只能查询一天。
>
对于摇周边人数、摇周边次数、点击摇周边消息的人数、点击摇周边消息的次数都为0的设备,不在结果列表中返回。
方法
```php
$shakearound->stats->devicesSummary(int $timestamp, int $pageIndex)
```
参数
> $timestamp 指定查询日期时间戳,单位为秒
$pageIndex 指定查询的结果页序号,返回结果按摇周边人数降序排序,每50条记录为一页
示例
```php
$result = $shakearound->stats->devicesSummary(1435075200, 1);
/* 返回结果
{
"data": {
"devices": [
{
"device_id": 10097,
"major": 10001,
"minor": 12102,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
"shake_pv": 1
"shake_uv": 2
"click_pv": 3
"click_uv": 4
},
{
"device_id": 10098,
"major": 10001,
"minor": 12103,
"uuid": "FDA50693-A4E2-4FB1-AFCF-C6EB07647825"
"shake_pv": 1
"shake_uv": 2
"click_pv": 3
"click_uv": 4
}
],
},
"date":1435075200
"total_count": 151
"page_index":1
"errcode": 0,
"errmsg": "success."
}
*/
```
### 以页面为维度的数据统计
查询单个页面通过摇周边摇出来的人数、次数,点击摇周边页面的人数、次数
> 注意:
查询的最长时间跨度为30天。只能查询最近90天的数据。
方法
```php
$shakearound->stats->pageSummary(int $pageId, int $beginDate, int $endDate);
```
参数
> $pageId 指定页面的页面ID
$beginDate 起始日期时间戳,最长时间跨度为30天,单位为秒
$endDate 结束日期时间戳,最长时间跨度为30天,单位为秒
示例
```php
$result = $shakearound->stats->pageSummary(12345, 1425052800, 1425139200);
/* 返回结果
{
"data": [
{
"click_pv": 0,
"click_uv": 0,
"ftime": 1425052800,
"shake_pv": 0,
"shake_uv": 0
},
{
"click_pv": 0,
"click_uv": 0,
"ftime": 1425139200,
"shake_pv": 0,
"shake_uv": 0
}
],
"errcode": 0,
"errmsg": "success."
}
*/
```
### 批量查询页面统计数据
查询指定时间商家帐号下的每个页面进行摇周边操作的人数、次数,点击摇周边消息的人数、次数。
>
对于摇周边人数、摇周边次数、点击摇周边消息的人数、点击摇周边消息的次数都为0的页面,不在结果列表中返回。
方法
```php
$shakearound->stats->pagesSummary(int $timestamp, int $pageIndex);
```
参数
> $timestamp 指定查询日期时间戳,单位为秒
$pageIndex 指定查询的结果页序号,返回结果按摇周边人数降序排序,每50条记录为一页
示例
```php
$result = $shakearound->stats->pagesSummary(1435075200, 1);
/* 返回结果
{
"data": {
"pages": [
{
"page_id":1234
"click_pv": 1,
"click_uv": 3,
"shake_pv": 0,
"shake_uv": 0
},
{
"page_id":5678
"click_pv": 1,
"click_uv": 2,
"shake_pv": 0,
"shake_uv": 0
},
],
},
"date":1435075200
"total_count": 151
"page_index":1
"errcode": 0,
"errmsg": "success."
}
*/
```
## 设备分组管理
调用H5页面获取设备信息 JS API接口,需要先把设备分组,微信客户端只会返回已在分组中的设备信息。
### 新增分组
新建设备分组,每个帐号下最多只有1000个分组。
方法
```php
$shakearound->group->create(string $name)
参数
> $name 分组名称,不超过100汉字或200个英文字母
示例
```php
$result = $shakearound->group->create('test');
/* 返回结果
{
"data": {
"group_id" : 123,
"group_name" : "test"
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 编辑分组信息
编辑设备分组信息,目前只能修改分组名。
方法
> $shakearound->group->update(int $groupId, string $name)
参数
> $groupId 分组唯一标识,全局唯一
$name 分组名称,不超过100汉字或200个英文字母
示例
```php
$result = $shakearound->group->update(123, 'newName');
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 删除分组
删除设备分组,若分组中还存在设备,则不能删除成功。需把设备移除以后,才能删除。
> 在执行删除前,最好先使用 `get` 方法查询分组详情,若分组内有设备,先使用 `removeDevices` 方法移除。
方法
```php
$shakearound->group->delete(int $groupId)
```
参数
> $groupId 分组唯一标识,全局唯一
示例
```php
$result = $shakearound->group->delete(123);
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 查询分组列表
查询账号下所有的分组。
方法
```php
$shakearound->group->list(int $begin, int $count)
```
参数
> $begin 分组列表的起始索引值
$count 待查询的分组数量,不能超过1000个
示例
```php
$result = $shakearound->group->list(0, 2);
/* 返回结果
{
"data": {
"groups":[
{
"group_id" : 123,
"group_name" : "test1"
},
{
"group_id" : 124,
"group_name" : "test2"
}
],
"total_count": 100
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 查询分组详情
查询分组详情,包括分组名,分组id,分组里的设备列表。
方法
```php
$shakearound->group->get(int $groupId, int $begin, int $count)
```
参数
> $groupId 分组唯一标识,全局唯一
$begin 分组里设备的起始索引值
$count 待查询的分组里设备的数量,不能超过1000个
示例
```php
$result = $shakearound->group->get(123, 0, 2);
/* 返回结果
{
"data": {
"group_id" : 123,
"group_name" : "test",
"total_count": 100,
"devices" :[
{
"device_id" : 123456,
"uuid" : "FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
"major" : 10001,
"minor" : 10001,
"comment" : "test device1",
"poi_id" : 12345,
},
{
"device_id" : 123457,
"uuid" : "FDA50693-A4E2-4FB1-AFCF-C6EB07647825",
"major" : 10001,
"minor" : 10002,
"comment" : "test device2",
"poi_id" : 12345,
}
]
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 添加设备到分组
添加设备到分组,每个分组能够持有的设备上限为10000,并且每次添加操作的添加上限为1000。
> 只有在摇周边申请的设备才能添加到分组。
方法
> $shakearound->group->addDevices(int $groupId, array $deviceIdentifiers)
参数
> $groupId 分组唯一标识,全局唯一
$deviceIdentifiers 设备id列表
示例
```php
$result = $shakearound->group->addDevices(123, [
['device_id' => 10097],
['device_id' => 10098],
]);
// 或
$result = $shakearound->group->addDevices(123, [
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12102,
],
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12103,
]
]);
/* 返回结果
{
"data": {
},
"errcode": 0,
"errmsg": "success."
}
*/
```
### 从分组中移除设备
从分组中移除设备,每次删除操作的上限为 1000。
方法
```php
$shakearound->group->removeDevices(int $groupId, array $deviceIdentifiers)
```
参数
> $groupId 分组唯一标识,全局唯一
$deviceIdentifiers 设备id列表
示例
```php
$result = $shakearound->group->removeDevices(123, [
['device_id' => 10097],
['device_id' => 10098],
]);
// 或
$result = $shakearound->group->removeDevices(123, [
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12102,
],
[
'uuid' => 'FDA50693-A4E2-4FB1-AFCF-C6EB07647825',
'major' => 10001,
'minor' => 12103,
]
]);
```
## 摇一摇事件通知
用户进入摇一摇界面,在“周边”页卡下摇一摇时,微信会把这个事件推送到开发者填写的URL(登录公众平台进入开发者中心设置)。推送内容包含摇一摇时“周边”页卡展示出来的页面所对应的设备信息,以及附近最多五个属于该公众账号的设备的信息。当摇出列表时,此事件不推送。
> 摇一摇事件的事件类型:ShakearoundUserShake
关于事件的处理请移步: [事件](events)
================================================
FILE: docs/src/5.x/official-account/store.md
================================================
# 门店小程序
## 拉取门店小程序类目
```php
$app->store->categories();
```
## 创建门店小程序
> 说明:创建门店小程序提交后需要公众号管理员确认通过后才可进行审核。如果主管理员 24 小时超时未确认,才能再次提交。
```php
$app->store->createMerchant($baseInfo);
```
> - `$baseInfo` 为门店小程序的基本信息数组,**`qualification_list` 字段为类目相关证件的临时素材 `mediaid` 如果 `second_catid` 对应的 `sensitive_type` 为 1 ,则 `qualification_list` 字段需要填 支持 0~5 个 `mediaid`,例如 `mediaid1`。`headimg_mediaid` 字段为头像 --- 临时素材 `mediaid`。`mediaid` 用现有的 `media/upload` 接口得到的,获取链接: [临时素材](../basic-services/media.md) ( 支持 PNG\JPEG\JPG\GIF 格式的图片,后续加上其他格式)**
示例:
```php
$info = [
"first_catid" => 476, //categories 接口获取的一级类目id
"second_catid" => 477, //categories 接口获取的二级类目id
"qualification_list" => "RTZgKZ386yFn5kQSWLTxe4bqxwgzGBjs3OE02cg9CVQk1wRVE3c8fjUFX7jvpi-P",
"headimg_mediaid" => "RTZgKZ386yFn5kQSWLTxe4bqxwgzGBjs3OE02cg9CVQk1wRVE3c8fjUFX7jvpi-P",
"nickname" => "hardenzhang308",
"intro" => "hardenzhangtest",
"org_code" => "",
"other_files" => ""
];
$result = $app->store->createMerchant($info);
```
> 注意:创建门店小程序的审核结果,会以事件形式推送给商户填写的回调 URL
## 查询门店小程序审核结果
```php
$app->store->getStatus($baseInfo);
```
## 修改门店小程序信息
```php
$app->store->updateMerchant($data);
```
> - `$data` 需要更新的部分数据,目前仅支持门店头像和门店小程序介绍,**若有填写内容则为覆盖更新,若无内容则视为不修改,维持原有内容。`headimg_mediaid`、`intro` 字段参考创建门店小程序**
示例:
```php
$data = [
"headimg_mediaid" => "RTZgKZ386yFn5kQSWLTxe4bqxwgzGBjs3OE02cg9CVQk1wRVE3c8fjUFX7jvpi-P",
"intro" => "麦辣鸡腿堡套餐,麦乐鸡,全家桶",
];
$result = $app->store->updateMerchant($data);
```
## 从腾讯地图拉取省市区信息
```php
$app->store->districts();
```
## 在腾讯地图中搜索门店
```php
$app->store->searchFromMap($districtId, $keyword);
```
> - `$districtId` 为从腾讯地图拉取的地区 `id`
> - `$keyword` 为搜索的关键词
## 在腾讯地图中创建门店
```php
$app->store->createFromMap($baseInfo);
```
示例:
```php
$baseInfo = [
"name" => "hardenzhang",
"longitude" => "113.323753357",
"latitude" => "23.0974903107",
"province" => "广东省",
"city" => "广州市",
"district" => "海珠区",
"address" => "TIT",
"category" => "类目1:类目2",
"telephone" => "12345678901",
"photo" => "http://mmbiz.qpic.cn/mmbiz_png/tW66AWE2K6ECFPcyAcIZTG8RlcR0sAqBibOm8gao5xOoLfIic9ZJ6MADAktGPxZI7MZLcadZUT36b14NJ2cHRHA/0?wx_fmt=png",
"license" => "http://mmbiz.qpic.cn/mmbiz_png/tW66AWE2K6ECFPcyAcIZTG8RlcR0sAqBibOm8gao5xOoLfIic9ZJ6MADAktGPxZI7MZLcadZUT36b14NJ2cHRHA/0?wx_fmt=png",
"introduct" => "test",
"districtid" => "440105",
];
```
> - `$baseInfo`: 门店相关信息
> 事件推送 --- 腾讯地图中创建门店的审核结果。腾讯地图审核周期为 3 个工作日,请在期间内留意审核结果事件推送。提交后未当即返回事件推送即为审核中,请耐心等待。
## 添加门店
```php
$app->store->create($baseInfo);
```
示例:
```php
$baseInfo = [
"poi_id" => "",
"map_poi_id" => "2880741500279549033",
"pic_list" => "['list' => ['http://mmbiz.qpic.cn/mmbiz_jpg/tW66AWvE2K4EJxIYOVpiaGOkfg0iayibiaP2xHOChvbmKQD5uh8ymibbEKlTTPmjTdQ8ia43sULLeG1pT2psOfPic4kTw/0?wx_fmt=jpeg']]",
"contract_phone" => "1111222222",
"credential" => "22883878-0",
"qualification_list" => "RTZgKZ386yFn5kQSWLTxe4bqxwgzGBjs3OE02cg9CVQk1wRVE3c8fjUFX7jvpi-P"
];
```
> - `$baseInfo`: 门店相关信息。`pic_list` 门店图片,可传多张图片 `pic_list`
> 事件推送 - 创建门店的审核结果
## 更新门店信息
```php
$app->store->update($baseInfo);
```
> - `$baseInfo`: 门店相关信息。
> 果要更新门店的图片,实际相当于走一次重新为门店添加图片的流程,之前的旧图片会全部废弃。并且如果重新添加的图片中有与之前旧图片相同的,此时这个图片不需要重新审核。
================================================
FILE: docs/src/5.x/official-account/template_message.md
================================================
# 模板消息
模板消息仅用于公众号向用户发送重要的服务通知,只能用于符合其要求的服务场景中,如信用卡刷卡通知,商品购买成功通知等。不支持广告等营销类消息以及其它所有可能对用户造成骚扰的消息。
## 修改账号所属行业
```php
$app->template_message->setIndustry($industryId1, $industryId2);
```
## 获取支持的行业列表
```php
$app->template_message->getIndustry();
```
## 添加模板
在公众号后台获取 `$shortId` 并添加到账户。
```php
$app->template_message->addTemplate($shortId);
```
## 获取所有模板列表
```php
$app->template_message->getPrivateTemplates();
```
## 删除模板
```php
$app->template_message->deletePrivateTemplate($templateId);
```
## 发送模板消息
```php
$app->template_message->send([
'touser' => 'user-openid',
'template_id' => 'template-id',
'url' => 'https://easywechat.com',
'miniprogram' => [
'appid' => 'xxxxxxx',
'pagepath' => 'pages/xxx',
],
'data' => [
'key1' => 'VALUE',
'key2' => 'VALUE2',
...
],
]);
```
> 如果 url 和 miniprogram 字段都传,会优先跳转小程序。
## 发送一次性订阅消息
```php
$app->template_message->sendSubscription([
'touser' => 'user-openid',
'template_id' => 'template-id',
'url' => 'https://easywechat.com',
'scene' => 1000,
'data' => [
'key1' => 'VALUE',
'key2' => 'VALUE2',
...
],
]);
```
> 如果你想为发送的内容字段指定颜色,你可以将 "data" 部分写成下面 4 种不同的样式,不写 `color` 将会是默认黑色:
```php
'data' => [
'foo' => '你好', // 不需要指定颜色
'bar' => ['你好', '#F00'], // 指定为红色
'baz' => ['value' => '你好', 'color' => '#550038'], // 与第二种一样
'zoo' => ['value' => '你好'], // 与第一种一样
]
```
================================================
FILE: docs/src/5.x/official-account/tutorial.md
================================================
# 快速开始
在我们已经安装完成后,即可很快的开始使用它了,当然你还是有必要明白 PHP 基本知识,如命名空间等,我这里就不赘述了。
我们以完成服务器端验证与接收响应用户发送的消息为例来演示,首先你有必要了解一下微信交互的运行流程:
```
+-----------------+ +---------------+
+----------+ | | POST/GET/PUT | |
| | ------------------> | | -------------------> | |
| user | | wechat server | | your server |
| | < - - - - - - - - - | | | |
+----------+ | | <- - - - - - - - - - | |
+-----------------+ +---------------+
```
那么我们要做的就是图中 **微信服务器把用户消息转到我们的自有服务器(虚线返回部分)** 后的处理过程。
## 服务端验证
在微信接入开始有一个 “服务器验证” 的过程,这一步呢,其实就是微信服务器向我们服务器发起一个请求(上图实线部分),传了一个名称为 `echostr` 的字符串过来,我们只需要原样返回就好了。
你也知道,微信后台只能填写一个服务器地址,所以 **服务器验证** 与 **消息的接收与回复**,都在这一个链接内完成交互。
考虑到这些,我已经把验证这一步给封装到 SDK 里了,你可以完全忽略这一步。
下面我们来配置一个基本的服务端,这里假设我们自己的服务器域名叫 `easywechat.com`,我们在服务器上准备这么一个文件`server.php`:
// server.php
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'wx3cf0f39249eb0xxx',
'secret' => 'f1c242f4f28f735d4687abb469072xxx',
'token' => 'TestToken',
'response_type' => 'array',
//...
];
$app = Factory::officialAccount($config);
$response = $app->server->serve();
// 将响应输出
$response->send();exit; // Laravel 里请使用:return $response;
```
> :heart: 安全模式下请一定要配置 `aes_key`
一个服务端带验证功能的代码已经完成,当然没有对消息做处理,别着急,后面我们再讲。
我们先来分析上面的代码:
```php
// 引入我们的主项目工厂类。
use EasyWeChat\Factory;
// 一些配置
$config = [...];
// 使用配置来初始化一个公众号应用实例。
$app = Factory::officialAccount($config);
$response = $app->server->serve();
// 将响应输出
$response->send(); exit; // Laravel 里请使用:return $response;
```
最后这一行我有必要详细讲一下:
> 1. 我们的 `$app->server->serve()` 就是执行服务端业务了,那么它的返回值是一个 `Symfony\Component\HttpFoundation\Response` 实例。
> 2. 我这里是直接调用了它的 `send()` 方法,它就是直接输出(echo)了,我们在一些框架就不能直接输出了,那你就直接拿到 Response 实例后做相应的操作即可,比如 Laravel 里你就可以直接 `return $app->server->serve();`
OK, 有了上面的代码,那么请你按 **[微信官方的接入指引](http://mp.weixin.qq.com/wiki/)** 在公众号后台完成配置并启用,并相应修改上面的 `$config` 的相关配置。
> URL 就是我们的 `http://easywechat.com/server.php`,这里我是举例哦,你可不要填写我的域名。
这样,点击提交验证就 OK 了。
> :heart: 请一定要将微信后台的开发者模式 “**启用**” !!!!!!看到红色 “**停用**” 才真正的是启用了。
> 最后,请不要用浏览器访问这个地址,它是给微信服务器访问的,不是给人访问的。
## 接收 & 回复用户消息
那服务端验证通过了,我们就来试一下接收消息吧。
> 在刚刚上面代码最后一行 `$app->server->serve()->send();` 前面,我们调用 `$app->server` 的 `push()` 方法来注册一个消息处理器,这里用到了 **[PHP 闭包](http://php.net/manual/zh/functions.anonymous.php)** 的知识,如果你不熟悉赶紧补课去。
```php
// ...
$app->server->push(function ($message) {
return "您好!欢迎使用 EasyWeChat!";
});
$response = $app->server->serve();
// 将响应输出
$response->send(); // Laravel 里请使用:return $response;
```
> 注意:send() 方法里已经包含 echo 了,请不要再加 echo 在前面。
好吧,打开你的微信客户端,向你的公众号发送任意一条消息,你应该会收到回复:`您好!欢迎使用 EasyWeChat!`。
> 到了“你的公众号暂时无法提供服务” ?, 好,那检查一下你的日志吧,日志在哪儿?我们的配置里写了日志路径了(`__DIR__.'/wechat.log'`)。 没有这个文件?看看权限哦。
> avel 框架应用时,因 POST 请求默认会有 CSRF 验证,所以需要在 `App\Http\Middleware\VerifyCsrfToken` 的 `except` 数组中添加微信请求,否则会提示“你的公众号暂时无法提供服务”。
一个基本的服务端验证就完成了。
## 总结
1. 所有的应用服务都通过主入口 `EasyWeChat\Factory` 类来创建:
```php
// 公众号
$app = Factory::officialAccount($config);
// 小程序
$app = Factory::miniProgram($config);
// 开放平台
$app = Factory::openPlatform($config);
// 企业微信
$app = Factory::work($config);
// 企业微信开放平台
$app = Factory::openWork($config);
// 微信支付
$app = Factory::payment($config);
```
## 最后
希望你在使用本 SDK 的时候如果你发现 SDK 的不足,欢迎提交 PR 或者给我[提建议 & 报告问题](https://github.com/overtrue/wechat/issues)。
================================================
FILE: docs/src/5.x/official-account/user-tag.md
================================================
# 用户标签
## 获取所有标签
```php
$app->user_tag->list();
```
示例:
```php
$tags = $app->user_tag->list();
// {
// "tags": [
// {
// "id": 0,
// "name": "标签1",
// "count": 72596
// },
// {
// "id": 1,
// "name": "标签2",
// "count": 36
// },
// ...
// ]
// }
```
## 创建标签
```php
$app->user_tag->create($name);
```
示例:
```php
$app->user_tag->create('测试标签');
```
## 修改标签信息
```php
$app->user_tag->update($tagId, $name);
```
示例:
```php
$app->user_tag->update(12, "新的名称");
```
## 删除标签
```php
$app->user_tag->delete($tagId);
```
## 获取指定 openid 用户所属的标签
```php
$userTags = $app->user_tag->userTags($openId);
//
// {
// "tagid_list":["标签1","标签2"]
// }
```
## 获取标签下用户列表
```php
$app->user_tag->usersOfTag($tagId, $nextOpenId = '');
// $nextOpenId:第一个拉取的OPENID,不填默认从头开始拉取
// {
// "count":2, // 这次获取的粉丝数量
// "data":{ // 粉丝列表
// "openid":[
// "ocYxcuAEy30bX0NXmGn4ypqx3tI0",
// "ocYxcuBt0mRugKZ7tGAHPnUaOW7Y"
// ]
// },
// "next_openid":"ocYxcuBt0mRugKZ7tGAHPnUaOW7Y"//拉取列表最后一个用户的openid
// }
```
## 批量为用户添加标签
```php
$openIds = [$openId1, $openId2, ...];
$app->user_tag->tagUsers($openIds, $tagId);
```
## 批量为用户移除标签
```php
$openIds = [$openId1, $openId2, ...];
$app->user_tag->untagUsers($openIds, $tagId);
```
================================================
FILE: docs/src/5.x/official-account/user.md
================================================
# 用户
用户信息的获取是微信开发中比较常用的一个功能了,以下所有的用户信息的获取与更新,都是**基于微信的 `openid` 的,并且是已关注当前账号的**,其它情况可能无法正常使用。
## 获取用户信息
获取单个:
```php
$user = $app->user->get($openId);
```
获取多个:
```php
$users = $app->user->select([$openId1, $openId2, ...]);
```
## 获取用户列表
```php
$app->user->list($nextOpenId = null); // $nextOpenId 可选
```
示例:
```php
$users = $app->user->list();
// result
{
"total": 2,
"count": 2,
"data": {
"openid": [
"OPENID1",
"OPENID2"
]
},
"next_openid": "NEXT_OPENID"
}
```
## 修改用户备注
```php
$app->user->remark($openId, $remark); // 成功返回boolean
```
示例:
```php
$app->user->remark($openId, "僵尸粉");
```
## 拉黑用户
```php
$app->user->block('openidxxxxx');
// 或者多个用户
$app->user->block(['openid1', 'openid2', 'openid3', ...]);
```
## 取消拉黑用户
```php
$app->user->unblock('openidxxxxx');
// 或者多个用户
$app->user->unblock(['openid1', 'openid2', 'openid3', ...]);
```
## 获取黑名单
```php
$app->user->blacklist($beginOpenid = null); // $beginOpenid 可选
```
## 账号迁移 openid 转换
账号迁移请从这里了解:https://kf.qq.com/product/weixinmp.html#hid=2488
微信用户关注不同的公众号,对应的 OpenID 是不一样的,迁移成功后,粉丝的 OpenID 以目标帐号(即新公众号)对应的 OpenID 为准。但开发者可以通过开发接口转换 OpenID,开发文档可以参考:
提供一个 openid 转换的 API 接口,当帐号迁移后,可以通过该接口:
1. 将原帐号粉丝的 openid 转换为新帐号的 openid。
2. 将有授权关系用户的 openid 转换为新帐号的 openid。
3. 将卡券关联用户的 openid 转换为新帐号的 openid。
> - ◆ 原帐号:准备要迁移的帐号,当审核完成且管理员确认后即被回收。
> - ◆ 新帐号:用来接纳粉丝的帐号。新帐号在整个流程中均能正常使用。
一定要按照下面的步骤来操作。
1. 一定要在原帐号被冻结之前,最好是准备提交审核前,获取原帐号的用户列表。如果没有原帐号的用户列表,用不了转换工具。如果原账号被回收,这时候也没办法调用接口获取用户列表。
如何获取用户列表见这里:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140840
2. 转换 openid 的 API 接口如下,可在帐号迁移审核完成后开始调用,并最多保留 15 天。若帐号迁移没完成,调用时无返回结果或报错。帐号迁移 15 天后,该转换接口将会失效、无法拉取到数据。
```php
$app->user->changeOpenid($oldAppId, $openidList);
```
返回值样例:
```json
{
"errcode": 0,
"errmsg": "ok",
"result_list": [
{
"ori_openid": "oEmYbwN-n24jxvk4Sox81qedINkQ",
"new_openid": "o2FwqwI9xCsVadFah_HtpPfaR-X4",
"err_msg": "ok"
},
{
"ori_openid": "oEmYbwH9uVd4RKJk7ZZg6SzL6tTo",
"err_msg": "ori_openid error"
}
]
}
```
================================================
FILE: docs/src/5.x/open-platform/authorizer-delegate.md
================================================
# 代授权方实现业务
> 授权方已经把公众号、小程序授权给你的开放平台第三方平台了,接下来的代授权方实现业务只需一行代码即可获得授权方实例。
## 实例化
```php
use EasyWeChat\Factory;
$config = [
// ...
];
$openPlatform = Factory::openPlatform($config);
```
### 获取授权方实例
```php
// 代公众号实现业务
$officialAccount = $openPlatform->officialAccount(string $appId, string $refreshToken);
// 代小程序实现业务
$miniProgram = $openPlatform->miniProgram(string $appId, string $refreshToken);
```
> $appId 为授权方公众号 APPID,非开放平台第三方平台 APPID
>
> $refreshToken 为授权方的 refresh_token,可通过 [获取授权方授权信息](https://easywechat.com/docs/master/open-platform/index#heading-h2-2) 接口获得。
### 帮助授权方管理开放平台账号
```php
// 代公众号实现业务
$account = $officialAccount->account;
// 代小程序实现业务
$account = $miniProgram->account;
// 创建开放平台账号
// 并绑定公众号或小程序
$result = $account->create();
// 将公众号或小程序绑定到指定开放平台帐号下
$result = $account->bindTo($openAppId);
// 将公众号/小程序从开放平台帐号下解绑
$result = $account->unbindFrom($openAppid);
// 获取公众号/小程序所绑定的开放平台帐号
$result = $account->getBinding();
```
> 授权第三方平台注册的开放平台帐号只可用于获取用户 unionid 实现用户身份打通。
>
> 第三方平台不可操作(包括绑定/解绑)通过 open.weixin.qq.com 线上流程注册的开放平台帐号。
>
> 公众号只可将此权限集授权给一个第三方平台,授权互斥。
接下来的 API 调用等操作和公众号、小程序的开发一致,请移步到[公众号](https://easywechat.com/docs/master/official-account/index)或[小程序](https://easywechat.com/docs/master/mini-program/index)开发章节继续进行开发吧。
### 代码示例
```php
// 假设你的公众号消息与事件接收 URL 为:https://easywechat.com/$APPID$/callback ...
Route::post('{appId}/callback', function ($appId) {
// ...
$officialAccount = $openPlatform->officialAccount($appId);
$server = $officialAccount->server; // ❗️❗️ 这里的 server 为授权方的 server,而不是开放平台的 server,请注意!!!
$server->push(function () {
return 'Welcome!';
});
return $server->serve();
});
// 调用授权方业务例子
Route::get('how-to-use', function () {
$officialAccount = $openPlatform->officialAccount('已授权的公众号 APPID', 'Refresh-token');
// 获取用户列表:
$officialAccount->user->list();
$miniProgram = $openPlatform->miniProgram('已授权的小程序 APPID', 'Refresh-token');
// 根据 code 获取 session
$miniProgram->auth->session('js-code');
// 其他同理
});
```
================================================
FILE: docs/src/5.x/open-platform/index.md
================================================
# 微信开放平台第三方平台
此页涉及接口信息与说明请参见:[授权流程技术说明 - 官方文档](https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1453779503&token=&lang=)
# 微信开放平台第三方平台
## 实例化
```php
'开放平台第三方平台 APPID',
'secret' => '开放平台第三方平台 Secret',
'token' => '开放平台第三方平台 Token',
'aes_key' => '开放平台第三方平台 AES Key'
];
$openPlatform = Factory::openPlatform($config);
```
## 获取用户授权页 URL
```php
$openPlatform->getPreAuthorizationUrl('https://easywechat.com/callback'); // 传入回调URI即可
```
## 使用授权码换取接口调用凭据和授权信息
在用户在授权页授权流程完成后,授权页会自动跳转进入回调URI,并在URL参数中返回授权码和过期时间,如:(https://easywechat.com/callback?auth_code=xxx&expires_in=600)
```php
$openPlatform->handleAuthorize(string $authCode = null);
```
> $authCode 不传的时候会获取 url 中的 auth_code 参数值
## 获取授权方的帐号基本信息
```php
$openPlatform->getAuthorizer(string $appId);
```
## 获取授权方的选项设置信息
```php
$openPlatform->getAuthorizerOption(string $appId, string $name);
```
## 设置授权方的选项信息
```php
$openPlatform->setAuthorizerOption(string $appId, string $name, string $value);
```
> 该API用于获取授权方的公众号或小程序的选项设置信息,如:地理位置上报,语音识别开关,多客服开关。注意,获取各项选项设置信息,需要有授权方的授权,详见权限集说明。
## 获取已授权的授权方列表
```php
$openPlatform->getAuthorizers(int $offset = 0, int $count = 500)
```
================================================
FILE: docs/src/5.x/open-platform/server.md
================================================
# 服务端
## 第三方平台推送事件
公众号第三方平台推送的有四个事件:
> 如已经授权的公众号、小程序再次进行授权,而未修改已授权的权限的话,是没有相关事件推送的。
授权成功 `authorized`
授权更新 `updateauthorized`
授权取消 `unauthorized`
VerifyTicket `component_verify_ticket`
SDK 默认会处理事件 `component_verify_ticket` ,并会缓存 `verify_ticket` 所以如果你暂时不需要处理其他事件,直接这样使用即可:
```php
$server = $openPlatform->server;
return $server->serve();
```
## 自定义消息处理器
> *消息处理器详细说明见公众号开发 - 服务端一节*
```php
use EasyWeChat\OpenPlatform\Server\Guard;
$server = $openPlatform->server;
// 处理授权成功事件
$server->push(function ($message) {
// ...
}, Guard::EVENT_AUTHORIZED);
// 处理授权更新事件
$server->push(function ($message) {
// ...
}, Guard::EVENT_UPDATE_AUTHORIZED);
// 处理授权取消事件
$server->push(function ($message) {
// ...
}, Guard::EVENT_UNAUTHORIZED);
```
### 示例(Laravel 框架)
```php
// 假设你的开放平台第三方平台设置的授权事件接收 URL 为: https://easywechat.com/open-platform (其他事件推送同样会推送到这个 URL)
Route::post('open-platform', function () { // 关闭 CSRF
// $openPlatform 为你实例化的开放平台对象,此处省略实例化步骤
return $openPlatform->server->serve(); // Done!
});
// 处理事件
use EasyWeChat\OpenPlatform\Server\Guard;
Route::post('open-platform', function () {
$server = $openPlatform->server;
// 处理授权成功事件,其他事件同理
$server->push(function ($message) {
// $message 为微信推送的通知内容,不同事件不同内容,详看微信官方文档
// 获取授权公众号 AppId: $message['AuthorizerAppid']
// 获取 AuthCode:$message['AuthorizationCode']
// 然后进行业务处理,如存数据库等...
}, Guard::EVENT_AUTHORIZED);
return $server->serve();
});
```
================================================
FILE: docs/src/5.x/open-work/index.md
================================================
# 企业微信第三方服务商
## 实例化
```php
'服务商的corpid',
'secret' => '服务商的secret,在服务商管理后台可见',
'suite_id' => '以ww或wx开头应用id',
'suite_secret' => '应用secret',
'token' => '应用的Token',
'aes_key' => '应用的EncodingAESKey',
'reg_template_id' => '注册定制化模板ID',
'redirect_uri_install' => '安装应用的回调url(可选)',
'redirect_uri_single' => '单点登录回调url (可选)',
'redirect_uri_oauth' => '网页授权第三方回调url (可选)',
];
$app = Factory::openWork($config);
```
================================================
FILE: docs/src/5.x/open-work/provider.md
================================================
# 服务商相关接口
## 单点登录
### 获取从第三方单点登录连接
```php
$app->provider->getLoginUrl(string $redirectUri = '', string $userType = 'admin', string $state = ''); //$redirectUri 回调地址 $userType支持登录的类型
```
### 获取登录用户信息
```php
$app->provider->getLoginInfo(string $authCode); //$authCode oauth2.0授权企业微信管理员登录产生的code,最长为512字节。只能使用一次,5分钟未被使用自动过期
```
## 注册定制化
### 获取注册码
```php
$app->provider->getRegisterCode(
string $corpName = '', //企业名称
string $adminName = '',//管理员姓名
string $adminMobile = '',//管理员手机号
string $state = ''//自定义的状态值
);
```
### 获取注册Uri
```php
$app->provider->getRegisterUri(string $registerCode = ''); //$registerCode 注册码
```
### 查询注册状态
```php
$app->provider->getRegisterInfo(string $registerCode); //$registerCode 注册码
```
### 设置授权应用可见范围
```php
$app->provider->setAgentScope(
string $accessToken, //查询注册状态接口返回的access_token
string $agentId, // 授权方应用id
array $allowUser = [], //应用可见范围(成员)若未填该字段,则清空可见范围中成员列表
array $allowParty = [], // 应用可见范围(部门)若未填该字段,则清空可见范围中部门列表
array $allowTag = [] //应用可见范围(标签)若未填该字段,则清空可见范围中标签列表
)
```
### 设置通讯录同步完成
```php
$app->provider->contactSyncSuccess(string $accessToken); //$accessToken //查询注册状态接口返回的access_token
```
### 通讯录单个搜索
```php
$app->provider->searchContact(
string $corpId, //查询的企业corpid
string $queryWord, //搜索关键词。当查询用户时应为用户名称、名称拼音或者英文名;当查询部门时应为部门名称或者部门名称拼音
string $agentId, //授权方应用id
int $offset = 0, //查询的偏移量,每次调用的offset在上一次offset基础上加上limit
int $limit = 50, //查询返回的最大数量,默认为50,最多为200,查询返回的数量可能小于limit指定的值
int $queryType = 0, //查询类型 1:查询用户,返回用户userid列表 2:查询部门,返回部门id列表。 不填该字段或者填0代表同时查询部门跟用户
$fullMatchField = null //如果需要精确匹配用户名称或者部门名称或者英文名,不填则默认为模糊匹配;1:匹配用户名称或者部门名称 2:匹配用户英文名
)
```
================================================
FILE: docs/src/5.x/open-work/server.md
================================================
# 服务端
## 企业微信第三方回调协议
SDK 默认会处理事件 `suite_ticket` ,并会缓存 `suite_ticket`
> 需要注意的是:授权成功、变更授权、取消授权通知时间的响应必须在 1000ms 内完成,以保证用户安装应用的体验。建议在接收到此事件时 立即回应企业微信,之后再做相关业务的处理。
```php
$server = $app->server;
$server->push(function ($message) {
//指令回调
if (isset($message['InfoType'])) {
switch ($message['InfoType']) {
//推送suite_ticket
case 'suite_ticket':
break;
//授权成功通知
case 'create_auth':
break;
//变更授权通知
case 'cancel_auth':
break;
//通讯录事件通知
case 'change_contact':
switch ($message['ChangeType']) {
case 'create_user':
return '新增成员事件';
break;
case 'update_user':
return '更新成员事件';
break;
case 'delete_user':
return '删除成员事件';
break;
case 'create_party':
return '新增部门事件';
break;
case 'update_party':
return '更新部门事件';
break;
case 'delete_party':
return '删除部门事件';
break;
case 'update_tag':
return '标签成员变更事件';
break;
}
break;
default:
return 'fail';
break;
}
}
//数据回调
if(isset($message['MsgType'])){
switch ($message['MsgType']) {
case 'event':
return '事件消息';//详情 https://work.weixin.qq.com/api/doc/90001/90143/90376#%E5%88%A0%E9%99%A4%E6%88%90%E5%91%98%E4%BA%8B%E4%BB%B6
break;
case 'text':
return '文本消息';//详情 https://work.weixin.qq.com/api/doc/90001/90143/90375#%E5%9B%BE%E7%89%87%E6%B6%88%E6%81%AF
break;
case 'image':
return '图片消息';
break;
//等等...不再一一举例
default:
return '其他消息';
break;
}
}
});
$response = $server->serve();
$response->send();
```
================================================
FILE: docs/src/5.x/open-work/service.md
================================================
# 第三方应用接口
## 获取应用suite_access_token
```php
$app->suite_access_token->getToken()
```
## 获取预授权码
```php
$app->corp->getPreAuthCode();
```
## 设置授权配置
```php
$app->corp->setSession(string $preAuthCode, array $sessionInfo);
```
## 获取企业永久授权码
```php
$app->corp->getPermanentByCode(string $preAuthCode); //传入临时授权码
```
## 获取企业授权信息
```php
$app->corp->getAuthorization(string $authCorpId, string $permanentCode); //$authCorpId 授权的企业corp_id $permanentCode 授权的永久授权码
```
## 获取应用的管理员列表
```php
$app->corp->getManagers(string $authCorpId, string $agentId); //$authCorpId 授权的企业corp_id $agentId 授权方安装的应用agentid
```
## 网页授权登录第三方
### 构造第三方oauth2链接
```php
//$redirectUri 回调uri 这里可以覆盖 默认读取配置文件
//$scope 应用授权作用域。
//$state 自定义安全值
$app->corp->getOAuthRedirectUrl(string $redirectUri = '', string $scope = 'snsapi_userinfo', string $state = null);
```
### 第三方根据code获取企业成员信息
```php
$app->corp->getUserByCode(string $code);
```
### 第三方使用user_ticket获取成员详情
```php
$app->corp->getUserByTicket(string $userTicket);
```
================================================
FILE: docs/src/5.x/open-work/work.md
================================================
# 企业
### 获取授权企业的相关信息
```php
$work = $app->work('授权企业的corp_id','授权企业的永久授权码');
```
然后就可以像企业微信一样 获取相关的数据信息
================================================
FILE: docs/src/5.x/overview.md
================================================
# EasyWeChat
EasyWeChat 是一个开源的 [微信](http://www.wechat.com) 非官方 SDK。
EasyWeChat 的安装非常简单,因为它是一个标准的 [Composer](https://getcomposer.org/) 包,这意味着任何满足下列安装条件的 PHP 项目支持 Composer 都可以使用它。
### 环境需求
> - PHP >= 7.4
> - [PHP cURL 扩展](http://php.net/manual/en/book.curl.php)
> - [PHP OpenSSL 扩展](http://php.net/manual/en/book.openssl.php)
> - [PHP SimpleXML 扩展](http://php.net/manual/en/book.simplexml.php)
> - [PHP fileinfo 拓展](http://php.net/manual/en/book.fileinfo.php)
### 加入我们
[EasyWeChat SDK 交流群](http://shang.qq.com/wpa/qunwpa?idkey=b4dcf3ec51a7e8c3c3a746cf450ce59895e5c4ec4fbcb0f80c2cd97c3c6e63e9) ID: 319502940
> 为了避免广告及不看文档用户,加群需要付费,所以请使用 能支持群费的客户端。
> 另外:付费加群不代表我们有责任在群里回答你的问题,所以请认真阅读微信官方文档与 SDK 使用文档再使用,否则提的低级问题不会有人理你
> 不喜勿加,谢谢!
> 除非你发现了明确的 Bug,否则不要在群里 @ 我 :pray:
你有以下两种方式加入到我们中来,为广大开发者提供更优质的免费开源的服务:
> - **贡献代码**:我们的代码都在 [overtrue/wechat](https://github.com/overtrue/wechat) ,你可以提交 PR 到任何一个项目,当然,前提是代码质量必须是 OK 的。
> - **翻译或补充文档**:我们的文档在:[w7corp/EasyWeChat](https://github.com/w7corp/easywechat/tree/master/docs),你可以选择补充文档或者参与英文文档的翻译,目前有 `zh-cn` 与 `en` 两个分支,你可以提交对应的 PR 到目标分支参与翻译工作。
### 开始之前
我们提供了视频教程: 当然,我还是建议你具备以下基础知识,否则可能没有那么快上手。
本 SDK 不是一个全新再造的东西,所以我不会从 0 开始教会你开发微信,你完全有必要在使用本 SDK 前做好以下工作:
> - 具备 PHP 基础知识,不要连闭包是啥都不明白,可以参考我在知乎的回答: [想要开发自己的 PHP 框架需要那些知识储备?](http://www.zhihu.com/question/26635323/answer/33812516)
> - 熟悉 PHP 常见的知识:自动加载、composer 的使用、JSON 处理、Curl 的使用等;
> - **仔细阅读并看懂**[微信官方文档](http://mp.weixin.qq.com/wiki/13/80a1a25adbc46faf2716774c423b3151.html) [微信开放平台文档](https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419318292&token=&lang=zh_CN);
> - 明白微信接口的组成,自有服务器、微信服务器、公众号(还有其它各种号)、测试号、以及通信原理(交互过程);
> - 了解基本的 HTTP 协议,Header 头、请求方式(GET\POST\PUT\PATCH\DELETE)等;
> - 基本的 Debug 技能,查看 php 日志,nginx 日志等。
如果你不具备这些知识,请不要使用,因为用起来会比较痛苦。
另外你有必要看一下以下的链接:
> -
> -
如果你在群里问以下类似的问题,这真的是你没有做好上面的工作:
> - "为啥我的不行啊,请问服务器日志怎么看啊?"
> - "请问这是什么原因啊?[结果/报错截图]"
> - "请问这个 SDK 怎么用啊?"
> - "谁能告诉我这个 SDK 是怎么安装的啊?"
> - "怎么接收用户发的消息啊?"
> - "为啥我的报这个错啊:Class XXXX not found..."
> - ...
我们专门针对一些容易出现的通用问题已经做了汇总: [疑难解答](troubleshooting) ,如果你在问题疑难解答没找到你出现的问题,那么可以在这里提问 [GitHub](https://github.com/overtrue/wechat/issues),提问请描述清楚你用的版本,你的做法是什么,不然别人没法帮你。
> 不要在 QQ 单独找我提问\*\*,除非你是发现了明显的 bug。有问题先审查代码,看文档, 再 google,然后 去群里发个问题,带上你的代码,重现流程,大家有空的会帮忙你解答。谢谢合作!:pray:
### 打赏支持
这是一个开源的项目,我们没有收费服务,你如果觉得你从中获益,简化了你的开发工作,你可以 [打赏](https://github.com/sponsors/overtrue) 来支持我们。
================================================
FILE: docs/src/5.x/payment/bill.md
================================================
# 对账单
## 下载对账单
> 调用参数正确会返回一个 `EasyWeChat\Kernel\Http\StreamResponse` 对象,否则会返回相应错误信息
Example:
```php
$bill = $app->bill->get('20140603'); // type: ALL
// or
$bill = $app->bill->get('20140603', 'SUCCESS'); // type: SUCCESS
// 调用正确,`$bill` 为 csv 格式的内容,保存为文件:
$bill->saveAs('your/path/to', 'file-20140603.csv');
```
第二个参数为账单类型,参考:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_6 中 `bill_type`,默认为 `ALL`
================================================
FILE: docs/src/5.x/payment/contract.md
================================================
# 签约
## 公众号签约
> 参数 `appid`, `version`, `timestamp`, `sign` 可不用传入
```php
$result = $app->contract->web([
'mch_id' => '1200009811',
'plan_id' => '12535',
'contract_code' => '100000',
'contract_display_account' => '微信代扣',
'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action',
]);
```
## APP 签约
```php
$result = $app->contract->app(array $params);
```
## H5 签约
```php
$result = $app->contract->h5(array $params);
```
## 小程序签约
```php
$result = $app->jssdk->contractConfig(array $params);
```
## 申请扣款
```php
$result = $app->contract->apply(array $params);
```
## 申请解约
```php
$result = $app->contract->delete(array $params);
```
================================================
FILE: docs/src/5.x/payment/index.md
================================================
# 支付
你在阅读本文之前确认你已经仔细阅读了:[微信支付 | 商户平台开发文档](https://pay.weixin.qq.com/wiki/doc/api/index.html)。
> 🚨 此版本仅支持微信支付 V2 版接口,V3 版接口请使用 6.x 版本或在支付模块独立使用 [wechatpay/wechatpay](https://packagist.org/packages/wechatpay/wechatpay) 来支持 v2+v3 支付接口。
## 配置
配置在前面的例子中已经提到过了,支付的相关配置如下:
```php
use EasyWeChat\Factory;
$config = [
// 必要配置
'app_id' => 'xxxx',
'mch_id' => 'your-mch-id',
'key' => 'key-for-signature', // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
// 如需使用敏感接口(如退款、发送红包等)需要配置 API 证书路径(登录商户平台下载 API 证书)
'cert_path' => 'path/to/your/cert.pem', // XXX: 绝对路径!!!!
'key_path' => 'path/to/your/key', // XXX: 绝对路径!!!!
'notify_url' => '默认的订单回调地址', // 你也可以在下单时单独设置来想覆盖它
];
$app = Factory::payment($config);
```
### 服务商
#### 设置子商户信息
```php
$app->setSubMerchant('sub-merchant-id', 'sub-app-id'); // 子商户 AppID 为可选项
```
### 刷卡支付
[官方文档](https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=9_10)
```php
$result = $app->pay([
'body' => 'image形象店-深圳腾大- QQ公仔',
'out_trade_no' => '1217752501201407033233368018',
'total_fee' => 888,
'auth_code' => '120061098828009406',
]);
```
## 授权码查询 OPENID 接口
```php
$app->authCodeToOpenid($authCode);
```
## 沙箱模式
微信支付沙箱环境,是提供给微信支付商户的开发者,用于模拟支付及回调通知。以验证商户是否理解回调通知、账单格式,以及是否对异常做了正确的处理。EasyWeChat SDK 对于这一功能进行了封装,开发者只需一步即可在沙箱模式和常规模式间切换,方便开发与最终的部署。
```php
// 在实例化的时候传入配置即可
$app = Factory::payment([
// ...
'sandbox' => true, // 设置为 false 或注释则关闭沙箱模式
]);
// 判断当前是否为沙箱模式:
bool $app->inSandbox();
```
> 特别注意,沙箱模式对于测试用例有严格要求,若使用的用例与规定不符,将导致测试失败。具体用例要求可关注公众号“微信支付商户接入验收助手”(WXPayAssist)查看。
================================================
FILE: docs/src/5.x/payment/jssdk.md
================================================
# JSSDK
JSSDK 模块用于生成调起微信支付以及共享收货地址的调用所需的配置参数。
## 配置
```php
use EasyWeChat\Factory;
$config = [
// 前面的appid什么的也得保留哦
'app_id' => 'xxxx',
'mch_id' => 'your-mch-id',
'key' => 'key-for-signature',
'cert_path' => 'path/to/your/cert.pem', // XXX: 绝对路径!!!!
'key_path' => 'path/to/your/key', // XXX: 绝对路径!!!!
'notify_url' => '默认的订单回调地址', // 你也可以在下单时单独设置来想覆盖它
// 'device_info' => '013467007045764',
// 'sub_app_id' => '',
// 'sub_merchant_id' => '',
// ...
];
$payment = Factory::payment($config);
$jssdk = $payment->jssdk;
```
## 生成支付 JS 配置
有三种发起支付的方式:[WeixinJSBridge](https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6), [JSSDK](https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=15_1), [小程序](https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7)
1. WeixinJSBridge:
```php
$json = $jssdk->bridgeConfig($prepayId); // 返回 json 字符串,如果想返回数组,传第二个参数 false
```
javascript:
```js
...
WeixinJSBridge.invoke(
'getBrandWCPayRequest', = $json ?>,
function(res){
if(res.err_msg == "get_brand_wcpay_request:ok" ) {
// 使用以上方式判断前端返回,微信团队郑重提示:
// res.err_msg将在用户支付成功后返回
// ok,但并不保证它绝对可靠。
}
}
);
...
```
2. JSSDK:
```php
$config = $jssdk->sdkConfig($prepayId); // 返回数组
```
javascript:
```js
wx.chooseWXPay({
timestamp: = $config['timestamp'] ?>,
nonceStr: '= $config['nonceStr'] ?>',
package: '= $config['package'] ?>',
signType: '= $config['signType'] ?>',
paySign: '= $config['paySign'] ?>', // 支付签名
success: function (res) {
// 支付成功后的回调函数
}
});
```
3. 小程序:
```php
$config = $jssdk->bridgeConfig($prepayId, false); // 返回数组
```
javascript:
```js
wx.requestPayment({
timeStamp: = $config['timeStamp'] ?>, //注意 timeStamp 的格式
nonceStr: '= $config['nonceStr'] ?>',
package: '= $config['package'] ?>',
signType: '= $config['signType'] ?>',
paySign: '= $config['paySign'] ?>', // 支付签名
success: function (res) {
// 支付成功后的回调函数
}
});
```
## 生成共享收货地址 JS 配置
1. 发起 OAuth 授权,获取用户 `$accessToken`,参考网页授权章节。
2. 使用 `$accessToken` 获取配置
```php
$configForPickAddress = $jssdk->shareAddressConfig($token);
// 拿着这个生成好的配置 $configForPickAddress 去订单页(或者直接显示订单页)写 js 调用了
// ...
```
## 生成 APP 支付配置
```php
$config = $jssdk->appConfig($prepayId);
```
`$config` 为数组格式,你可以用 API 返回给客户端
# 二维码生成工具推荐
你也许需要生成二维码,那么以下这些供参考:
> - https://github.com/endroid/QrCode
> - https://github.com/Bacon/BaconQrCode
> - https://github.com/SimpleSoftwareIO/simple-qrcode (Bacon/BaconQrCode 的 Laravel 版本)
> - https://github.com/aferrandini/PHPQRCode
================================================
FILE: docs/src/5.x/payment/micropay.md
================================================
# 付款码支付
## 配置
> 请务必先熟悉流程:
```php
$result = $app->pay([
'body' => 'image形象店-深圳腾大- QQ公仔',
'out_trade_no' => '20150806125346',
'total_fee' => 88,
'spbill_create_ip' => '123.12.12.123', // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址
'auth_code' => '120061098828009406', // 扫码支付付款码,设备读取用户微信中的条码或者二维码信息
]);
```
#### 支付结果
付款码支付方式没有回调通知,支付结果直接返回,请参考:[微信付款码支付文档](https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=5_1) 更新您的订单状态。
================================================
FILE: docs/src/5.x/payment/notify.md
================================================
# 通知
## 支付结果通知
在用户成功支付后,微信服务器会向该 **订单中设置的回调 URL** 发起一个 POST 请求,请求的内容为一个 XML。里面包含了所有的详细信息,具体请参考:[支付结果通知](https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7)
而对于用户的退款操作,在退款成功之后也会有一个异步回调通知。
本 SDK 内预置了相关方法,以方便开发者处理这些通知,具体用法如下:
只需要在控制器中使用 `handlePaidNotify()` 方法,在其中对自己的业务进行处理并向微信服务器发送一个响应。
```php
$response = $app->handlePaidNotify(function ($message, $fail) {
// 你的逻辑
return true;
// 或者错误消息
$fail('Order not exists.');
});
$response->send(); // Laravel 里请使用:return $response;
```
这里需要注意的有几个点:
0. 退款结果通知和扫码支付通知的使用方法均类似。
1. `handlePaidNotify` 只接收一个 [`Closure`](http://php.net/manual/zh/class.closure.php) 匿名函数。
2. 该匿名函数接收两个参数,这两个参数分别为:
> - `$message` 为微信推送过来的通知信息,为一个数组;
> - `$fail` 为一个函数,触发该函数可向微信服务器返回对应的错误信息,**微信会稍后重试再通知**。
3. 该函数返回值就是告诉微信 **“我是否处理完成”**。如果你触发 `$fail` 函数,那么微信会在稍后再次继续通知你,直到你明确的告诉它:“我已经处理完成了”,**只有**在函数里 `return true;` 才代表处理完成。
4. `handlePaidNotify` 返回值 `$response` 是一个 Response 对象,如果你要直接输出,使用 `$response->send()`, 在一些框架里(如 Laravel)不是输出而是返回:`return $response`。
通常我们的处理逻辑大概是下面这样(**以下只是伪代码**):
```php
$response = $app->handlePaidNotify(function($message, $fail){
// 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
$order = 查询订单($message['out_trade_no']);
if (!$order || $order->paid_at) { // 如果订单不存在 或者 订单已经支付过了
return true; // 告诉微信,我已经处理完了,订单没找到,别再通知我了
}
///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况,确认是已经支付 /////////////
if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态,不代表支付状态
// 用户是否支付成功
if (array_get($message, 'result_code') === 'SUCCESS') {
$order->paid_at = time(); // 更新支付时间为当前时间
$order->status = 'paid';
// 用户支付失败
} elseif (array_get($message, 'result_code') === 'FAIL') {
$order->status = 'paid_fail';
}
} else {
return $fail('通信失败,请稍后再通知我');
}
$order->save(); // 保存订单
return true; // 返回处理完成
});
$response->send(); // return $response;
```
> 注意:请把 “支付成功与否” 与 “是否处理完成” 分开,它俩没有必然关系。
> 比如:微信通知你用户支付完成,但是支付失败了(result_code 为 'FAIL'),你应该**更新你的订单为支付失败**,但是要**告诉微信处理完成**。
## 退款结果通知
使用示例:
```php
$response = $app->handleRefundedNotify(function ($message, $reqInfo, $fail) {
// 其中 $message['req_info'] 获取到的是加密信息
// $reqInfo 为 message['req_info'] 解密后的信息
// 你的业务逻辑...
return true; // 返回 true 告诉微信“我已处理完成”
// 或返回错误原因 $fail('参数格式校验错误');
});
$response->send();
```
## 扫码支付通知
扫码支付【模式一】:https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=6_4
```php
// 扫码支付通知接收第三个参数 `$alert`,如果触发该函数,会返回“业务错误”到微信服务器,触发 `$fail` 则返回“通信错误”
$response = $app->handleScannedNotify(function ($message, $fail, $alert) use ($app) {
// 如:$alert('商品已售空');
// 如业务流程正常,则要调用“统一下单”接口,并返回 prepay_id 字符串,代码如下
$result = $app->order->unify([
'trade_type' => 'NATIVE',
'product_id' => $message['product_id'],
// ...
]);
return $result['prepay_id'];
});
$response->send();
```
================================================
FILE: docs/src/5.x/payment/order.md
================================================
# 订单
## 统一下单
没错,什么 H5 支付,公众号支付,扫码支付,支付中签约,全部都是用这个接口下单。
> 参数 `appid`, `mch_id`, `nonce_str`, `sign`, `sign_type` 可不用传入
> 服务商模式下, 需使用 `sub_openid`, 并传入`sub_mch_id` 和`sub_appid`
```php
$result = $app->order->unify([
'body' => '腾讯充值中心-QQ会员充值',
'out_trade_no' => '20150806125346',
'total_fee' => 88,
'spbill_create_ip' => '123.12.12.123', // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址
'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
'openid' => 'oUpF8uMuAJO_M2pxb1Q9zNjWeS6o',
]);
// $result:
//{
// "return_code": "SUCCESS",
// "return_msg": "OK",
// "appid": "wx2421b1c4390ec4sb",
// "mch_id": "10000100",
// "nonce_str": "IITRi8Iabbblz1J",
// "openid": "oUpF8uMuAJO_M2pxb1Q9zNjWeSs6o",
// "sign": "7921E432F65EB8ED0CE9755F0E86D72F2",
// "result_code": "SUCCESS",
// "prepay_id": "wx201411102639507cbf6ffd8b0779950874",
// "trade_type": "JSAPI"
//}
```
**第二个参数**为是否[支付中签约](https://pay.weixin.qq.com/wiki/doc/api/pap.php?chapter=18_13&index=5),默认 `false`
> 支付中签约相关参数 `contract_mchid`, `contract_appid`, `request_serial` 可不用传入
```php
$isContract = true;
$result = $app->order->unify([
'body' => '腾讯充值中心-QQ会员充值',
'out_trade_no' => '20150806125346',
'total_fee' => 88,
'spbill_create_ip' => '123.12.12.123', // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址
'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
'openid' => 'oUpF8uMuAJO_M2pxb1Q9zNjWeS6o',
'plan_id' => 123,// 协议模板id
'contract_code' => 100001256,// 签约协议号
'contract_display_account' => '腾讯充值中心',// 签约用户的名称
'contract_notify_url' => 'http://easywechat.com/contract_notify'
], $isContract);
//$result:
//{
// "return_code": "SUCCESS",
// "return_msg": "OK",
// "appid": "wx123456",
// "mch_id": "10000100",
// "nonce_str": "CfOcMkDFblzulYvI",
// "sign": "B53F4AFEE7FA6AD5739581486A5CB9C9",
// "result_code": "SUCCESS",
// "prepay_id": "wx08175759731015754a5c13791522969400",
// "trade_type": "JSAPI",
// "plan_id": "123",
// "request_serial": "1565258279",
// "contract_code": "100001256",
// "contract_display_account": "腾讯充值中心",
// "out_trade_no": "201908088195558331565258279",
// "contract_result_code": "SUCCESS"
//}
```
## 查询订单
该接口提供所有微信支付订单的查询,商户可以通过该接口主动查询订单状态,完成下一步的业务逻辑。
需要调用查询接口的情况:
> - 当商户后台、网络、服务器等出现异常,商户系统最终未接收到支付通知;
> - 调用支付接口后,返回系统错误或未知交易状态情况;
> - 调用被扫支付 API,返回 USERPAYING 的状态;
> - 调用关单或撤销接口 API 之前,需确认支付状态;
### 根据商户订单号查询
```php
$app->order->queryByOutTradeNumber("商户系统内部的订单号(out_trade_no)");
```
### 根据微信订单号查询
```php
$app->order->queryByTransactionId("微信订单号(transaction_id)");
```
## 关闭订单
> 注意:订单生成后不能马上调用关单接口,最短调用时间间隔为 5 分钟。
```php
$app->order->close(商户系统内部的订单号(out_trade_no));
```
================================================
FILE: docs/src/5.x/payment/profit-sharing.md
================================================
# 分账
> 官方文档 https://pay.weixin.qq.com/wiki/doc/api/allocation.php?chapter=27_1&index=1
```php
use EasyWeChat\Factory;
$config = [
'app_id' => '***',
"secret" => "***",
'mch_id' => '***',
'key' => '***',
'cert_path' => 'cert.pem',
'key_path' => 'key.pem',
'notify_url' => 'http://***.com/notify.php',
];
$payment = Factory::payment($config);
```
### 添加接收方
> 商户发起添加分账接收方请求,后续可通过发起分账请求将结算后的钱分到该分账接收方。
```php
$receiver = [
"type" => "PERSONAL_OPENID",
"account" => "…………",//PERSONAL_OPENID:个人openid
"name" => "张三",//接收方真实姓名
"relation_type" => "PARTNER"
];
$payment->profit_sharing->addReceiver($receiver);
$receiver = [
"type" => "MERCHANT_ID",
"account" => "132456798",//MERCHANT_ID:商户ID
"name" => "商户全称",//商户全称
"relation_type" => "PARTNER"
];
$payment->profit_sharing->addReceiver($receiver);
```
### 删除接收方
```php
$payment->profit_sharing->deleteReceiver($receiver);
```
### 单次分账
```php
$transaction_id = "***";
$out_trade_no = "***";
$receivers = [
[
"type" => "PERSONAL_OPENID",
"account" => "***",
"amount" => 2,
"description" => "分到个人"
],
[
"type" => "MERCHANT_ID",
"account" => "***",
"amount" => 1,
"description" => "分到商户"
]
];
$sharing = $payment->profit_sharing->share($transaction_id,$out_trade_no,$receivers);
```
### 多次分账
```php
$payment->profit_sharing->multiShare($transaction_id,$out_trade_no,$receivers);
```
### 多次分账完结
```php
$params = [
"transaction_id" => "",
"out_order_no" => "",
"description" => ""
];
$payment->profit_sharing->markOrderAsFinished($params);
```
### 分账查询
```php
$res = $payment->profit_sharing->query($transaction_id,$out_trade_no);
```
> 查询结果
```
Array
(
[return_code] => SUCCESS
[result_code] => SUCCESS
[mch_id] => ***
[nonce_str] => 38e92cbe2790642f
[sign] => 8904B6440C58785540950F2911500F55C9A94CAC75790B0721B9AA470E6BF9A8
[transaction_id] => 4200000589202007249764665257
[out_order_no] => 202007241544057945
[order_id] => 30000103702020072402011591464
[status] => FINISHED
[receivers] => [{"type":"MERCHANT_ID","account":"***","amount":7,"description":"解冻给分账方","result":"SUCCESS","finish_time":"20200724172033"},{"type":"PERSONAL_OPENID","account":"***","amount":2,"description":"分到个人1","result":"SUCCESS","finish_time":"20200724172033"},{"type":"PERSONAL_OPENID","account":"***-g4","amount":1,"description":"分到郭","result":"SUCCESS","finish_time":"20200724172034"}]
)
```
### 分账退回
```php
$out_trade_no = "***";//退款订单号
$out_return_no = "***";//系统内部退款单号
$return_amount = 1;
$return_account = "***-g4";
$description = "订单取消";
$payment->profit_sharing->returnShare($out_trade_no,$out_return_no,$return_amount,$return_account,$description);
```
================================================
FILE: docs/src/5.x/payment/redpack.md
================================================
# 红包
在阅读本文之前确认你已经仔细阅读了:[微信支付 | 现金红包文档 ](https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=13_1)。
## 配置
与支付接口一样,红包接口也需要配置如下参数,需要特别注意的是,红包相关的全部接口**都需要使用 SSL 证书**,因此**cert_path 以及 cert_key 必须正确配置**。
```php
use EasyWeChat\Factory;
$config = [
'app_id' => 'you-app-id',
'mch_id' => 'your-mch-id',
'key' => 'key-for-signature',
'cert_path' => 'path/to/your/cert.pem',
'key_path' => 'path/to/your/key',
// ...
];
$payment = Factory::payment($config);
$redpack = $payment->redpack;
```
**服务商模式下需注意**
```php
// 不能传递第二个参数subAppID,否则微信将一直返回签名错误
$payment->setSubMerchant($subMerchantID);
```
## 发送红包
微信的现金红包分为**普通红包**和**裂变红包**两类。SDK 中对其分别进行了封装,同时也提供了一个统一的调用方法。
**默认情况下,通过接口发送的红包金额应该在200元以内,但可以通过在调用发送接口时传递场景 ID (scene_id)来发送特定场景的红包,不同场景红包可以由商户自己登录商户平台设置最大金额。scene_id 的可选值及对应含义可参阅微信支付官方文档。**
### 发送普通红包接口
```php
$redpackData = [
'mch_billno' => 'xy123456',
'send_name' => '测试红包',
're_openid' => 'oxTWIuGaIt6gTKsQRLau2M0yL16E',
'total_num' => 1, //固定为1,可不传
'total_amount' => 100, //单位为分,不小于100
'wishing' => '祝福语',
'client_ip' => '192.168.0.1', //可不传,不传则由 SDK 取当前客户端 IP
'act_name' => '测试活动',
'remark' => '测试备注',
// ...
];
$result = $redpack->sendNormal($redpackData);
```
### 发送裂变红包接口
```php
$redpackData = [
'mch_billno' => 'xy123456',
'send_name' => '测试红包',
're_openid' => 'oxTWIuGaIt6gTKsQRLau2M0yL16E',
'total_num' => 3, //不小于3
'total_amount' => 300, //单位为分,不小于300
'wishing' => '祝福语',
'act_name' => '测试活动',
'remark' => '测试备注',
'amt_type' => 'ALL_RAND', //可不传
// ...
];
$result = $redpack->sendGroup($redpackData);
```
### 发送小程序红包接口
```php
$redpackData = [
'mch_billno' => 'xy123456',
'send_name' => '测试红包',
're_openid' => 'oxTWIuGaIt6gTKsQRLau2M0yL16E',
'total_amount' => 100, //单位为分,不小于100
'wishing' => '祝福语',
'client_ip' => '192.168.0.1', //可不传,不传则由 SDK 取当前客户端 IP
'act_name' => '测试活动',
'remark' => '测试备注',
// ...
];
$result = $redpack->sendMiniprogramNormal($redpackData);
```
## 红包预下单接口
红包预下单接口是为摇一摇红包接口配合使用的,在开发摇一摇周边的摇红包相关功能时,需要调用本接口获取红包单号。详情参见[官方文档](http://mp.weixin.qq.com/wiki/7/0ddd50ed2421b99fedd071281c074aab.html#.E7.BA.A2.E5.8C.85.E9.A2.84.E4.B8.8B.E5.8D.95.E6.8E.A5.E5.8F.A3)
```php
$redpackData = [
'hb_type' => 'NORMAL', //NORMAL 或 GROUP
'mch_billno' => 'xy123456',
'send_name' => '测试红包',
're_openid' => 'oxTWIuGaIt6gTKsQRLau2M0yL16E',
'total_num' => 1, //普通红包固定为1,裂变红包不小于3
'total_amount' => 100, //单位为分,普通红包不小于100,裂变红包不小于300
'wishing' => '祝福语',
'client_ip' => '192.168.0.1', //可不传,不传则由 SDK 取当前客户端 IP
'act_name' => '测试活动',
'remark' => '测试备注',
'amt_type' => 'ALL_RAND',
// ...
];
$result = $redpack->prepare($redpackData);
```
## 查询红包信息
用于商户对已发放的红包进行查询红包的具体信息以及领取情况 ,普通红包和裂变包均使用这一接口进行查询。
```php
$mchBillNo = "商户系统内部的订单号(mch_billno)";
$redpack->info($mchBillNo);
```
================================================
FILE: docs/src/5.x/payment/refund.md
================================================
# 退款
## 申请退款
当交易发生之后一段时间内,由于买家或者卖家的原因需要退款时,卖家可以通过退款接口将支付款退还给买家,微信支付将在收到退款请求并且验证成功之后,按照退款规则将支付款按原路退到买家帐号上。
注意:
> 1、交易时间超过一年的订单无法提交退款;
> 2、微信支付退款支持单笔交易分多次退款,多次退款需要提交原支付订单的商户订单号和设置不同的退款单号。一笔退款失败后重新提交,要采用原来的退款单号。总退款金额不能超过用户实际支付金额。
参考:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4
### 根据微信订单号退款
```php
// 参数分别为:微信订单号、商户退款单号、订单金额、退款金额、其他参数
$app->refund->byTransactionId(string $transactionId, string $refundNumber, int $totalFee, int $refundFee, array $config = []);
// Example:
$result = $app->refund->byTransactionId('transaction-id-xxx', 'refund-no-xxx', 10000, 10000, [
// 可在此处传入其他参数,详细参数见微信支付文档
'refund_desc' => '商品已售完',
]);
```
### 根据商户订单号退款
```php
// 参数分别为:商户订单号、商户退款单号、订单金额、退款金额、其他参数
$app->refund->byOutTradeNumber(string $number, string $refundNumber, int $totalFee, int $refundFee, array $config = []);
// Example:
$result = $app->refund->byOutTradeNumber('out-trade-no-xxx', 'refund-no-xxx', 20000, 1000, [
// 可在此处传入其他参数,详细参数见微信支付文档
'refund_desc' => '退运费',
]);
```
> $refundNumber 为商户退款单号,自己生成用于自己识别即可。
## 查询退款
提交退款申请后,通过调用该接口查询退款状态。退款有一定延时,用零钱支付的退款20分钟内到账,银行卡支付的退款3个工作日后重新查询退款状态。
可通过 4 种不同类型的单号查询:
> - 微信订单号 => `queryByTransactionId($transactionId)`
> - 商户订单号 => `queryByOutTradeNumber($outTradeNumber)`
> - 商户退款单号 => `queryByOutRefundNumber($outRefundNumber)`
> - 微信退款单号 => `queryByRefundId($refundId)`
================================================
FILE: docs/src/5.x/payment/reverse.md
================================================
# 撤销订单
目前只有 **刷卡支付** 有此功能。
> 调用支付接口后请勿立即调用撤销订单API,建议支付后至少15s后再调用撤销订单接口。
## 通过内部订单号撤销订单
```php
$app->reverse->byOutTradeNumber("商户系统内部的订单号(out_trade_no)");
```
## 通过微信订单号撤销订单
```php
$app->reverse->byTransactionId("微信的订单号(transaction_id)");
```
================================================
FILE: docs/src/5.x/payment/scan-pay.md
================================================
## 扫码支付
### 模式一:先生成产品二维码,扫码下单后支付
> 请务必先熟悉流程:
#### 生成产品二维码内容
```php
$content = $app->scheme($productId); // $productId 为你的产品/商品ID,用于回调时带回,自己识别即可
//结果示例:weixin://wxpay/bizpayurl?sign=XXXXX&appid=XXXXX&mch_id=XXXXX&product_id=XXXXXX&time_stamp=XXXXXX&nonce_str=XXXXX
```
将 `$content` 生成二维码,SDK 并不内置二维码生成库,使用你熟悉的工具创建二维码即可,比如 PHP 部分有以下工具可以选择:
> -
> -
> -
#### 处理回调
当用户扫码时,你的回调接口会收到一个通知,调用[统一下单接口](https://easywechat.com/5.x/payment/order)创建订单后返回 `prepay_id`,你可以使用下面的代码处理扫码通知:
```php
// 扫码支付通知接收第三个参数 `$alert`,如果触发该函数,会返回“业务错误”到微信服务器,触发 `$fail` 则返回“通信错误”
$response = $app->handleScannedNotify(function ($message, $fail, $alert) use ($app) {
// 如:$alert('商品已售空');
// 如业务流程正常,则要调用“统一下单”接口,并返回 prepay_id 字符串,代码如下
$result = $app->order->unify([
'trade_type' => 'NATIVE',
'product_id' => $message['product_id'], // $message['product_id'] 则为生成二维码时的产品 ID
// ...
]);
return $result['prepay_id'];
});
$response->send();
```
用户在手机上付完钱以后,你会再收到**付款结果通知**,这时候请参考:[处理微信支付通知](https://easywechat.com/5.x/payment/notify) 更新您的订单状态。
### 模式二:先下单,生成订单后创建二维码
> :
#### 根据用户选购的商品生成订单
调用[统一下单接口](https://easywechat.com/5.x/payment/order)创建订单:
```php
$result = $app->order->unify([
'trade_type' => 'NATIVE',
'product_id' => $message['product_id'], // $message['product_id'] 则为生成二维码时的产品 ID
// ...
]);
```
#### 生成二维码
> 版本 4.1.7+ 支持
从上一步得到的 `$result['code_url']` 得到二维码内容:
将 `$result['code_url']` 生成二维码图片向用户展示即可扫码,生成工具上面自己找一下即可。 SDK 不内置
#### 支付通知
这种方式的通知就只有**付款结果通知**了,这时候请参考:[处理微信支付通知](https://easywechat.com/5.x/payment/notify) 更新您的订单状态。
================================================
FILE: docs/src/5.x/payment/security.md
================================================
# 安全与风控
> EasyWeChat 4.0.7+
## 获取 RSA 公钥
```php
$result = $app->security->getPublicKey();
// 存成文件
file_put_contents('./public.pem', $result);
```
将会得到 PKCS#1 格式密钥:
```
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEArT82k67xybiJS9AD8nNAeuDYdrtCRaxkS6cgs8L9h83eqlDTlrdw
zBVSv5V4imTq/URbXn4K0V/KJ1TwDrqOI8hamGB0fvU13WW1NcJuv41RnJVua0QA
lS3tS1JzOZpMS9BEGeFvyFF/epbi/m9+2kUWG94FccArNnBtBqqvFncXgQsm98JB
3a62NbS1ePP/hMI7Kkz+JNMyYsWkrOUFDCXAbSZkWBJekY4nGZtK1erqGRve8Jbx
TWirAm/s08rUrjOuZFA21/EI2nea3DidJMTVnXVPY2qcAjF+595shwUKyTjKB8v1
REPB3hPF1Z75O6LwuLfyPiCrCTmVoyfqjwIDAQAB
-----END RSA PUBLIC KEY-----
```
使用 OpenSSL 转换 PKCS#1 为 PKCS#8 格式密钥:
```shell
openssl rsa -RSAPublicKey_in -in public.pem -out public.pem
```
PKCS#8 格式密钥:
```
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArT82k67xybiJS9AD8nNA
euDYdrtCRaxkS6cgs8L9h83eqlDTlrdwzBVSv5V4imTq/URbXn4K0V/KJ1TwDrqO
I8hamGB0fvU13WW1NcJuv41RnJVua0QAlS3tS1JzOZpMS9BEGeFvyFF/epbi/m9+
lkUWG94FccArNnBtBqqvFncXgQsm98JB3a42NbS1ePP/hMI7Kkz+JNMyYsWkrOUF
DCXAbSZkWBJekY4nGZtK1erqGRve8JbxTWirAm/s08rUrjOuZFA21/EI2nea3Did
JMTVnXVPY2qcAjF+595shwUKyTjKB8v1REPB3hPF1Z75O6LwuLfyPiCrCTmVoyfq
jwIDAQAB
-----END PUBLIC KEY-----
```
================================================
FILE: docs/src/5.x/payment/transfer.md
================================================
# 企业付款
> EasyWeChat 4.0.7+
该模块需要用到双向证书,请参考:https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=4_3
## 企业付款到用户零钱
```php
$app->transfer->toBalance([
'partner_trade_no' => '1233455', // 商户订单号,需保持唯一性(只能是字母或者数字,不能包含有符号)
'openid' => 'oxTWIuGaIt6gTKsQRLau2M0yL16E',
'check_name' => 'FORCE_CHECK', // NO_CHECK:不校验真实姓名, FORCE_CHECK:强校验真实姓名
're_user_name' => '王小帅', // 如果 check_name 设置为FORCE_CHECK,则必填用户真实姓名
'amount' => 10000, // 企业付款金额,单位为分
'desc' => '理赔', // 企业付款操作说明信息。必填
]);
```
## 查询付款到零钱的订单
```php
$partnerTradeNo = 1233455;
$app->transfer->queryBalanceOrder($partnerTradeNo);
```
## 企业付款到银行卡
企业付款到银行卡需要对银行卡号与姓名进行 RSA 加密,所以这里需要先下载 RSA 公钥到本地(服务器),我们提供了一个命令行工具:[EasyWeChat/console](https://github.com/EasyWeChat/console),请使用 composer 安装完成。
```bash
$ composer require easywechat/console -vvv
```
然后,在项目根目录执行以下命令下载公钥:
```bash
$ ./vendor/bin/easywechat payment:rsa_public_key \
> --mch_id=14339221228 \
> --api_key=36YTbDmLgyQ52noqdxgwGiYy \
> --cert_path=/Users/overtrue/www/demo/apiclient_cert.pem \
> --key_path=/Users/overtrue/www/demo/apiclient_key.pem
```
将会在当前目录生成一个 `./public-14339221228.pem` 文件,你可以将它移动到敏感目录,然后在支付配置文件中加如以下选项:
```php
use EasyWeChat\Factory;
$config = [
// 必要配置
'app_id' => 'xxxx',
'mch_id' => 'your-mch-id',
'key' => 'key-for-signature', // API 密钥
// 如需使用敏感接口(如退款、发送红包等)需要配置 API 证书路径(登录商户平台下载 API 证书)
'cert_path' => '/path/to/your/cert.pem', // XXX: 绝对路径!!!!
'key_path' => '/path/to/your/key', // XXX: 绝对路径!!!!
// 将上面得到的公钥存放路径填写在这里
'rsa_public_key_path' => '/path/to/your/rsa/publick/key/public-14339221228.pem', // <<<------------------------
'notify_url' => '默认的订单回调地址', // 你也可以在下单时单独设置来想覆盖它
];
$app = Factory::payment($config);
```
```php
$result = $app->transfer->toBankCard([
'partner_trade_no' => '1229222022',
'enc_bank_no' => '6214830901234564', // 银行卡号
'enc_true_name' => '安正超', // 银行卡对应的用户真实姓名
'bank_code' => '1001', // 银行编号
'amount' => 100, // 单位:分
'desc' => '测试',
]);
```
## 查询付款到银行卡的订单
```php
$partnerTradeNo = 1233455;
$app->transfer->queryBankCardOrder($partnerTradeNo);
```
================================================
FILE: docs/src/5.x/sidebar.js
================================================
exports = module.exports = [
{
text: '开始使用',
collapsible: true,
items: [
{ text: '概述', link: '/5.x/overview.html' },
{ text: '安装', link: '/5.x/installation.html' },
{ text: '在框架中使用', link: '/5.x/integration.html' },
{ text: '常见问题汇总', link: '/5.x/troubleshooting.html' }
]
},
{
text: '公众号',
collapsible: true,
items: [
{ text: '入门', link: '/5.x/official-account/index.html' },
{
text: '快速开始',
link: '/5.x/official-account/tutorial.html'
},
{
text: '配置',
link: '/5.x/official-account/configuration.html'
},
{ text: '基础接口', link: '/5.x/official-account/base.html' },
{ text: '服务端', link: '/5.x/official-account/server.html' },
{ text: '消息', link: '/5.x/official-account/messages.html' },
{
text: '多客服消息转发',
link: '/5.x/official-account/message-transfer'
},
{
text: '消息群发',
link: '/5.x/official-account/broadcasting.html'
},
{
text: '模板消息',
link: '/5.x/official-account/template_message.html'
},
{ text: '用户', link: '/5.x/official-account/user.html' },
{
text: '用户标签',
link: '/5.x/official-account/user-tag.html'
},
{ text: '网页授权', link: '/5.x/official-account/oauth.html' },
{ text: 'JSSDK', link: '/5.x/basic-services/jssdk.html' },
{ text: '临时素材', link: '/5.x/basic-services/media.html' },
{ text: '二维码', link: '/5.x/basic-services/qrcode.html' },
{ text: '短网址', link: '/5.x/basic-services/url.html' },
{
text: '素材管理',
link: '/5.x/official-account/material.html'
},
{ text: '草稿箱',
link: '/5.x/official-account/draft.html'
},
{ text: '菜单', link: '/5.x/official-account/menu.html' },
{ text: '卡券', link: '/5.x/official-account/card.html' },
{ text: '门店', link: '/5.x/official-account/poi.html' },
{
text: '客服',
link: '/5.x/official-account/customer_service.html'
},
{
text: '摇一摇周边',
link: '/5.x/official-account/shake-around.html'
},
{
text: '数据统计与分析',
link: '/5.x/official-account/data_cube.html'
},
{
text: '语义理解',
link: '/5.x/official-account/semantic.html'
},
{ text: '自动回复', link: '/5.x/official-account/reply.html' },
{
text: '评论数据管理',
link: '/5.x/official-account/comment.html'
},
{ text: '返佣商品', link: '/5.x/official-account/goods.html' }
]
},
{
text: '微信支付',
collapsible: true,
items: [
{ text: '入门', link: '/5.x/payment/index.html' },
{ text: '订单', link: '/5.x/payment/order.html' },
{ text: '退款', link: '/5.x/payment/refund.html' },
{ text: '账单', link: '/5.x/payment/bill.html' },
{ text: '通知', link: '/5.x/payment/notify.html' },
{ text: '红包', link: '/5.x/payment/redpack.html' },
{ text: '付款码支付', link: '/5.x/payment/micropay.html' },
{ text: '扫码支付', link: '/5.x/payment/scan-pay.html' },
{ text: 'JSSDK', link: '/5.x/payment/jssdk.html' },
{ text: '企业付款', link: '/5.x/payment/transfer.html' },
{ text: '撤销订单', link: '/5.x/payment/reverse.html' },
{ text: '安全工具', link: '/5.x/payment/security.html' },
{ text: '分账', link: '/5.x/payment/profit-sharing.html' }
]
},
{
text: '小程序',
collapsible: true,
items: [
{ text: '入门', link: '/5.x/mini-program/index.html' },
{ text: '小程序码', link: '/5.x/mini-program/app_code.html' },
{
text: '客服消息',
link: '/5.x/mini-program/customer_service.html'
},
{
text: '数据统计与分析',
link: '/5.x/mini-program/data_cube.html'
},
{ text: '微信登录', link: '/5.x/mini-program/auth.html' },
{
text: '模板消息',
link: '/5.x/mini-program/template_message.html'
},
{ text: '消息解密', link: '/5.x/mini-program/decrypt.html' },
{
text: '内容安全',
link: '/5.x/basic-services/content_security.html'
},
{ text: '物流助手', link: '/5.x/mini-program/express.html' },
{ text: '生物认证', link: '/5.x/mini-program/soter.html' },
{ text: '插件管理', link: '/5.x/mini-program/plugin.html' },
{
text: '附近的小程序',
link: '/5.x/mini-program/nearby_poi.html'
},
{
text: '订阅消息',
link: '/5.x/mini-program/subscribe_message.html'
},
{ text: '直播', link: '/5.x/mini-program/live.html' },
{
text: '安全风控',
link: '/5.x/mini-program/safety_control.html'
},
{
text: 'URL Scheme',
link: '/5.x/mini-program/url_scheme.html'
},
{ text: 'URL Link', link: '/5.x/mini-program/url_link.html' },
{
text: 'Short Link',
link: '/5.x/mini-program/short_link.html'
},
{ text: '手机号', link: '/5.x/mini-program/phone_number.html' },
{
text: '小程序发货信息管理服务',
link: '/5.x/mini-program/shipping.html'
},
{ text: '商户功能', link: '/5.x/mini-program/business.html' },
{ text: 'OCR 文字识别', link: '/5.x/mini-program/ocr.html' },
{ text: '微信小商店', link: '/5.x/mini-program/mall.html' },
{ text: '实时日志', link: '/5.x/mini-program/realtime_log.html' },
{ text: '风险控制', link: '/5.x/mini-program/risk_control.html' },
{ text: '联盟推广', link: '/5.x/mini-program/union.html' },
{ text: '动态消息', link: '/5.x/mini-program/activity_message.html' },
{ text: '搜索功能', link: '/5.x/mini-program/search.html' }
]
},
{
text: '开放平台',
collapsible: true,
items: [
{ text: '入门', link: '/5.x/open-platform/index.html' },
{ text: '服务端', link: '/5.x/open-platform/server.html' },
{
text: '代授权',
link: '/5.x/open-platform/authorizer-delegate.html'
}
]
},
{
text: '企业微信',
collapsible: true,
items: [
{ text: '入门', link: '/5.x/wework/index.html' },
{ text: '服务端', link: '/5.x/wework/server.html' },
{ text: '应用管理', link: '/5.x/wework/agents.html' },
{ text: '消息发送', link: '/5.x/wework/message.html' },
{ text: '通讯录', link: '/5.x/wework/contacts.html' },
{ text: '网页授权', link: '/5.x/wework/oauth.html' },
{ text: '客户联系', link: '/5.x/wework/external-contact.html' },
{ text: '产品图册', link: '/5.x/wework/product.html' },
{ text: '聊天敏感词', link: '/5.x/wework/intercept.html' },
{ text: '微信客服', link: '/5.x/wework/kf.html' },
{ text: '自定义菜单', link: '/5.x/wework/menu.html' },
{ text: '素材管理', link: '/5.x/wework/media.html' },
{ text: 'OA', link: '/5.x/wework/oa.html' },
{ text: '企业互联', link: '/5.x/wework/corp-group.html' },
{ text: '会话内容存档', link: '/5.x/wework/msg-audit.html' },
{ text: '电子发票', link: '/5.x/wework/invoice.html' },
{ text: '小程序', link: '/5.x/wework/mini-program.html' },
{ text: 'JSSDK', link: '/5.x/wework/jssdk.html' },
{ text: '群机器人', link: '/5.x/wework/group-robot.html' },
{ text: '移动端', link: '/5.x/wework/mobile.html' },
{ text: '企微帐号ID转换', link: '/5.x/wework/to-account.html' },
{ text: '日程', link: '/5.x/wework/calendar.html' },
{ text: '微盘', link: '/5.x/wework/wedrive.html' },
{ text: '群聊管理', link: '/5.x/wework/chat.html' },
{ text: '入群欢迎语', link: '/5.x/wework/group-welcome-template.html' }
]
},
{
text: '企业微信开放平台',
collapsible: true,
items: [
{ text: '入门', link: '/5.x/open-work/index.html' },
{ text: '服务商接口', link: '/5.x/open-work/provider.html' },
{ text: '服务商', link: '/5.x/open-work/server.html' },
{ text: '第三方应用接口', link: '/5.x/open-work/service.html' },
{ text: '企业相关', link: '/5.x/open-work/work.html' }
]
},
{
text: '小微商户',
collapsible: true,
items: [
{ text: '入门', link: '/5.x/micro-merchant/index.html' },
{
text: '获取平台证书',
link: '/5.x/micro-merchant/certficates.html'
},
{ text: '图片上传', link: '/5.x/micro-merchant/media.html' },
{
text: '商户入驻',
link: '/5.x/micro-merchant/submit-application.html'
},
{ text: '商户升级', link: '/5.x/micro-merchant/upgrade.html' },
{
text: '商户信息修改',
link: '/5.x/micro-merchant/material.html'
},
{ text: '提现相关', link: '/5.x/micro-merchant/withdraw.html' },
{
text: '商户配置',
link: '/5.x/micro-merchant/merchant-config.html'
}
]
},
{
text: '自定义',
collapsible: true,
items: [
{
text: 'Access Token',
link: '/5.x/customize/access_token.html'
},
{ text: '缓存', link: '/5.x/customize/cache.html' },
{ text: '模块替换', link: '/5.x/customize/replace-service.html' }
]
},
{
text: '其他',
collapsible: true,
items: [
{ text: '常见问题', link: '/5.x/troubleshooting.html' },
{ text: '参与贡献', link: '/5.x/contributing.html' }
]
}
]
================================================
FILE: docs/src/5.x/troubleshooting.md
================================================
# 疑难解答
在微信公众平台开发的道路上,遍布着各种大大小小的坑,有的人掉坑里,几经折腾又爬出来了,然后拍拍屁股走人。然而坑还在那里,还会继续有后来人掉进去……
这,是我们不愿看到的。
所以在这里,我们将陆续将微信开发中可能遇到的各种疑难问题进行汇总,并给出对应的解决办法。一般情况下,这些问题都可以对号入座,轻松地解决。但也不排除特殊情况,这时候你遇到的问题与文中某一个症状一致,但文中所给的解决方案并不凑效,这种情况下就需要发挥你自己的智慧,去……折腾了……
我们期待这一版块为各位的开发带来便利,同时也希望各位本着开源、分享的精神对其进行补充和完善,将各种坑一一填小、填平,让微信开发变得不那么痛苦,甚至,变成一件快乐的事……
## 时区不对
使用命令 `date` 可以在服务器上查看当前时间,如果发现时区不对则需要修改时区:[Setting The Correct Timezone In CentOS And Ubuntu Servers With NTP](https://www.liberiangeek.net/2013/02/setting-the-correct-timezone-in-centos-and-ubuntu-servers-with-ntp/)
## curl: (60) SSL certificate problem: unable to get local issuer certificate
这是 SSL 证书问题所致,在使用 SDK 调用微信支付等相关的操作时可能会遇到报 “SSL certificate problem: unable to get local issuer certificate” 的错误。
微信公众平台提供的文档中建议对部分较敏感的操作接口使用 https 协议进行访问,例如微信支付和红包等接口中涉及到操作商户资金的一些操作。
wechat SDK 遵循了官方建议,所以在调用这些接口时,除了按照官方文档设置操作证书文件外,还需要保证服务器正确安装了 CA 证书。
1. 下载 CA 证书
你可以从 http://curl.haxx.se/ca/cacert.pem 下载 或者 使用[微信官方提供的证书](https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=4_3)中的 CA 证书 `rootca.pem` 也是同样的效果。
2. 在 `php.ini` 中配置 CA 证书
只需要将上面下载好的 CA 证书放置到您的服务器上某个位置,然后修改 `php.ini` 的 `curl.cainfo` 为该路径(**绝对路径!**),重启 `php-fpm` 服务即可。
```ini
curl.cainfo = /path/to/downloaded/cacert.pem
```
> 注意证书文件**路径为绝对路径**!以自己实际情况为准。
其它修改 HTTP 类源文件的方式是不允许的。
## cURL error 56: SSLRead() return error -9806
目前在 OSX 下,发现使用 HomeBrew 装的 PHP 7.0 有这个问题,解决方案是重新 brew 安装 PHP:
```shell
$ brew install homebrew/php/php70 --with-homebrew-openssl --with-homebrew-curl --without-snmp -vvv
```
验证:
```shell
$ php -i | grep 'OpenSSL support'
OpenSSL support => enabled
OpenSSL support => enabled
```
## 支付失败!当前页面的 URL 未注册
这是由于微信支付授权目录未正确配置引起的。此时开发者应该登录微信公众平台,进入**【微信支付】->【开发设置】**进行设置。
1. 公众号可添加 3 个支付授权目录,满足不同应用使用同一个公众号进行支付的业务需求。
2. 正确的**【支付授权目录】**应以 `http://` 或 `https://` 开头,并以正斜杠 `/` 结尾,授权目录所包含的域名**必须经过 ICP 备案**。
3. 支付授权目录需**细化至二级或三级目录**。
4. 所有**实际调起微信支付请求的页面都必须要所配置的支付授权目录之下**。
5. 在开发过程中,也可以使用测试授权目录进行开发测试,此时还**应该将参与测试的个人微信号添加到测试白名单中**,否则将出现对应的错误提示……
> \*页面**、**目录**、**URL **以及**域名\*\*等几个基本概念,并对自己所使用的框架的路由机制有一个大致了解。这样你才会知道自己正在配置的参数是个啥玩意儿,有什么卵用…… :smile:
## redirect_url 参数错误
这是由于程序使用了**网页授权**而公众号没有正确配置**【网页授权域名】**所致。此时你需要登录[微信公众平台](https://mp.weixin.qq.com/),在【开发】->【接口权限】页面找到**网页授权获取用户基本信息**进行配置并保存。
1. 网页授权域名应该为通过 ICP 备案的有效域名,否则保存时无法通过安全监测。
2. 网页授权域名即程序完成授权获得授权 code 后跳转到的页面的域名,一般情况下为你的业务域名。
3. 网页授权域名配置成功后会立即生效。
4. 公众号的网页授权域名只可配置一个,请合理规划你的业务,否则你会发现……授权域名不够用哈。
## [JSAPI] config: invalid url domain
在使用 JS-SDK 进行开发时,每个页面都需要调用 wx.config() 方法配置 JSPAI 参数。如果没有正确配置 **JSAPI 安全域名**并且开启了调试模式,此时就报此错误。遇到这个问题时,开发者需要登录微信公众平台,进入【公众号设置】->【功能设置】页面,将项目所使用的域名添加至 **【JSAPI 安全域名】**列表中。
1. 一个公众号同时最多可绑定**三个**安全域名,并且这些域名必须为通过 **ICP 备案**的**一级或一级以上**的有效域名。
2. JSAPI 安全域名每个月**限修改三次**,修改任何一个都算,所以,请谨慎操作。
3. 如果需要使用 JSAPI 调起支付功能,则支付目录必须也在所配置的**安全域名之下**,并且需要将支付目录添加至**支付授权目录**。
## token 验证失败、向公众号发送消息无任何反应
相信对接公众号一般是微信开发者进行开发过程中最先进行的工作,而在这看似简单的配置操作中,也可能会掉坑里。
最常见的两种情况就如下:
1. 确认你 “**启用**” 了开发模式, token 验证通过不代表启用,保存后也不代表启用。看到红色 “**停用**” 才真正的是启用了。
2. 配置好 URL(服务器地址)以及 Token(令牌)后,点击保存时提示**token 验证失败**,出现这种情况的原因有多种,其中之一便是网络不稳定,所以**可尝试多次保存**,若始终无法通过再排查其它可能因素。
3. 配置保存成功之后,向公众号发送消息无任何反应,自己的消息处理程序也没有被调用的记录(无对应日志)。这种情况下如果你尝试**反复停用和启用服务器配置**,可能突然间惊奇地了现,问题莫名其妙的解决了。
4. 使用在线调试工具的消息接口,http://mp.weixin.qq.com/debug/, 只要返回绿色的“**请求成功**”,就代表你的代码没有问题,请**重复上面第 3 项**再测试。
5. **如果你在用什么本地开发工具,或者什么 ngrok 代理到本机这样的开发方式,那么失败就很正常了,微信服务器到你机器的网络延迟太大(还是用服务器开发吧)。**
> 器 TOKEN 验证原理(官方文档有说明)并谨记服务器验证时使用 GET 方式访问,而公众平台向你的服务器发送消息/数据则使用 POST 方式,所以服务器验证成功之后,在某些启用了 CSRF 验证的框架里,接收消息时可能还会遇到 CSRF 相关的问题,请根据自己项目实际情况进行排查。
> 另外有的朋友的 Laravel 里使用了 laravel-debugbar,这个组件的原理是在页面输出时在后面添加 HTML 来实现的,所以它会改变我们返回给微信的内容,此时要么卸载,要么禁用掉它。
## Maximum function nesting level of '100' reached, aborting!
在使用了 Xdebug 的环境下可能出现这个问题。这是由于 Xdebug 限制函数嵌套的最大层级数(默认为 100),当嵌套次数达到该值便会触发 Xdebug 跳出嵌套并报此错误。
为避免这个问题,**可以将 Xdebug 的 max_nesting_level 参数适当设置大一些**,通常设置为 200 就可以了(当然可根据自己实际情况设置为更大的值)。
如下,修改 php.ini 配置文件后,重启 Apache 或 php-fpm 服务即可。
```ini
xdebug.max_nesting_level=200
```
## 扫码支付 获取商户订单信息超时或商户返回 httpcode 非 200!
1.确定签名正确,使用 SDK 基本上不会出什么问题 2.微信调用扫码支付回调链接,使用 POST 方式,确定服务器回调方法是否取消 csrf 验证
## Request access_token fail:{"errcode":61023,"errmsg":"refresh_token is invalid hint: [zDNUIA07582974]"}!
在用户授权时会获得该 authorizer_refresh_token 刷新令牌,而当缓存或数据库存储的该 authorizer_refresh_token 刷新令牌丢失后,可能会出现该问题,微信文档中说明
1.接口调用凭据刷新令牌(在授权的公众号具备 API 权限时,才有此返回值),刷新令牌主要用于第三方平台获取和刷新已授权用户的 access_token,只会在授权时刻提供,请妥善保存。
2.一旦丢失,只能让用户重新授权,才能再次拿到新的刷新令牌(https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1453779503&token=&lang=)。
3.为避免该问题,请将存储该刷新令牌的缓存有效期设置为 0(永久存储),并尽量不要去将该缓存或数据库清空。
如下:以 redis 为例。
```php
'expire' => 0,
```
## 替换 Handler,让 easywechat 支持协程
在 Swoft、IMI 等基于 Swoole 的协程框架中使用 easywechat 时,不免会有一个问题,就是 guzzle 客户端内置的 handler 不支持协程的问题。
这里,提供一个办法主动替换容器内的 guzzle_handler.
```php
$app = Factory::miniProgram($config);
$app['guzzle_handler'] = CoroutineHandler::class;
```
鉴于有些同学找不到可用的 `CoroutineHandler`,这里提供几个,供大家使用。
- hyperf/guzzle
- yurunsoft/guzzle-swoole
- mix/guzzle-hook
================================================
FILE: docs/src/5.x/wework/agents.md
================================================
# 应用管理
> 企业微信在17年11月对 API 进行了大量的改动,应用管理部分已经没啥用了
应用管理是企业微信中比较特别的地方,因为它的使用是不基于应用的,或者说基于任何一个应用都能访问这些 API,所以在用法上是直接调用 work 实例的 `agent` 属性。
```php
$config = [
...
];
$app = Factory::work($config);
```
## 应用列表
```php
$agents = $app->agent->list(); // 测试拿不到内容
```
## 应用详情
```php
$agents = $app->agent->get($agentId); // 只能传配置文件中的 id,API 改动所致
```
## 设置应用
```php
$agents = $app->agent->set($agentId, ['foo' => 'bar']);
```
## 设置工作台自定义展示
### 模版类型数据结构
可以通过接口配置展示类型。具体可设置:
- 关键数据型
- 图片型
- 列表型
- webview型
> 官方文档
> https://open.work.weixin.qq.com/api/doc/90000/90135/92535
### 设置应用在工作台展示的模版
```php
$params = [
'agentid' => 1000005,
'type' => 'image', //展示类型
'image' => [
'url' => 'xxxx',
'jump_url' => 'http://www.qq.com',
'pagepath' => 'pages/index'
],
'replace_user_data' => true
];
$agents->agent_workbench->setWorkbenchTemplate(array $params);
```
### 获取应用在工作台展示的模版
```php
$agentId = 100005;
$agents->agent_workbench->getWorkbenchTemplate(int $agentId);
```
### 设置应用在用户工作台展示的数据
```php
$params = [
'agentid' => 1000005,
'userid' => 'test', //员工id
'type' => 'keydata', //展示类型
'keydata' => [
'items' => [
[
'key' => '待审批',
'data' => '2',
'jump_url' => 'http://www.qq.com',
'pagepath' => 'pages/index'
],
[
'key' => '带批阅作业',
'data' => '4',
'jump_url' => 'http://www.qq.com',
'pagepath' => 'pages/index'
],
[
'key' => '成绩录入',
'data' => '45',
'jump_url' => 'http://www.qq.com',
'pagepath' => 'pages/index'
],
[
'key' => '综合评价',
'data' => '98',
'jump_url' => 'http://www.qq.com',
'pagepath' => 'pages/index'
]
]
]
];
$agents->agent_workbench->setWorkbenchData(array $params);
```
================================================
FILE: docs/src/5.x/wework/calendar.md
================================================
# 日程
企业微信日程功能允许应用管理企业内的日程安排,包括创建、更新、删除日程等操作。
## 获取实例
```php
$calendar = $app->calendar;
```
## 日程管理
### 创建日程
创建新的日程安排:
```php
$calendar = [
'organizer' => 'organizer_userid',
'summary' => '部门会议',
'color' => 1,
'description' => '讨论下季度工作计划',
'shares' => [
[
'userid' => 'participant1'
],
[
'userid' => 'participant2'
]
],
'start_time' => 1635724800, // 开始时间戳
'end_time' => 1635728400, // 结束时间戳
'cal_id' => '日程ID',
'reminders' => [
[
'is_repeat' => 0,
'remind_before_event_secs' => 300, // 提前5分钟提醒
'is_custom_repeat' => 0
]
],
'location' => [
'meetingroom' => '会议室A',
'address' => '公司A座10楼会议室A'
]
];
$result = $calendar->add($calendar);
```
**参数说明:**
- `organizer` string 组织者的userid
- `summary` string 日程标题
- `color` int 日程颜色,0-11对应不同颜色
- `description` string 日程详情描述
- `shares` array 参与人列表
- `start_time` int 开始时间戳
- `end_time` int 结束时间戳
- `cal_id` string 日程ID(可选)
- `reminders` array 提醒设置
- `location` array 地点信息
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"cal_id": "wcjgewCwAAqeJcPI1d8Pwbjt7nttzAAA"
}
```
### 更新日程
更新已存在的日程:
```php
$calendarData = [
'summary' => '更新后的会议标题',
'description' => '更新后的会议内容',
'start_time' => 1635731400,
'end_time' => 1635735000,
'location' => [
'meetingroom' => '会议室B',
'address' => '公司B座5楼会议室B'
]
];
$result = $calendar->update('wcjgewCwAAqeJcPI1d8Pwbjt7nttzAAA', $calendarData);
```
### 获取日程详情
获取指定日程的详细信息:
```php
$result = $calendar->get('wcjgewCwAAqeJcPI1d8Pwbjt7nttzAAA');
```
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"calendar": {
"cal_id": "wcjgewCwAAqeJcPI1d8Pwbjt7nttzAAA",
"organizer": "zhangsan",
"summary": "部门会议",
"color": 1,
"description": "讨论下季度工作计划",
"start_time": 1635724800,
"end_time": 1635728400,
"status": 1,
"location": {
"meetingroom": "会议室A",
"address": "公司A座10楼会议室A"
},
"shares": [
{
"userid": "participant1"
}
]
}
}
```
### 删除日程
删除指定的日程:
```php
$result = $calendar->delete('wcjgewCwAAqeJcPI1d8Pwbjt7nttzAAA');
```
### 获取日程列表
获取指定时间范围内的日程列表:
```php
$result = $calendar->list([
'offset' => 0,
'limit' => 10,
'start_time' => 1635724800, // 可选,开始时间
'end_time' => 1635811200 // 可选,结束时间
]);
```
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"calendar_list": [
{
"cal_id": "wcjgewCwAAqeJcPI1d8Pwbjt7nttzAAA",
"summary": "部门会议",
"start_time": 1635724800,
"end_time": 1635728400,
"status": 1
}
]
}
```
## 日程操作
### 接受日程邀请
参与者接受日程邀请:
```php
$result = $calendar->accept('wcjgewCwAAqeJcPI1d8Pwbjt7nttzAAA');
```
### 拒绝日程邀请
参与者拒绝日程邀请:
```php
$result = $calendar->decline('wcjgewCwAAqeJcPI1d8Pwbjt7nttzAAA');
```
### 设置日程状态
设置日程的参与状态:
```php
$result = $calendar->setStatus('wcjgewCwAAqeJcPI1d8Pwbjt7nttzAAA', [
'status' => 1, // 1:接受 2:拒绝 3:待定
'userid' => 'participant1'
]);
```
## 使用示例
### 创建部门例会
```php
use EasyWeChat\Factory;
$config = [
'corp_id' => 'your-corp-id',
'agent_id' => 'your-agent-id',
'secret' => 'your-secret',
// ...
];
$app = Factory::work($config);
$calendar = $app->calendar;
// 创建每周例会
$meetingData = [
'organizer' => 'manager_001',
'summary' => '技术部周例会',
'color' => 2, // 蓝色
'description' => '本周工作总结和下周计划讨论',
'shares' => [
['userid' => 'dev_001'],
['userid' => 'dev_002'],
['userid' => 'dev_003']
],
'start_time' => strtotime('next Monday 14:00'),
'end_time' => strtotime('next Monday 15:30'),
'reminders' => [
[
'is_repeat' => 0,
'remind_before_event_secs' => 900, // 提前15分钟提醒
'is_custom_repeat' => 0
]
],
'location' => [
'meetingroom' => '技术部会议室',
'address' => '研发中心2楼技术部会议室'
]
];
$result = $calendar->add($meetingData);
if ($result['errcode'] === 0) {
$calId = $result['cal_id'];
echo "例会创建成功,日程ID: {$calId}\n";
// 获取日程详情确认
$detail = $calendar->get($calId);
if ($detail['errcode'] === 0) {
$cal = $detail['calendar'];
echo "会议标题: {$cal['summary']}\n";
echo "开始时间: " . date('Y-m-d H:i:s', $cal['start_time']) . "\n";
echo "结束时间: " . date('Y-m-d H:i:s', $cal['end_time']) . "\n";
echo "参与人数: " . count($cal['shares']) . "\n";
}
} else {
echo "创建失败: {$result['errmsg']}\n";
}
```
### 批量处理日程
```php
// 获取本周的所有日程
$startOfWeek = strtotime('Monday this week');
$endOfWeek = strtotime('Sunday this week 23:59:59');
$calendarList = $calendar->list([
'start_time' => $startOfWeek,
'end_time' => $endOfWeek,
'limit' => 50
]);
if ($calendarList['errcode'] === 0) {
echo "本周共有 " . count($calendarList['calendar_list']) . " 个日程\n";
foreach ($calendarList['calendar_list'] as $cal) {
$startTime = date('m-d H:i', $cal['start_time']);
$endTime = date('H:i', $cal['end_time']);
echo "{$startTime}-{$endTime}: {$cal['summary']}\n";
// 如果是会议室预订类型的会议,检查状态
if (strpos($cal['summary'], '会议室') !== false) {
$detail = $calendar->get($cal['cal_id']);
if ($detail['errcode'] === 0) {
$status = $detail['calendar']['status'] ?? 0;
echo " 状态: " . ($status == 1 ? '正常' : '可能有冲突') . "\n";
}
}
}
}
```
### 日程提醒管理
```php
// 创建有多种提醒的重要会议
$importantMeeting = [
'organizer' => 'ceo_001',
'summary' => '董事会会议',
'color' => 0, // 红色,表示重要
'description' => '季度业绩汇报和战略讨论',
'shares' => [
['userid' => 'cto_001'],
['userid' => 'cfo_001'],
['userid' => 'director_001']
],
'start_time' => strtotime('+3 days 09:00'),
'end_time' => strtotime('+3 days 12:00'),
'reminders' => [
[
'is_repeat' => 0,
'remind_before_event_secs' => 86400, // 提前1天提醒
'is_custom_repeat' => 0
],
[
'is_repeat' => 0,
'remind_before_event_secs' => 3600, // 提前1小时提醒
'is_custom_repeat' => 0
],
[
'is_repeat' => 0,
'remind_before_event_secs' => 300, // 提前5分钟提醒
'is_custom_repeat' => 0
]
],
'location' => [
'meetingroom' => '董事会议室',
'address' => '总部大厦顶层董事会议室'
]
];
$result = $calendar->add($importantMeeting);
```
## 注意事项
1. **权限要求**:操作日程需要相应的应用权限
2. **时间格式**:所有时间参数使用Unix时间戳
3. **参与人限制**:单个日程的参与人数有上限
4. **日程冲突**:系统会检测时间冲突但不会自动解决
5. **提醒限制**:每个日程最多可设置5个提醒
## 最佳实践
1. **合理设置提醒**:根据会议重要性设置不同的提醒时间
2. **明确描述**:在description中提供详细的会议议程
3. **地点信息**:提供准确的会议地点信息
4. **状态管理**:及时更新和处理日程状态变更
5. **批量操作**:使用列表接口进行批量查询和管理
## 错误码说明
| 错误码 | 说明 |
|--------|------|
| 0 | 成功 |
| 40003 | 无效的UserID |
| 40013 | 不合法的CorpID |
| 60003 | 部门长度不符合限制 |
| 60102 | UserID已存在 |
| 85002 | 包含不合法字符 |
| 85004 | 每企业日程数量超过上限 |
================================================
FILE: docs/src/5.x/wework/chat.md
================================================
# 群聊管理
企业微信群聊管理功能允许应用管理企业内部群聊,包括创建群聊、管理群成员、发送群消息等。
## 获取实例
```php
$chat = $app->chat;
```
## 群聊基础操作
### 创建群聊
创建新的企业微信群聊:
```php
$chatData = [
'chatid' => 'project_team_001',
'name' => '项目开发小组',
'owner' => 'project_manager',
'userlist' => ['dev001', 'dev002', 'test001', 'pm001']
];
$result = $chat->create($chatData);
```
**参数说明:**
- `chatid` string 群聊ID,可自定义,不能与已有群聊重复
- `name` string 群聊名称
- `owner` string 群主的userid
- `userlist` array 群成员userid列表
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok"
}
```
### 获取群聊信息
获取指定群聊的详细信息:
```php
$result = $chat->get('project_team_001');
```
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"chat_info": {
"chatid": "project_team_001",
"name": "项目开发小组",
"owner": "project_manager",
"userlist": [
"dev001",
"dev002",
"test001",
"pm001"
]
}
}
```
### 修改群聊信息
更新群聊的基本信息:
```php
$updateData = [
'chatid' => 'project_team_001',
'name' => 'Alpha项目开发小组', // 新群名称
'owner' => 'new_project_manager', // 新群主
'add_user_list' => ['dev003', 'qa001'], // 新增成员
'del_user_list' => ['test001'] // 移除成员
];
$result = $chat->update($updateData);
```
**参数说明:**
- `chatid` string 群聊ID
- `name` string 新群名称(可选)
- `owner` string 新群主userid(可选)
- `add_user_list` array 要添加的成员列表(可选)
- `del_user_list` array 要移除的成员列表(可选)
### 解散群聊
解散指定的群聊:
```php
$result = $chat->quit('project_team_001');
```
## 群成员管理
### 批量邀请成员
向群聊中批量添加成员:
```php
$result = $chat->addMembers('project_team_001', ['new_dev001', 'new_qa001', 'new_pm001']);
```
### 批量移除成员
从群聊中批量移除成员:
```php
$result = $chat->removeMembers('project_team_001', ['old_dev001', 'former_pm001']);
```
### 获取群成员列表
获取群聊的所有成员信息:
```php
$result = $chat->getMembers('project_team_001');
```
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"userlist": [
{
"userid": "dev001",
"status": 1,
"join_time": 1635724800
},
{
"userid": "pm001",
"status": 1,
"join_time": 1635724800
}
]
}
```
## 群消息发送
### 发送文本消息
向群聊发送文本消息:
```php
$message = [
'chatid' => 'project_team_001',
'msgtype' => 'text',
'text' => [
'content' => '大家好,项目进入关键阶段,请及时沟通进展情况。'
]
];
$result = $chat->sendMessage($message);
```
### 发送图片消息
发送图片消息到群聊:
```php
$message = [
'chatid' => 'project_team_001',
'msgtype' => 'image',
'image' => [
'media_id' => 'image_media_id_123'
]
];
$result = $chat->sendMessage($message);
```
### 发送文件消息
发送文件到群聊:
```php
$message = [
'chatid' => 'project_team_001',
'msgtype' => 'file',
'file' => [
'media_id' => 'file_media_id_456'
]
];
$result = $chat->sendMessage($message);
```
### 发送卡片消息
发送图文卡片消息:
```php
$message = [
'chatid' => 'project_team_001',
'msgtype' => 'news',
'news' => [
'articles' => [
[
'title' => '项目进度报告',
'description' => '本周项目进展情况总结',
'url' => 'https://work.weixin.qq.com/report/123',
'picurl' => 'https://example.com/pic.jpg'
]
]
]
];
$result = $chat->sendMessage($message);
```
## 使用示例
### 项目群管理
```php
use EasyWeChat\Factory;
$config = [
'corp_id' => 'your-corp-id',
'agent_id' => 'your-agent-id',
'secret' => 'your-secret',
// ...
];
$app = Factory::work($config);
$chat = $app->chat;
// 1. 创建项目群
$projectChat = [
'chatid' => 'alpha_project_' . date('Ymd'),
'name' => 'Alpha项目组',
'owner' => 'project_manager_001',
'userlist' => [
'pm_001', // 项目经理
'dev_001', // 开发
'dev_002',
'qa_001', // 测试
'ui_001', // 设计
'ops_001' // 运维
]
];
$createResult = $chat->create($projectChat);
if ($createResult['errcode'] === 0) {
$chatId = $projectChat['chatid'];
echo "项目群创建成功: {$chatId}\n";
// 2. 发送欢迎消息
$welcomeMsg = [
'chatid' => $chatId,
'msgtype' => 'text',
'text' => [
'content' => "欢迎大家加入Alpha项目组!\n\n" .
"项目目标:开发新版本产品功能\n" .
"预计周期:8周\n" .
"请大家及时在群内同步工作进展,有问题随时讨论。"
]
];
$sendResult = $chat->sendMessage($welcomeMsg);
if ($sendResult['errcode'] === 0) {
echo "欢迎消息发送成功\n";
}
// 3. 定期发送项目进度提醒
$reminderMsg = [
'chatid' => $chatId,
'msgtype' => 'news',
'news' => [
'articles' => [
[
'title' => '项目进度提醒',
'description' => '请各位同事及时更新项目进度,确保按时完成任务',
'url' => 'https://project.company.com/alpha/progress',
'picurl' => 'https://cdn.company.com/project-icon.png'
]
]
]
];
$chat->sendMessage($reminderMsg);
}
```
### 动态群成员管理
```php
// 根据项目阶段动态调整群成员
function updateProjectTeam($chat, $chatId, $phase) {
switch ($phase) {
case 'design':
// 设计阶段:加入设计师,移除运维
$chat->addMembers($chatId, ['ui_002', 'ux_001']);
$chat->removeMembers($chatId, ['ops_001']);
$chat->sendMessage([
'chatid' => $chatId,
'msgtype' => 'text',
'text' => [
'content' => '项目进入设计阶段,欢迎设计团队加入!'
]
]);
break;
case 'development':
// 开发阶段:加入更多开发者
$chat->addMembers($chatId, ['dev_003', 'dev_004', 'backend_001']);
$chat->sendMessage([
'chatid' => $chatId,
'msgtype' => 'text',
'text' => [
'content' => '项目进入开发阶段,开发团队全员到位!'
]
]);
break;
case 'testing':
// 测试阶段:加入测试团队
$chat->addMembers($chatId, ['qa_002', 'qa_003', 'automation_001']);
$chat->sendMessage([
'chatid' => $chatId,
'msgtype' => 'text',
'text' => [
'content' => '项目进入测试阶段,测试团队请开始工作!'
]
]);
break;
case 'deployment':
// 部署阶段:重新加入运维
$chat->addMembers($chatId, ['ops_001', 'ops_002']);
$chat->sendMessage([
'chatid' => $chatId,
'msgtype' => 'text',
'text' => [
'content' => '项目准备部署,运维团队请准备!'
]
]);
break;
}
}
// 使用示例
updateProjectTeam($chat, $chatId, 'development');
```
### 群消息推送系统
```php
// 定时推送项目状态
function sendProjectStatus($chat, $chatId) {
// 获取项目数据(示例)
$projectData = [
'completed_tasks' => 45,
'total_tasks' => 60,
'bugs_fixed' => 12,
'open_bugs' => 3,
'progress' => 75
];
$progressBar = str_repeat('█', intval($projectData['progress'] / 10)) .
str_repeat('░', 10 - intval($projectData['progress'] / 10));
$statusMessage = [
'chatid' => $chatId,
'msgtype' => 'text',
'text' => [
'content' => "📊 项目进度日报\n\n" .
"进度: {$progressBar} {$projectData['progress']}%\n" .
"任务完成: {$projectData['completed_tasks']}/{$projectData['total_tasks']}\n" .
"Bug修复: {$projectData['bugs_fixed']}\n" .
"待修复Bug: {$projectData['open_bugs']}\n\n" .
"继续加油!💪"
]
];
return $chat->sendMessage($statusMessage);
}
// 每日定时发送
sendProjectStatus($chat, $chatId);
```
### 群聊数据统计
```php
// 统计群聊活跃度
function getChatStatistics($chat, $chatIds) {
$statistics = [];
foreach ($chatIds as $chatId) {
$chatInfo = $chat->get($chatId);
if ($chatInfo['errcode'] === 0) {
$info = $chatInfo['chat_info'];
$memberCount = count($info['userlist']);
$statistics[] = [
'chatid' => $chatId,
'name' => $info['name'],
'member_count' => $memberCount,
'owner' => $info['owner']
];
}
}
return $statistics;
}
// 生成群聊报告
$chatList = ['alpha_project_20231101', 'beta_project_20231015', 'gamma_project_20231020'];
$stats = getChatStatistics($chat, $chatList);
foreach ($stats as $stat) {
echo "群聊: {$stat['name']}\n";
echo "成员数: {$stat['member_count']}\n";
echo "群主: {$stat['owner']}\n";
echo "---\n";
}
```
## 注意事项
1. **群聊数量限制**:每个应用创建的群聊数量有限制
2. **成员数量限制**:单个群聊的成员数量有上限
3. **消息频率限制**:群消息发送有频率限制
4. **权限要求**:操作群聊需要相应的应用权限
5. **群主变更**:群主变更需要原群主或管理员权限
## 最佳实践
1. **群聊命名规范**:使用有意义的群聊ID和名称
2. **成员管理**:及时添加或移除相关成员
3. **消息内容**:发送有价值的群消息,避免垃圾信息
4. **权限控制**:合理设置群主和管理员
5. **定期清理**:定期清理不活跃的群聊
## 错误码说明
| 错误码 | 说明 |
|--------|------|
| 0 | 成功 |
| 40003 | 无效的UserID |
| 40013 | 不合法的CorpID |
| 86001 | 不合法的群聊ID |
| 86002 | 群聊不存在 |
| 86003 | 不合法的群聊名称 |
| 86004 | 群聊成员数量超出限制 |
| 86005 | 群聊创建数量超出限制 |
================================================
FILE: docs/src/5.x/wework/contacts.md
================================================
# 通讯录
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxx', // 通讯录的 secret
//...
];
$contacts = Factory::work($config);
```
## 成员管理
### 创建成员
```php
$data = [
"userid" => "overtrue",
"name" => "超哥",
"english_name" => "overtrue"
"mobile" => "1818888888",
];
$contacts->user->create($data);
```
### 读取成员
```php
$contacts->user->get('overtrue');
```
### 更新成员
```php
$contacts->user->update('overtrue', [
"isleader" => 0,
'position' => 'PHP 酱油工程师',
//...
]);
```
### 删除成员
```php
$contacts->user->delete('overtrue');
// 或者删除多个
$contacts->user->delete(['overtrue', 'zhangsan', 'wangwu']);
```
### 获取部门成员
```php
$contacts->user->getDepartmentUsers($departmentId);
// 递归获取子部门下面的成员
$contacts->user->getDepartmentUsers($departmentId, true);
```
### 获取部门成员详情
```php
$contacts->user->getDetailedDepartmentUsers($departmentId);
// 递归获取子部门下面的成员
$contacts->user->getDetailedDepartmentUsers($departmentId, true);
```
### 用户 ID 转为 openid
```php
$contacts->user->userIdToOpenid($userId);
// 或者指定应用 ID
$contacts->user->userIdToOpenid($userId, $agentId);
```
### openid 转为用户 ID
```php
$contacts->user->openidToUserId($openid);
```
### 手机号转为用户 ID
```php
$contacts->user->mobileToUserId($mobile);
```
### 二次验证
企业在成员验证成功后,调用如下接口即可让成员加入成功
```php
$contacts->user->accept($userId);
```
### 邀请成员
企业可通过接口批量邀请成员使用企业微信,邀请后将通过短信或邮件下发通知。
```php
$params = [
'user' => ['UserID1', 'UserID2', 'UserID3'], // 成员ID列表, 最多支持1000个
'party' => ['PartyID1', 'PartyID2'], // 部门ID列表,最多支持100个
'tag' => ['TagID1', 'TagID2'], // 标签ID列表,最多支持100个
];
$contacts->user->invite($params);
```
> `user`, `party`, `tag` 三者不能同时为空
### 获取邀请二维码
```php
$sizeType = 1; // qrcode尺寸类型,1: 171 x 171; 2: 399 x 399; 3: 741 x 741; 4: 2052 x 2052
$contacts->user->getInvitationQrCode($sizeType);
```
## 部门管理
### 创建部门
```php
$contacts->department->create([
'name' => '广州研发中心',
'parentid' => 1,
'order' => 1,
'id' => 2,
]);
```
### 更新部门
```php
$contacts->department->update($id, [
'name' => '广州研发中心',
'parentid' => 1,
'order' => 1,
]);
```
### 删除部门
```php
$contacts->department->delete($id);
```
### 获取部门列表
```php
$contacts->department->list();
// 获取指定部门及其下的子部门
$contacts->department->list($id);
```
## 标签管理
### 创建标签
```php
$contacts->tag->create($tagName, $tagId);
```
### 更新标签名字
```php
$contacts->tag->update($tagId, $tagName);
```
### 删除标签
```php
$contacts->tag->delete($tagId);
```
### 获取标签列表
```php
$contacts->tag->list();
```
### 获取标签成员(标签详情)
```php
$contacts->tag->get($tagId);
```
### 增加标签成员
```php
$contacts->tag->tagUsers($tagId, [$userId1, $userId2, ...]);
// 指定部门
$contacts->tag->tagDepartments($tagId, [$departmentId1, $departmentId2, ...]);
```
### 删除标签成员
```php
$contacts->tag->untagUsers($tagId, [$userId1, $userId2, ...]);
// 指定部门
$contacts->tag->untagDepartments($tagId, [$departmentId1, $departmentId2, ...]);
```
## 异步批量接口
> 注意: 【异步批量接口】需要使用“通讯录同步”secret所获取的accesstoken来调用。
> 传送: https://work.weixin.qq.com/wework_admin/frame#apps/contactsApi
### 增量更新成员
```php
$params = [
'media_id' => 'mediaId',
'to_invite' => true,
'callback' => [
'url' => 'xxx',
'token' => 'xxx',
'encodingaeskey' => 'xxx'
]
];
$contacts->batch_jobs->batchUpdateUsers(array $params);
```
### 全量覆盖成员
```php
$params = [
'media_id' => 'mediaId',
'to_invite' => true,
'callback' => [
'url' => 'xxx',
'token' => 'xxx',
'encodingaeskey' => 'xxx'
]
];
$contacts->batch_jobs->batchReplaceUsers(array $params);
```
### 全量覆盖部门
```php
$params = [
'media_id' => 'mediaId',
'callback' => [
'url' => 'xxx',
'token' => 'xxx',
'encodingaeskey' => 'xxx'
]
];
$contacts->batch_jobs->batchReplaceDepartments(array $params);
```
### 获取异步任务结果
```php
$jobId = '2322232';
$contacts->batch_jobs->getJobStatus(array $jobId);
```
## 互联企业
### 获取应用的可见范围
```php
$contacts->linked_corp->getAgentPermissions();
```
### 获取互联企业成员详细信息
```php
$userId = 'corpId/userId';
$contacts->linked_corp->getUser(string $userId);
```
### 获取互联企业部门成员
```php
$departmentId = 'linkedId/departmentId';
$fetchChild = true;
$contacts->linked_corp->getUsers(string $departmentId, bool $fetchChild = true);
```
### 获取互联企业部门成员详情
```php
$departmentId = 'linkedId/departmentId';
$fetchChild = true;
$contacts->linked_corp->getDetailedUsers(string $departmentId, bool $fetchChild = true);
```
### 获取互联企业部门列表
```php
$departmentId = 'linkedId/departmentId';
$contacts->linked_corp->getDepartments(string $departmentId);
```
================================================
FILE: docs/src/5.x/wework/corp-group.md
================================================
# 企业互联
### 获取应用共享信息
```php
$agentId = 100001;
$app->corp_group->getAppShareInfo(int $agentId);
```
### 获取下级企业的access_token
```php
$corpId = 'wwd216fa8c4c5c0e7x';
$agentId = 100001;
$app->corp_group->getToken(string $corpId, int $agentId)
```
### 获取下级企业的小程序session
```php
$userId = 'wmAoNVCwAAUrSqEqz7oQpEIEMVWDrPeg';
$sessionKey = 'n8cnNEoyW1pxSRz6/Lwjwg==';
$app->corp_group->getMiniProgramTransferSession(string $userId, string $sessionKey);
```
================================================
FILE: docs/src/5.x/wework/external-contact.md
================================================
# 客户联系
## 获取实例
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxx',
...
];
$app = Factory::work($config);
// 基础接口
$app->external_contact;
// 「联系我」
$app->contact_way;
// 消息管理
$app->external_contact_message;
// 数据统计
$app->external_contact_statistics;
```
## 基础接口
### 获取配置了客户联系功能的成员列表
```php
$app->external_contact->getFollowUsers();
```
### 获取外部联系人列表
```php
$userId = 'zhangsan';
$app->external_contact->list($userId);
```
### 获取外部联系人详情
```php
$externalUserId = 'woAJ2GCAAAXtWyujaWJHDDGi0mACH71w';
$app->external_contact->get($externalUserId);
```
### 批量获取客户详情
```php
$userId = 'zhangsai';
$cursor = '';
$limit = 100;
$app->external_contact->batchGetByUser(string $userId, string $cursor, int $limit);
```
### 修改客户备注信息
```php
$data = [
"userid"=>'员工id',
"external_userid"=>'客户id',
"remark"=> '新备注',
"description"=>'新描述',
"remark_company"=>'新公司',
"remark_mobiles"=>[ '电话1','电话2'],
"remark_pic_mediaid"=> "MEDIAID"
];
$app->external_contact->remark($data);
```
### 获取离职成员的客户列表
```php
$pageId = 0;
$pageSize = 1000;
$app->external_contact->getUnassigned($pageId, $pageSize);
```
### 分配成员的客户(离职或在职)
```php
$externalUserId = 'woAJ2GCAAAXtWyujaWJHDDGi0mACH71w';
$handoverUserId = 'zhangsan';
$takeoverUserId = 'lisi';
$transferSuccessMessage = '您好,您的服务已升级,后续将由我的同事张三@腾讯接替我的工作,继续为您服务。'; //不填则使用默认文案
$app->external_contact->transfer($externalUserId, $handoverUserId, $takeoverUserId, $transferSuccessMessage);
```
### 离职成员的群再分配
```php
$chatIds = ['群聊id1', '群聊id2'];
$takeoverUserId = '接替群主userid';
$app->external_contact->transferGroupChat($chatIds, $takeoverUserId);
```
### 查询客户接替结果
```php
$externalUserId = 'woAJ2GCAAAXtWyujaWJHDDGi0mACH71w';
$handoverUserId = 'zhangsan';
$takeoverUserId = 'lisi';
$app->external_contact->getTransferResult($externalUserId, $handoverUserId, $takeoverUserId);
```
## 客户群管理
### 获取客户群列表
```php
$params = [
"status_filter" => 0,
"owner_filter" => [
"userid_list" => ["abel"],
"partyid_list" => [7]
],
"offset" => 0,
"limit" => 100
];
$app->external_contact->getGroupChats(array $params);
```
### 获取客户群详情
```php
$chatId = 'wrOgQhDgAAMYQiS5ol9G7gK9JVAAAA';
$app->external_contact->getGroupChat(string $chatId);
```
## 客户朋友圈
### 获取企业全部的发表列表
```php
$params = [
'start_time' => 1605000000,
'end_time' => 1605172726,
'creator' => 'zhangshan',
'filter_type' => 1,
'cursor' => 'CURSOR',
'limit' => 10
];
$app->external_contact_moment->list(array $params);
```
### 获取客户朋友圈企业发表的列表
```php
$momentId = 'momxxx';
$cursor = 'CURSOR';
$limit = 10;
$app->external_contact_moment->getTasks(string $momentId, string $cursor, int $limit);
```
### 获取客户朋友圈发表时选择的可见范围
```php
$momentId = 'momxxx';
$userId = 'xxx';
$cursor = 'CURSOR';
$limit = 10;
$app->external_contact_moment->getCustomers(string $momentId, string $userId, string $cursor, int $limit);
```
### 获取客户朋友圈发表后的可见客户列表
```php
$momentId = 'momxxx';
$userId = 'xxx';
$cursor = 'CURSOR';
$limit = 10;
$app->external_contact_moment->getSendResult(string $momentId, string $userId, string $cursor, int $limit);
```
### 获取客户朋友圈的互动数据
```php
$momentId = 'momxxx';
$userId = 'xxx';
$app->external_contact_moment->getComments(string $momentId, string $userId);
```
## 客户标签管理
> 注意: 对于添加/删除/编辑企业客户标签接口,目前仅支持使用“客户联系”secret所获取的accesstoken来调用。
> 原文: https://work.weixin.qq.com/api/doc/90000/90135/92117
### 获取企业标签库
```php
$tagIds = [
"etXXXXXXXXXX",
"etYYYYYYYYYY"
];
$app->external_contact->getCorpTags(array $tagIds=[]);
```
### 添加企业客户标签
```php
$params = [
"group_id" => "GROUP_ID",
"group_name" => "GROUP_NAME",
"order" => 1,
"tag" => [
[
"name" => "TAG_NAME_1",
"order" => 1
],
[
"name" => "TAG_NAME_2",
"order" => 2
]
]
];
$app->external_contact->addCorpTag(array $params);
```
### 编辑企业客户标签
```php
$id = 'TAG_ID';
$name = 'NEW_TAG_NAME';
$order = 1;
$app->external_contact->updateCorpTag(string $id, string $name, int $order = 1);
```
### 删除企业客户标签
```php
$tagId = [
'TAG_ID_1',
'TAG_ID_2'
];
$groupId = [
'GROUP_ID_1',
'GROUP_ID_2'
];
$app->external_contact->deleteCorpTag(array $tagId,array $groupId);
```
### 编辑客户企业标签
```php
$params = [
"userid" => "zhangsan",
"external_userid" => "woAJ2GCAAAd1NPGHKSD4wKmE8Aabj9AAA",
"add_tag" => ["TAGID1", "TAGID2"],
"remove_tag" => ["TAGID3", "TAGID4"]
];
$app->external_contact->markTags(array $params);
```
## 配置客户联系「联系我」方式
> 注意:
> 1. 通过API添加的「联系我」不会在管理端进行展示。
> 2. 每个企业可通过API最多配置10万个「联系我」。
> 3. 截止 2019-06-21 官方文档没有提供获取所有「联系我」列表的接口,请开发者注意自行保管处理 configId,避免无法溯源。
### 增加「联系我」方式
```php
$type = 1;
$scene = 1;
$config = [
'style' => 1,
'remark' => '渠道客户',
'skip_verify' => true,
'state' => 'teststate',
'user' => ['UserID1', 'UserID2', 'UserID3'],
];
$app->contact_way->create($type, $scene, $config);
// {
// "errcode": 0,
// "errmsg": "ok",
// "config_id":"42b34949e138eb6e027c123cba77fad7"
// }
```
### 获取「联系我」方式
```php
$configId = '42b34949e138eb6e027c123cba77fad7';
$app->contact_way->get($configId);
```
### 更新「联系我」方式
```php
$configId = '42b34949e138eb6e027c123cba77fad7';
$config = [
'style' => 1,
'remark' => '渠道客户2',
'skip_verify' => true,
'state' => 'teststate2',
'user' => ['UserID4', 'UserID5', 'UserID6'],
];
$app->contact_way->update($configId, $config);
```
### 删除「联系我」方式
```php
$configId = '42b34949e138eb6e027c123cba77fad7';
$app->contact_way->delete($configId);
```
## 消息管理
### 添加企业群发消息模板
```php
$msg = [
'external_userid' => [
'woAJ2GCAAAXtWyujaWJHDDGi0mACas1w',
'wmqfasd1e1927831291723123109r712',
],
'sender' => 'zhangsan',
'text' => [
'content' => '文本消息内容',
],
'image' => [
'media_id' => 'MEDIA_ID',
],
'link' => [
'title' => '消息标题',
'picurl' => 'https://example.pic.com/path',
'desc' => '消息描述',
'url' => 'https://example.link.com/path',
],
'miniprogram' => [
'title' => '消息标题',
'pic_media_id' => 'MEDIA_ID',
'appid' => 'wx8bd80126147df384',
'page' => '/path/index',
],
];
$app->external_contact_message->submit($msg);
// {
// "errcode": 0,
// "errmsg": "ok",
// "fail_list":["wmqfasd1e19278asdasdasd"],
// "msgid":"msgGCAAAXtWyujaWJHDDGi0mACas1w"
// }
```
### 获取企业群发消息发送结果
```php
$msgId = 'msgGCAAAXtWyujaWJHDDGi0mACas1w';
$app->external_contact_message->get($msgId);
```
### 发送新客户欢迎语
```php
$welcomeCode = 'WELCOMECODE';
$msg = [
'text' => [
'content' => '文本消息内容',
],
'image' => [
'media_id' => 'MEDIA_ID',
],
'link' => [
'title' => '消息标题',
'picurl' => 'https://example.pic.com/path',
'desc' => '消息描述',
'url' => 'https://example.link.com/path',
],
'miniprogram' => [
'title' => '消息标题',
'pic_media_id' => 'MEDIA_ID',
'appid' => 'wx8bd80126147df384',
'page' => '/path/index',
],
];
$app->external_contact_message->sendWelcome($welcomeCode, $msg);
```
## 数据统计
### 获取「联系客户统计」数据
```php
$userIds = [
'zhangsan',
'lisi'
];
$partyIds = [
'PARTY_ID_1',
'PARTY_ID_2'
];
$from = 1536508800;
$to = 1536940800;
$app->external_contact_statistics->userBehavior($userIds, $from, $to, $partyIds);
```
### 获取「群聊数据统计」数据.
- 按群主聚合的方式
```php
$params = [
'day_begin_time' => 1600272000,
'day_end_time' => 1600444800,
'owner_filter' => [
'userid_list' => ['zhangsan']
],
'order_by' => 2,
'order_asc' => 0,
'offset' => 0,
'limit' => 1000
];
$app->external_contact_statistics->groupChatStatistic(array $params);
```
- 按自然日聚合的方式
```php
$dayBeginTime = 1600272000;
$dayEndTime = 1600444800;
$userIds = ['userid1', 'userid2'];
$app->external_contact_statistics->groupChatStatisticGroupByDay(int $dayBeginTime, int $dayEndTime, array $userIds);
```
================================================
FILE: docs/src/5.x/wework/group-robot.md
================================================
# 群机器人
## 使用说明
使用前必须先在群组里面添加机器人,然后将 `Webhook 地址` 中的 `key` 取出来,作为示例中 `$groupKey` 的值。
> Webhook 地址示例:
> 微信文档:
## 发送文本类型消息
快速发送文本消息
```php
// 获取 Messenger 实例
$messenger = $app->group_robot_messenger;
// 群组 key
$groupKey = 'ab4f609a-3feb-427c-ae9d-b319ca712d36';
$messenger->message('大家好,我是本群的"喝水提醒小助手"')->toGroup($groupKey)->send();
// 或者写成
$messenger->toGroup($groupKey)->send('大家好,我是本群的"喝水提醒小助手"');
```
使用 `Text` 发送文本消息
```php
use EasyWeChat\Work\GroupRobot\Messages\Text;
// 准备消息
$text = new Text('hello');
// 发送
$messenger->message($text)->toGroup($groupKey)->send();
```
@某人:
```php
use EasyWeChat\Work\GroupRobot\Messages\Text;
// 通过构造函数传参
$text = new Text('hello', 'her-cat', '18700000000');
//$text = new Text('hello', ['her-cat', 'overtrue'], ['18700000000', '18700000001']);
// 通过 userId
$text->mention('her-cat');
//$text->mention(['her-cat', 'overtrue']);
// 通过手机号
$text->mentionByMobile('18700000000');
//$text->mentionByMobile(['18700000000', '18700000001']);
// @所有人
$text->mention('@all');
//$text->mentionByMobile('@all');
$messenger->message($text)->toGroup($groupKey)->send();
```
## 发送 Markdown 类型消息
```php
use EasyWeChat\Work\GroupRobot\Messages\Markdown;
$content = '
# 标题一
## 标题二
绿色
灰色
橙红色
> 引用文字
';
$markdown = new Markdown($content);
$messenger->message($markdown)->toGroup($groupKey)->send();
```
## 发送图片类型消息
```php
use EasyWeChat\Work\GroupRobot\Messages\Image;
$img = file_get_contents('http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png');
$image = new Image(base64_encode($img), md5($img));
$result = $messenger->message($image)->toGroup($groupKey)->send();
```
## 发送图文类型消息
```php
use EasyWeChat\Work\GroupRobot\Messages\News;
use EasyWeChat\Work\GroupRobot\Messages\NewsItem;
$items = [
new NewsItem([
'title' => '中秋节礼品领取',
'description' => '今年中秋节公司有豪礼相送',
'url' => 'https://easywechat.com',
'image' => 'http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png',
]),
//...
];
$news = new News($items);
$messenger->message($news)->toGroup($groupKey)->send();
```
## 其他方式
使用 `group_robot` 发送消息。
```php
$app->group_robot->message('大家好,我是本群的"喝水提醒小助手"')->toGroup($groupKey)->send();
```
================================================
FILE: docs/src/5.x/wework/group-welcome-template.md
================================================
# 入群欢迎语
企业微信入群欢迎语功能允许企业管理外部联系人入群时的欢迎消息模板,提升客户体验。
## 获取实例
```php
$groupWelcomeTemplate = $app->group_welcome_template;
```
## 欢迎语模板管理
### 添加入群欢迎语素材
向企业的入群欢迎语素材库中添加新的素材:
```php
$templateData = [
'text' => [
'content' => '欢迎加入我们的产品交流群!\n\n我是您的专属客服小助手,有任何问题都可以随时咨询我。'
],
'image' => [
'media_id' => 'image_media_id_123',
'pic_url' => 'https://example.com/welcome.jpg'
],
'link' => [
'title' => '产品使用指南',
'picurl' => 'https://example.com/guide_thumb.jpg',
'desc' => '点击查看产品详细使用说明',
'url' => 'https://help.example.com/guide'
],
'miniprogram' => [
'title' => '产品小程序',
'pic_media_id' => 'pic_media_id_456',
'appid' => 'wx1234567890abcdef',
'page' => 'pages/welcome/index'
]
];
$result = $groupWelcomeTemplate->add($templateData);
```
**参数说明:**
- `text` array 文本消息内容
- `image` array 图片消息(可选)
- `link` array 链接消息(可选)
- `miniprogram` array 小程序消息(可选)
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"template_id": "msgtemplate4doGWjViuUW"
}
```
### 编辑入群欢迎语素材
编辑已存在的入群欢迎语素材:
```php
$templateId = 'msgtemplate4doGWjViuUW';
$updateData = [
'text' => [
'content' => '欢迎加入我们的VIP客户交流群!\n\n感谢您对我们产品的支持,我们将为您提供专属的优质服务。'
],
'image' => [
'media_id' => 'new_image_media_id',
'pic_url' => 'https://example.com/vip_welcome.jpg'
]
];
$result = $groupWelcomeTemplate->edit($templateId, $updateData);
```
### 获取入群欢迎语素材
获取指定的入群欢迎语素材详情:
```php
$result = $groupWelcomeTemplate->get('msgtemplate4doGWjViuUW');
```
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"text": {
"content": "欢迎加入我们的产品交流群!"
},
"image": {
"pic_url": "https://example.com/welcome.jpg"
},
"link": {
"title": "产品使用指南",
"picurl": "https://example.com/guide_thumb.jpg",
"desc": "点击查看产品详细使用说明",
"url": "https://help.example.com/guide"
}
}
```
### 删除入群欢迎语素材
删除指定的入群欢迎语素材:
```php
$result = $groupWelcomeTemplate->delete('msgtemplate4doGWjViuUW');
```
## 使用示例
### 创建多样化欢迎语模板
```php
use EasyWeChat\Factory;
$config = [
'corp_id' => 'your-corp-id',
'agent_id' => 'your-agent-id',
'secret' => 'your-secret',
// ...
];
$app = Factory::work($config);
$groupWelcomeTemplate = $app->group_welcome_template;
// 1. 基础文本欢迎语
$basicTemplate = [
'text' => [
'content' => '👋 欢迎加入我们的官方客户群!\n\n' .
'🎯 群功能介绍:\n' .
'• 产品使用答疑\n' .
'• 新功能抢先体验\n' .
'• 专享优惠活动\n\n' .
'💡 有问题随时 @我,1对1为您解答'
]
];
$basicResult = $groupWelcomeTemplate->add($basicTemplate);
if ($basicResult['errcode'] === 0) {
echo "基础欢迎语创建成功: {$basicResult['template_id']}\n";
}
// 2. 富媒体欢迎语(图片+链接)
$richTemplate = [
'text' => [
'content' => '🎉 欢迎加入VIP专享群!'
],
'image' => [
'pic_url' => 'https://cdn.example.com/vip_welcome.png'
],
'link' => [
'title' => 'VIP专享权益说明',
'picurl' => 'https://cdn.example.com/vip_benefits_thumb.jpg',
'desc' => '点击了解VIP会员专享服务内容',
'url' => 'https://vip.example.com/benefits'
]
];
$richResult = $groupWelcomeTemplate->add($richTemplate);
if ($richResult['errcode'] === 0) {
echo "富媒体欢迎语创建成功: {$richResult['template_id']}\n";
}
// 3. 小程序欢迎语
$miniprogramTemplate = [
'text' => [
'content' => '欢迎使用我们的小程序服务!'
],
'miniprogram' => [
'title' => '立即体验产品',
'appid' => 'wx1234567890abcdef',
'page' => 'pages/newuser/welcome?from=group',
'pic_media_id' => 'miniprogram_pic_media_id'
]
];
$miniprogramResult = $groupWelcomeTemplate->add($miniprogramTemplate);
if ($miniprogramResult['errcode'] === 0) {
echo "小程序欢迎语创建成功: {$miniprogramResult['template_id']}\n";
}
```
### 分类管理欢迎语模板
```php
// 根据不同群类型创建不同的欢迎语
function createWelcomeTemplatesByType($groupWelcomeTemplate) {
$templates = [
'product_support' => [
'text' => [
'content' => '🔧 欢迎加入产品技术支持群!\n\n' .
'📋 群内服务:\n' .
'• 技术问题快速解答\n' .
'• 产品使用教程分享\n' .
'• 故障排除指导\n\n' .
'⏰ 服务时间:工作日 9:00-18:00'
],
'link' => [
'title' => '技术文档中心',
'desc' => '查看完整的产品技术文档',
'url' => 'https://docs.example.com',
'picurl' => 'https://cdn.example.com/docs_thumb.jpg'
]
],
'sales_consultation' => [
'text' => [
'content' => '💼 欢迎加入销售咨询群!\n\n' .
'🎯 我们可以为您提供:\n' .
'• 产品价格咨询\n' .
'• 定制化方案设计\n' .
'• 合作政策解答\n\n' .
'📞 急需帮助请直接联系:400-123-4567'
],
'image' => [
'pic_url' => 'https://cdn.example.com/sales_banner.jpg'
]
],
'community_discussion' => [
'text' => [
'content' => '🌟 欢迎加入用户交流社区!\n\n' .
'💬 在这里您可以:\n' .
'• 分享使用心得\n' .
'• 参与产品讨论\n' .
'• 结识志同道合的朋友\n\n' .
'🏆 活跃用户将有机会获得专属礼品'
],
'miniprogram' => [
'title' => '社区积分商城',
'appid' => 'wx1234567890abcdef',
'page' => 'pages/community/points',
'pic_media_id' => 'community_pic_media_id'
]
]
];
$createdTemplates = [];
foreach ($templates as $type => $template) {
$result = $groupWelcomeTemplate->add($template);
if ($result['errcode'] === 0) {
$createdTemplates[$type] = $result['template_id'];
echo "创建 {$type} 欢迎语成功: {$result['template_id']}\n";
} else {
echo "创建 {$type} 欢迎语失败: {$result['errmsg']}\n";
}
sleep(1); // 避免频率限制
}
return $createdTemplates;
}
$templateIds = createWelcomeTemplatesByType($groupWelcomeTemplate);
```
### 定期更新欢迎语内容
```php
// 根据节日或活动更新欢迎语
function updateSeasonalWelcome($groupWelcomeTemplate, $templateId) {
$currentMonth = date('n');
$seasonalContent = '';
switch ($currentMonth) {
case 12:
case 1:
case 2:
$seasonalContent = '❄️ 冬日暖心服务,温暖每一位客户\n';
break;
case 3:
case 4:
case 5:
$seasonalContent = '🌸 春暖花开,与您共享美好时光\n';
break;
case 6:
case 7:
case 8:
$seasonalContent = '☀️ 夏日清凉,为您提供贴心服务\n';
break;
case 9:
case 10:
case 11:
$seasonalContent = '🍂 秋高气爽,收获满满的服务体验\n';
break;
}
$updateData = [
'text' => [
'content' => $seasonalContent .
'欢迎加入我们的客户服务群!\n\n' .
'我们将为您提供专业的服务支持。'
]
];
$result = $groupWelcomeTemplate->edit($templateId, $updateData);
if ($result['errcode'] === 0) {
echo "季节性欢迎语更新成功\n";
} else {
echo "更新失败: {$result['errmsg']}\n";
}
}
// 使用示例
if (!empty($templateIds['product_support'])) {
updateSeasonalWelcome($groupWelcomeTemplate, $templateIds['product_support']);
}
```
### 欢迎语模板管理
```php
// 获取和管理所有欢迎语模板
function manageWelcomeTemplates($groupWelcomeTemplate, $templateIds) {
foreach ($templateIds as $type => $templateId) {
// 获取模板详情
$detail = $groupWelcomeTemplate->get($templateId);
if ($detail['errcode'] === 0) {
echo "\n=== {$type} 模板 ({$templateId}) ===\n";
echo "文本内容: " . (isset($detail['text']['content']) ?
substr($detail['text']['content'], 0, 50) . '...' : '无') . "\n";
echo "是否包含图片: " . (isset($detail['image']) ? '是' : '否') . "\n";
echo "是否包含链接: " . (isset($detail['link']) ? '是' : '否') . "\n";
echo "是否包含小程序: " . (isset($detail['miniprogram']) ? '是' : '否') . "\n";
}
}
// 清理不再使用的模板
$unusedTemplates = ['old_template_id_1', 'old_template_id_2'];
foreach ($unusedTemplates as $templateId) {
$deleteResult = $groupWelcomeTemplate->delete($templateId);
if ($deleteResult['errcode'] === 0) {
echo "已删除废弃模板: {$templateId}\n";
}
}
}
manageWelcomeTemplates($groupWelcomeTemplate, $templateIds);
```
## 注意事项
1. **模板数量限制**:每个企业最多可创建100个入群欢迎语素材
2. **媒体资源**:图片和小程序封面需要先上传获取media_id
3. **内容审核**:欢迎语内容需要符合企业微信规范
4. **权限要求**:需要企业微信管理员权限
5. **更新频率**:避免频繁修改同一模板
## 最佳实践
1. **内容个性化**:根据不同群组类型设计不同的欢迎语
2. **信息丰富**:合理使用文本、图片、链接等多种形式
3. **定期更新**:根据季节、活动等适时更新内容
4. **简洁明了**:避免内容过长,突出重点信息
5. **引导行为**:通过欢迎语引导用户进行下一步操作
## 错误码说明
| 错误码 | 说明 |
|--------|------|
| 0 | 成功 |
| 40003 | 无效的UserID |
| 40013 | 不合法的CorpID |
| 41001 | 缺少access_token参数 |
| 84061 | 不合法的模板ID |
| 84062 | 模板已达到数量上限 |
| 84063 | 模板内容过长 |
| 84064 | 不合法的媒体文件 |
================================================
FILE: docs/src/5.x/wework/index.md
================================================
## 企业微信
企业微信的使用与公众号以及其它几个应用的使用方式都是一致的,使用 `\EasyWeChat\Factory::work($config)` 来初始化:
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'agent_id' => 100020, // 如果有 agend_id 则填写
'secret' => 'xxxxxxxxxx',
// 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
'response_type' => 'array',
'log' => [
'level' => 'debug',
'file' => __DIR__.'/wechat.log',
],
];
$app = Factory::work($config);
```
然后你就可以用 `$app` 来调用企业微信的服务了。
================================================
FILE: docs/src/5.x/wework/intercept.md
================================================
# 聊天敏感词
### 新建敏感词规则
```php
$params = [
'rule_name' => 'rulename',
'word_list' => [
'敏感词1', '敏感词2'
],
'semantics_list' => [1, 2, 3],
'intercept_type' => 1,
'applicable_range' => [
'user_list' => ['zhangshan'],
'department_list' => [2, 3]
]
];
$app->product->createInterceptRule($params);
```
### 获取敏感词规则详情
```php
$ruleId = 'ruleId';
$app->product->getInterceptRuleDetails($ruleId);
```
### 删除敏感词规则
```php
$ruleId = 'ruleId';
$app->product->deleteInterceptRule($ruleId);
```
### 编辑敏感词规则
```php
$params = [
'rule_id' => 'xxxx',
'rule_name' => 'rulename',
'word_list' => [
'敏感词1', '敏感词2'
],
'semantics_list' => [1, 2, 3],
'intercept_type' => 1,
'applicable_range' => [
'user_list' => ['zhangshan'],
'department_list' => [2, 3]
]
];
$app->product->updateInterceptRule($params);
```
================================================
FILE: docs/src/5.x/wework/invoice.md
================================================
# 电子发票
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxx',
//...
];
$app = Factory::work($config);
```
## 查询电子发票
https://work.weixin.qq.com/api/doc#11631
API:
```php
mixed get(string $cardId, string $encryptCode)
```
example:
```php
$app->invoice->get('CARDID', 'ENCRYPTCODE');
```
## 批量查询电子发票
https://work.weixin.qq.com/api/doc#11974
API:
```php
mixed select(array $invoices)
```
> $invoices: 发票参数列表
example:
```php
$invoices = [
["card_id" => "CARDID1", "encrypt_code" => "ENCRYPTCODE1"],
["card_id" => "CARDID2", "encrypt_code" => "ENCRYPTCODE2"]
];
$app->invoice->select($invoices);
```
## 更新发票状态
https://work.weixin.qq.com/api/doc#11633
API:
```php
mixed update(string $cardId, string $encryptCode, string $status)
```
> $status: 发报销状态
>
> > - INVOICE_REIMBURSE_INIT:发票初始状态,未锁定;
> > - INVOICE_REIMBURSE_LOCK:发票已锁定,无法重复提交报销;
> > - INVOICE_REIMBURSE_CLOSURE:发票已核销,从用户卡包中移除
## 批量更新发票状态
https://work.weixin.qq.com/api/doc#11633
API:
```php
mixed batchUpdate(array $invoices, string $openid, string $status)
```
example:
```php
$invoices = [
["card_id" => "CARDID1", "encrypt_code" => "ENCRYPTCODE1"],
["card_id" => "CARDID2", "encrypt_code" => "ENCRYPTCODE2"]
];
$openid = 'oV-gpwSU3xlMXbq0PqqRp1xHu9O4';
$status = 'INVOICE_REIMBURSE_CLOSURE';
$app->invoice->batchUpdate($invoices, $openid, $status)
```
================================================
FILE: docs/src/5.x/wework/jssdk.md
================================================
# JSSDK
企业微信 JSSDK 官方文档:https://open.work.weixin.qq.com/api/doc/90000/90136/90514
## API
### 获取config接口配置
```php
$app->jssdk->buildConfig(array $APIs, $debug = false, $beta = false, $json = true, array $openTagList = []);
```
默认返回 JSON 字符串,当 `$json` 为 `false` 时返回数组,你可以直接使用到网页中。
- 设置当前URL
```php
$app->jssdk->setUrl($url);
$app->jssdk->buildConfig(array $APIs, $debug = false, $beta = false, $json = true, array $openTagList = []);
```
如果不想用默认读取的URL,可以使用此方法手动设置,通常不需要。
- 示例
我们可以生成js配置文件:
```js
```
结果如下:
```js
```
### 获取agentConfig接口配置
调用wx.agentConfig之前,必须确保先成功调用wx.config. 注意:从企业微信3.0.24及以后版本(可通过企业微信UA判断版本号),无须先调用wx.config,可直接wx.agentConfig.
```php
$app->jssdk->buildAgentConfig(
array $jsApiList, // 需要检测的JS接口列表
$agentId, //应用id
bool $debug = false,
bool $beta = false,
bool $json = true,
array $openTagList = [],
string $url = null //设置当前URL
);
```
- 前端示例
```js
```
================================================
FILE: docs/src/5.x/wework/kf.md
================================================
# 微信客服
## 服务端(接收消息)
我们在企业微信 ”微信客服” 应用开启API接收消息的功能
将设置页面的 token 与 aes key 配置到 agents 下对应的应用内
> 注意: 需要使用“微信客服”secret所获取的accesstoken来调用
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxx',
// server config
'token' => 'xxxxxxxxx',
'aes_key' => 'xxxxxxxxxxxxxxxxxx',
//...
];
$app = Factory::work($config);
```
接着配置服务端与公众号的服务端用法一样:
请参考微信客服文档 https://open.work.weixin.qq.com/api/doc/90000/90135/94670
```php
$app->server->push(function($message){
// $message['FromUserName'] // 消息来源
// $message['MsgType'] // 消息类型:event ....
return 'Hello easywechat.';
});
$response = $app->server->serve();
$response->send();
```
`$response` 为 `Symfony\Component\HttpFoundation\Response` 实例,根据你的框架情况来决定如何处理响应。
## 客服帐号管理
### 添加客服帐号
```php
$app->kf_account->add(string $name, string $mediaId);
```
### 删除客服帐号
```php
$app->kf_account->del(string $openKfId);
```
### 修改客服帐号
```php
$app->kf_account->update(string $openKfId, string $name, string $mediaId);
```
### 获取客服帐号列表
```php
$app->kf_account->list();
```
### 获取客服帐号链接
```php
$app->kf_account->getAccountLink(string $openKfId, string $scene);
```
## 接待人员管理
### 添加接待人员
```php
$app->kf_servicer->add(string $openKfId, array $userIds);
```
### 删除接待人员
```php
$app->kf_servicer->del(string $openKfId, array $userIds);
```
### 获取接待人员列表
```php
$app->kf_servicer->list(string $openKfId);
```
## 会话分配与消息收发
### 获取会话状态
```php
$app->kf_message->state(string $openKfId, string $externalUserId);
```
### 变更会话状态
```php
$app->kf_message->updateState(string $openKfId, string $externalUserId, int $serviceState, string $serviceUserId);
```
### 读取消息
```php
$app->kf_message->sync(string $cursor, string $token, int $limit);
```
### 发送消息
```php
$app->kf_message->send(array $params);
```
### 发送事件响应消息
```php
$app->kf_message->event(array $params);
```
================================================
FILE: docs/src/5.x/wework/media.md
================================================
# 临时素材
它的使用是不基于应用的,或者说基于任何一个应用都能访问这些 API,所以在用法上是直接调用 work 实例的 `media` 属性:
**上传的媒体文件限制:**
所有文件size必须大于5个字节
> - 图片(image):2MB,支持JPG,PNG格式
> - 语音(voice):2MB,播放长度不超过60s,支持AMR格式
> - 视频(video):10MB,支持MP4格式
> - 普通文件(file):20MB
## 上传图片
> 注意:微信图片上传服务有敏感检测系统,图片内容如果含有敏感内容,如色情,商品推广,虚假信息等,上传可能失败。
```php
$app->media->uploadImage($path); // $path 为本地文件路径
```
## 上传声音
```php
$app->media->uploadVoice($path);
```
## 上传视频
```php
$app->media->uploadVideo($path);
```
## 上传普通文件
```php
$path = '/path/to/企业微信操作手册.pdf'
$form = [ //可选 发送时,中文文件名不显示或被过虑可传此参数
'filename' => '企业微信操作手册.pdf'
];
$app->media->uploadFile(string $path, array $form = []);
```
## 获取素材
```php
$app->media->get($mediaId);
```
================================================
FILE: docs/src/5.x/wework/menu.md
================================================
# 自定义菜单
自定义菜单是指为单个应用设置自定义菜单功能,所以在使用时请注意调用正确的应用实例。
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxx', // 应用的 secret
//...
];
$app = Factory::work($config);
```
## 创建菜单
```php
$menus = [
'button' => [
[
'name' => '首页',
'type' => 'view',
'url' => 'https://easywechat.com'
],
[
'name' => '关于我们',
'type' => 'view',
'url' => 'https://easywechat.com/about'
],
//...
],
];
$app->menu->create($menus);
```
## 获取菜单
```php
$app->menu->get();
```
## 删除菜单
```php
$app->menu->delete();
```
================================================
FILE: docs/src/5.x/wework/message.md
================================================
# 消息
## 主动发送消息
```php
use EasyWeChat\Kernel\Messages\TextCard;
// 获取 Messenger 实例
$messenger = $app->messenger;
// 准备消息
$message = new TextCard([
'title' => '你的请假单审批通过',
'description' => '单号:1928373, ....',
'url' => 'http://easywechat.com/oa/....'
]);
// 发送
$messenger->message($message)->toUser('overtrue')->send();
```
你也可以很方便的发送普通文本消息:
```php
$messenger->message('你的请假单(单号:1928373)已经审批通过!')->toUser('overtrue')->send();
// 或者写成
$messenger->toUser('overtrue')->send('你的请假单(单号:1928373)已经审批通过!');
```
## 接收消息
被动接收消息,与回复消息,请参考:[服务端](server)
## 更新任务卡片消息状态
```php
$messenger->updateTaskcard(array $userids, int $agentId, string $taskId, string $replaceName = '已收到')
```
================================================
FILE: docs/src/5.x/wework/mini-program.md
================================================
# 小程序
## 登录获取用户信息
> 注意:需要关联小程序,并且使用关联后的小程序AgentId与Secret。
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx', //企业id
'agent_id' => 100020, // 企业微信关联后的AgentId
'secret' => 'xxxxxxxxxx', //企业微信关联后的Secret
];
$app = Factory::work($config);
$miniProgram = $app->miniProgram();
$res = $miniProgram->auth->session("js-code");
```
================================================
FILE: docs/src/5.x/wework/mobile.md
================================================
# 移动端
## 通过code获取用户信息
通过iOS或Android应用授权登录,获取一次性code,通过后端服务器换取用户的信息。
```php
$code = 'CODE';
$app->mobile->getUser(string $code);
```
================================================
FILE: docs/src/5.x/wework/msg-audit.md
================================================
# 会话内容存档
> 企业需要使用会话内容存档应用secret所获取的accesstoken来调用。
> 原文: https://work.weixin.qq.com/api/doc/90000/90135/91614
### 会话存档相关SDK
- [wework-msgaudit](https://github.com/aa24615/wework-msgaudit)
### 获取会话内容存档开启成员列表
```php
$type = 1;
$app->msg_audit->getPermitUsers(string $type);
```
### 获取会话同意情况
- 单聊
```php
$info = [
[
"userid" => "XuJinSheng1",
"exteranalopenid" => "wmeDKaCQAAGd9oGiQWxVsAKwV2HxNAAA1"
],
[
"userid" => "XuJinSheng2",
"exteranalopenid" => "wmeDKaCQAAGd9oGiQWxVsAKwV2HxNAAA2"
],
[
"userid" => "XuJinSheng3",
"exteranalopenid" => "wmeDKaCQAAGd9oGiQWxVsAKwV2HxNAAA3"
]
];
$app->msg_audit->getSingleAgreeStatus(array $info);
```
- 群聊
```php
$roomId = 'wrjc7bDwAASxc8tZvBErFE02BtPWyAAA';
$app->msg_audit->getRoomAgreeStatus(string $roomId);
```
### 获取会话内容存档内部群信息
```php
$roomId = 'wrjc7bDwAASxc8tZvBErFE02BtPWyAAA';
$app->msg_audit->getRoom(string $roomId);
```
================================================
FILE: docs/src/5.x/wework/oa.md
================================================
# OA
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxx',
//...
];
$app = Factory::work($config);
```
## 打卡
### 获取企业所有打卡规则
```php
$app->oa->corpCheckinRules();
```
### 获取员工打卡规则
```php
$app->oa->checkinRules(int $datetime, array $userList);
```
### 获取打卡记录数据
> $type: 打卡类型 1:上下班打卡;2:外出打卡;3:全部打卡
```php
// 全部打卡数据
$app->oa->checkinRecords(1492617600, 1492790400, ["james","paul"]);
// 获取上下班打卡
$app->oa->checkinRecords(1492617600, 1492790400, ["james","paul"], 1);
// 获取外出打卡
$app->oa->checkinRecords(1492617600, 1492790400, ["james","paul"], 2);
```
### 获取打卡日报数据
```php
$app->oa->checkinDayData(int $startTime, int $endTime, array $userids);
```
### 获取打卡月报数据
```php
$app->oa->checkinMonthData(int $startTime, int $endTime, array $userids);
```
### 获取打卡人员排班信息
```php
$params = [
'groupid' => 226,
'items' => [
[
'userid' => 'james',
'day' => 5,
'schedule_id' => 234
]
],
'yearmonth' => 202012
];
$app->oa->setCheckinSchedus(array $params);
```
### 为打卡人员排班
```php
$app->oa->checkinSchedus(int $startTime, int $endTime, array $userids);
```
### 录入打卡人员人脸信息
```php
$app->oa->addCheckinUserface(string $userid, string $userface)
```
## 获取审批数据
API:
```php
mixed approvalRecords(int $startTime, int $endTime, int $nextNumber = null)
```
> $nextNumber: 第一个拉取的审批单号,不填从该时间段的第一个审批单拉取
```php
$app->oa->approvalRecords(1492617600, 1492790400);
// 指定第一个拉取的审批单号,不填从该时间段的第一个审批单拉取
$app->oa->approvalRecords(1492617600, 1492790400, '201704240001');
```
================================================
FILE: docs/src/5.x/wework/oauth.md
================================================
# OAuth
> 此文档为企业微信内部应用开发的网页授权
[企业微信官方文档](https://work.weixin.qq.com/api/doc#90000/90135/91020)
创建实例:
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxx', // 应用的 secret
'agent_id' => 100001,
];
$app = Factory::work($config);
```
## 跳转授权
```php
// $callbackUrl 为授权回调地址
$callbackUrl = 'https://xxx.xxx'; // 需设置可信域名
// 返回一个 redirect 实例
$redirect = $app->oauth->redirect($callbackUrl);
// 获取企业微信跳转目标地址
$targetUrl = $redirect->getTargetUrl();
// 直接跳转到企业微信授权
$redirect->send();
```
## 获取授权用户信息
在回调页面中,你可以使用以下方式获取授权者信息:
```php
$code = "回调URL中的code";
$user = $app->oauth->detailed()->userFromCode($code);
// 获取用户信息
$user->getId(); // 对应企业微信英文名(userid)
$user->getRaw(); // 获取企业微信接口返回的原始信息
```
获取用户其他信息需调用通讯录接口,参考:[企业微信通讯录 API](https://github.com/EasyWeChat/docs/blob/master/wework/contacts.md)
## 参考阅读
- 本模块基于 [overtrue/socialite](https://github.com/overtrue/socialite/) 实现,更多的使用请阅读该扩展包文档。
- state 参数的使用: [overtrue/socialite/#state](https://github.com/overtrue/socialite/#state)
================================================
FILE: docs/src/5.x/wework/product.md
================================================
# 产品图册
### 创建商品图册
```php
$params = [
'description'=>'世界上最好的商品',
'price'=>30000,
'product_sn'=>'xxxxxxxx',
'attachments'=>[
[
'type'=> 'image',
'image'=> [
'media_id'=> 'MEDIA_ID'
]
]
]
];
$app->product->createProductAlbum($params);
```
### 获取商品图册列表
```php
$app->product->getProductAlbums(int $limit, string $cursor);
```
### 获取商品图册
```php
$productId = 'productId';
$app->product->getProductAlbumDetails($productId);
```
### 删除商品图册
```php
$productId = 'productId';
$app->product->deleteProductAlbum($productId);
```
================================================
FILE: docs/src/5.x/wework/server.md
================================================
## 服务端
我们在企业微信应用开启接收消息的功能,将设置页面的 token 与 aes key 配置到 agents 下对应的应用内:
```php
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'agent_id' => 100022,
'secret' => 'xxxxxxxxxx',
// server config
'token' => 'xxxxxxxxx',
'aes_key' => 'xxxxxxxxxxxxxxxxxx',
//...
];
$app = Factory::work($config);
```
接着配置服务端与公众号的服务端用法一样:
```php
$app->server->push(function($message){
// $message['FromUserName'] // 消息来源
// $message['MsgType'] // 消息类型:event ....
return 'Hello easywechat.';
});
$response = $app->server->serve();
$response->send();
```
`$response` 为 `Symfony\Component\HttpFoundation\Response` 实例,根据你的框架情况来决定如何处理响应。
================================================
FILE: docs/src/5.x/wework/to-account.md
================================================
# 企微ID账号升级转换
:book: [官方文档 - 企业微信帐号ID安全性全面升级 说明文档](https://open.work.weixin.qq.com/api/doc/90001/90143/95327)
> 注意: 以下接口仅限第三方服务商调用
```php
$config = [...];
$app = Factory::openWork($config);
$work = $app->work('授权企业的corp_id','授权企业的永久授权码');
```
### corpid转换
```php
$work->corp_group->getOpenCorpid(string $corpId);
```
### userid转换
```php
$work->corp_group->batchUseridToOpenUserid(array $useridList);
```
### external_userid转换
```php
$work->external_contact->getNewExternalUserid(array $externalUserIds);
```
### 设置迁移完成
```php
$work->external_contact->finishExternalUseridMigration(string $corpId);
```
### unionid查询external_userid
```php
$work->external_contact->unionidToexternalUserid3rd(string $unionid, string $openid, string $corpid = '');
```
================================================
FILE: docs/src/5.x/wework/wedrive.md
================================================
# 微盘
企业微信微盘功能提供企业文件存储和管理能力,支持空间管理、文件操作等功能。
## 获取实例
```php
$wedrive = $app->wedrive;
```
## 空间管理
### 新建空间
创建新的微盘空间:
```php
$authInfo = [
[
'type' => 1, // 权限类型:1-成员 2-部门
'userid' => 'zhangsan',
'auth' => 1 // 权限:1-可下载 2-可预览 3-可编辑 4-可管理
],
[
'type' => 2,
'departmentid' => 2,
'auth' => 2
]
];
$result = $wedrive->space->create(
'admin_userid', // 操作者userid
'项目资料空间', // 空间名称
$authInfo, // 权限信息
0 // 空间类型:0-普通 1-相册
);
```
**参数说明:**
- `userid` string 操作者的userid
- `spaceName` string 空间名称
- `authInfo` array 空间成员权限信息
- `spaceSubType` int 空间类型,0:普通 1:相册
**权限类型说明:**
- `type` int 权限类型:1-成员 2-部门
- `userid` string 成员userid(type=1时必填)
- `departmentid` int 部门ID(type=2时必填)
- `auth` int 权限级别:1-可下载 2-可预览 3-可编辑 4-可管理
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"spaceid": "s_3b5ca2b43e454b89a6b4c32e516e4e99"
}
```
### 获取空间信息
获取指定空间的详细信息:
```php
$result = $wedrive->space->get('admin_userid', 's_3b5ca2b43e454b89a6b4c32e516e4e99');
```
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"space_info": {
"spaceid": "s_3b5ca2b43e454b89a6b4c32e516e4e99",
"space_name": "项目资料空间",
"auth_info": [
{
"type": 1,
"userid": "zhangsan",
"auth": 4,
"create_time": 1635724800
}
],
"space_sub_type": 0,
"space_capacity": 1073741824,
"space_used": 268435456
}
}
```
### 重命名空间
修改空间名称:
```php
$result = $wedrive->space->rename(
'admin_userid',
's_3b5ca2b43e454b89a6b4c32e516e4e99',
'更新后的空间名称'
);
```
### 解散空间
删除指定的空间:
```php
$result = $wedrive->space->dismiss('admin_userid', 's_3b5ca2b43e454b89a6b4c32e516e4e99');
```
## 文件管理
### 上传文件
上传文件到指定空间:
```php
$result = $wedrive->file->upload([
'userid' => 'zhangsan',
'spaceid' => 's_3b5ca2b43e454b89a6b4c32e516e4e99',
'fatherid' => 'parent_folder_id', // 父文件夹ID,根目录为空
'file_name' => '项目文档.docx',
'file_base64_content' => base64_encode(file_get_contents('/path/to/file.docx'))
]);
```
**参数说明:**
- `userid` string 操作者userid
- `spaceid` string 空间ID
- `fatherid` string 父文件夹ID,根目录时为空
- `file_name` string 文件名
- `file_base64_content` string 文件内容的base64编码
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"fileid": "f_3b5ca2b43e454b89a6b4c32e516e4e99"
}
```
### 新建文件夹
在指定位置创建文件夹:
```php
$result = $wedrive->file->createFolder([
'userid' => 'zhangsan',
'spaceid' => 's_3b5ca2b43e454b89a6b4c32e516e4e99',
'fatherid' => '', // 父目录ID,根目录为空
'folder_name' => '2023年度报告'
]);
```
### 获取文件列表
获取指定目录下的文件和文件夹列表:
```php
$result = $wedrive->file->list([
'userid' => 'zhangsan',
'spaceid' => 's_3b5ca2b43e454b89a6b4c32e516e4e99',
'fatherid' => '', // 目录ID,根目录为空
'sort_type' => 1, // 排序方式:1-名称 2-修改时间 3-大小
'start' => 0, // 起始位置
'limit' => 50 // 返回数量
]);
```
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"has_more": false,
"next_start": 0,
"file_list": [
{
"fileid": "f_3b5ca2b43e454b89a6b4c32e516e4e99",
"file_name": "项目文档.docx",
"spaceid": "s_3b5ca2b43e454b89a6b4c32e516e4e99",
"fatherid": "",
"file_size": 1024000,
"ctime": 1635724800,
"mtime": 1635724800,
"file_type": 1,
"file_status": 1
}
]
}
```
### 下载文件
获取文件下载链接:
```php
$result = $wedrive->file->download('zhangsan', 'f_3b5ca2b43e454b89a6b4c32e516e4e99');
```
**返回结果:**
```json
{
"errcode": 0,
"errmsg": "ok",
"download_url": "https://file.work.weixin.qq.com/xxx",
"cookie_name": "wedrive_ticket",
"cookie_value": "xxx"
}
```
### 移动文件
移动文件或文件夹到指定位置:
```php
$result = $wedrive->file->move([
'userid' => 'zhangsan',
'spaceid' => 's_3b5ca2b43e454b89a6b4c32e516e4e99',
'fileid' => 'f_3b5ca2b43e454b89a6b4c32e516e4e99',
'replace' => false, // 是否覆盖同名文件
'fatherid' => 'target_folder_id' // 目标文件夹ID
]);
```
### 删除文件
删除指定的文件或文件夹:
```php
$result = $wedrive->file->delete('zhangsan', 'f_3b5ca2b43e454b89a6b4c32e516e4e99');
```
### 重命名文件
修改文件或文件夹名称:
```php
$result = $wedrive->file->rename([
'userid' => 'zhangsan',
'fileid' => 'f_3b5ca2b43e454b89a6b4c32e516e4e99',
'new_name' => '新文件名.docx'
]);
```
## 权限管理
### 设置文件权限
设置文件的访问权限:
```php
$authInfo = [
[
'type' => 1,
'userid' => 'lisi',
'auth' => 2 // 可预览
],
[
'type' => 2,
'departmentid' => 3,
'auth' => 1 // 可下载
]
];
$result = $wedrive->file->setAuth([
'userid' => 'zhangsan',
'fileid' => 'f_3b5ca2b43e454b89a6b4c32e516e4e99',
'auth_info' => $authInfo
]);
```
### 获取文件权限
查询文件的权限设置:
```php
$result = $wedrive->file->getAuth('zhangsan', 'f_3b5ca2b43e454b89a6b4c32e516e4e99');
```
## 使用示例
### 项目文档管理
```php
use EasyWeChat\Factory;
$config = [
'corp_id' => 'your-corp-id',
'agent_id' => 'your-agent-id',
'secret' => 'your-secret',
// ...
];
$app = Factory::work($config);
$wedrive = $app->wedrive;
// 1. 创建项目空间
$authInfo = [
[
'type' => 1,
'userid' => 'project_manager',
'auth' => 4 // 项目经理有管理权限
],
[
'type' => 2,
'departmentid' => 10, // 开发部门
'auth' => 3 // 可编辑
],
[
'type' => 2,
'departmentid' => 20, // 测试部门
'auth' => 2 // 可预览
]
];
$space = $wedrive->space->create('admin', 'Alpha项目文档空间', $authInfo);
if ($space['errcode'] === 0) {
$spaceId = $space['spaceid'];
echo "空间创建成功: {$spaceId}\n";
// 2. 创建文件夹结构
$folders = ['需求文档', '设计文档', '开发文档', '测试文档'];
foreach ($folders as $folderName) {
$folder = $wedrive->file->createFolder([
'userid' => 'project_manager',
'spaceid' => $spaceId,
'fatherid' => '',
'folder_name' => $folderName
]);
if ($folder['errcode'] === 0) {
echo "文件夹创建成功: {$folderName}\n";
}
}
// 3. 上传项目文档
$docPath = '/path/to/project_requirements.docx';
if (file_exists($docPath)) {
$upload = $wedrive->file->upload([
'userid' => 'project_manager',
'spaceid' => $spaceId,
'fatherid' => '', // 先上传到根目录
'file_name' => '项目需求文档.docx',
'file_base64_content' => base64_encode(file_get_contents($docPath))
]);
if ($upload['errcode'] === 0) {
echo "文档上传成功: {$upload['fileid']}\n";
}
}
}
```
### 批量文件操作
```php
// 获取空间中的所有文件
$fileList = $wedrive->file->list([
'userid' => 'admin',
'spaceid' => $spaceId,
'fatherid' => '',
'limit' => 100
]);
if ($fileList['errcode'] === 0) {
foreach ($fileList['file_list'] as $file) {
echo "文件: {$file['file_name']} ";
echo "大小: " . round($file['file_size'] / 1024, 2) . "KB ";
echo "修改时间: " . date('Y-m-d H:i:s', $file['mtime']) . "\n";
// 如果是旧文件(超过30天),移动到归档文件夹
if ($file['mtime'] < strtotime('-30 days')) {
$move = $wedrive->file->move([
'userid' => 'admin',
'spaceid' => $spaceId,
'fileid' => $file['fileid'],
'fatherid' => 'archive_folder_id',
'replace' => false
]);
if ($move['errcode'] === 0) {
echo " -> 已移动到归档文件夹\n";
}
}
}
}
```
### 文件分享与权限控制
```php
// 为外部合作伙伴设置特定文件的预览权限
$shareAuth = [
[
'type' => 1,
'userid' => 'partner_001',
'auth' => 2 // 只能预览,不能下载
]
];
$setAuth = $wedrive->file->setAuth([
'userid' => 'project_manager',
'fileid' => $fileId,
'auth_info' => $shareAuth
]);
if ($setAuth['errcode'] === 0) {
// 获取下载链接供分享
$download = $wedrive->file->download('partner_001', $fileId);
if ($download['errcode'] === 0) {
echo "分享链接: {$download['download_url']}\n";
echo "访问凭证: {$download['cookie_value']}\n";
}
}
```
## 注意事项
1. **存储限制**:每个企业的微盘空间有总容量限制
2. **文件大小**:单个文件上传大小有限制,大文件建议分片上传
3. **权限继承**:子文件夹会继承父文件夹的权限设置
4. **删除恢复**:删除的文件会进入回收站,可以恢复
5. **并发操作**:避免同时对同一文件进行多个操作
## 最佳实践
1. **合理规划空间结构**:按项目或部门创建独立空间
2. **权限最小化原则**:只给必要的访问权限
3. **定期清理**:定期清理不需要的文件,释放存储空间
4. **版本管理**:对重要文档进行版本控制
5. **备份策略**:重要文件建议进行额外备份
## 错误码说明
| 错误码 | 说明 |
|--------|------|
| 0 | 成功 |
| 40003 | 无效的UserID |
| 41006 | 缺少spaceid参数 |
| 41008 | 缺少fileid参数 |
| 85005 | 文件不存在 |
| 85006 | 空间不存在 |
| 85007 | 没有权限 |
| 85008 | 空间容量不足 |
================================================
FILE: docs/src/6.x/cache.md
================================================
# 缓存
EasyWeChat 6.x 使用 [symfony/cache](https://github.com/symfony/cache) 组件来处理缓存,它支持目前几乎所有主流的缓存引擎。
在 SDK 中,所有缓存默认使用文件系统缓存,缓存路径取决于 PHP 的临时目录。如果你需要自定义缓存配置,可以通过简单的几个步骤来实现。
## 默认缓存行为
EasyWeChat 6.x 中的应用实例(如 `OfficialAccount\Application`、`MiniApp\Application` 等)都通过 `InteractWithCache` trait 提供了统一的缓存接口:
```php
use EasyWeChat\OfficialAccount\Application;
$app = new Application([
'app_id' => 'your-app-id',
'secret' => 'your-app-secret',
// ...
]);
// 获取默认缓存实例
$cache = $app->getCache();
// 缓存默认配置
echo $app->getCacheLifetime(); // 1500 秒
echo $app->getCacheNamespace(); // 'easywechat'
```
## 缓存配置调整
你可以调整缓存的生命周期和命名空间:
```php
// 设置缓存生命周期为 3600 秒(1小时)
$app->setCacheLifetime(3600);
// 设置缓存命名空间
$app->setCacheNamespace('my_wechat_app');
```
## 使用 Redis 缓存
### 基础 Redis 配置
使用 Redis 作为缓存引擎是最常见的需求。首先安装 Redis 相关扩展:
```bash
composer require predis/predis
```
然后配置 Redis 缓存:
```php
use EasyWeChat\OfficialAccount\Application;
use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Component\Cache\Psr16Cache;
// 创建应用实例
$app = new Application([
'app_id' => 'your-app-id',
'secret' => 'your-app-secret',
]);
// 创建 Redis 连接
$redis = new \Predis\Client([
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => 6379,
]);
// 创建 Redis 缓存适配器
$cache = new Psr16Cache(
new RedisAdapter($redis, 'easywechat', 1500)
);
// 设置自定义缓存
$app->setCache($cache);
```
### 使用 Redis 集群
对于 Redis 集群环境:
```php
use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Component\Cache\Psr16Cache;
// Redis 集群配置
$redis = new \Predis\Client([
[
'scheme' => 'tcp',
'host' => '10.0.0.1',
'port' => 6379,
],
[
'scheme' => 'tcp',
'host' => '10.0.0.2',
'port' => 6379,
],
], [
'cluster' => 'redis',
]);
$cache = new Psr16Cache(
new RedisAdapter($redis, 'easywechat_cluster', 1500)
);
$app->setCache($cache);
```
### 使用 phpredis 扩展
如果你使用 phpredis 扩展:
```php
use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Component\Cache\Psr16Cache;
// 使用 phpredis
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);
$redis->select(1); // 选择数据库
$cache = new Psr16Cache(
new RedisAdapter($redis, 'easywechat', 1500)
);
$app->setCache($cache);
```
## 使用 Memcached 缓存
```php
use Symfony\Component\Cache\Adapter\MemcachedAdapter;
use Symfony\Component\Cache\Psr16Cache;
// 创建 Memcached 连接
$memcached = new \Memcached();
$memcached->addServer('127.0.0.1', 11211);
// 创建缓存实例
$cache = new Psr16Cache(
new MemcachedAdapter($memcached, 'easywechat', 1500)
);
$app->setCache($cache);
```
## 在 Laravel 中使用
Laravel 框架提供了便捷的缓存管理,你可以直接使用 Laravel 的缓存驱动:
### 使用 Laravel Cache
```php
use Symfony\Component\Cache\Adapter\Psr16Adapter;
use Symfony\Component\Cache\Psr16Cache;
// 将 Laravel Cache 转换为 PSR-16 缓存
$cache = new Psr16Cache(
new Psr16Adapter(
app('cache')->store() // 使用默认缓存驱动
)
);
$app->setCache($cache);
```
### 使用指定的 Laravel Cache Store
```php
// 使用 Redis 作为缓存驱动
$cache = new Psr16Cache(
new Psr16Adapter(
app('cache')->store('redis')
)
);
$app->setCache($cache);
```
### Laravel 服务提供者中配置
在 Laravel 服务提供者中统一配置:
```php
// app/Providers/WeChatServiceProvider.php
use EasyWeChat\OfficialAccount\Application;
use Illuminate\Support\ServiceProvider;
use Symfony\Component\Cache\Adapter\Psr16Adapter;
use Symfony\Component\Cache\Psr16Cache;
class WeChatServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton('wechat.official_account', function ($app) {
$application = new Application(config('wechat.official_account'));
// 使用 Laravel 缓存
$cache = new Psr16Cache(
new Psr16Adapter(
$app['cache']->store(config('wechat.cache_store', 'redis'))
)
);
$application->setCache($cache);
return $application;
});
}
}
```
## 自定义缓存驱动
如果现有的缓存驱动无法满足你的需求,你可以实现自己的缓存类,只需实现 [PSR-16](https://www.php-fig.org/psr/psr-16/) 规范即可。
### 实现 PSR-16 接口
PSR-16 `CacheInterface` 接口包含以下方法:
```php
interface CacheInterface
{
public function get($key, $default = null);
public function set($key, $value, $ttl = null);
public function delete($key);
public function clear();
public function getMultiple($keys, $default = null);
public function setMultiple($values, $ttl = null);
public function deleteMultiple($keys);
public function has($key);
}
```
### 自定义缓存实现示例
```php
use Psr\SimpleCache\CacheInterface;
class MyCustomCache implements CacheInterface
{
private array $data = [];
public function get($key, $default = null)
{
return $this->data[$key] ?? $default;
}
public function set($key, $value, $ttl = null)
{
// 这里可以实现你的存储逻辑
// 比如存储到数据库、文件或其他存储系统
$this->data[$key] = $value;
return true;
}
public function delete($key)
{
unset($this->data[$key]);
return true;
}
public function clear()
{
$this->data = [];
return true;
}
public function getMultiple($keys, $default = null)
{
$result = [];
foreach ($keys as $key) {
$result[$key] = $this->get($key, $default);
}
return $result;
}
public function setMultiple($values, $ttl = null)
{
foreach ($values as $key => $value) {
$this->set($key, $value, $ttl);
}
return true;
}
public function deleteMultiple($keys)
{
foreach ($keys as $key) {
$this->delete($key);
}
return true;
}
public function has($key)
{
$stmt = $this->pdo->prepare("
SELECT 1 FROM cache_items
WHERE cache_key = ? AND (expires_at IS NULL OR expires_at > NOW())
");
$stmt->execute([$key]);
return $stmt->fetchColumn() !== false;
}
}
```
### 使用自定义缓存
```php
// 实例化自定义缓存
$myCache = new MyCustomCache();
// 应用到 EasyWeChat
$app->setCache($myCache);
```
## 数据库缓存实现
下面是一个使用数据库作为缓存存储的完整示例:
```php
use Psr\SimpleCache\CacheInterface;
class DatabaseCache implements CacheInterface
{
private \PDO $pdo;
public function __construct(\PDO $pdo)
{
$this->pdo = $pdo;
$this->createTable();
}
private function createTable()
{
$sql = "
CREATE TABLE IF NOT EXISTS cache_items (
cache_key VARCHAR(255) PRIMARY KEY,
cache_value TEXT,
expires_at TIMESTAMP NULL
)
";
$this->pdo->exec($sql);
}
public function get($key, $default = null)
{
$stmt = $this->pdo->prepare("
SELECT cache_value FROM cache_items
WHERE cache_key = ? AND (expires_at IS NULL OR expires_at > NOW())
");
$stmt->execute([$key]);
$result = $stmt->fetchColumn();
if ($result === false) {
return $default;
}
return unserialize($result);
}
public function set($key, $value, $ttl = null)
{
$expiresAt = $ttl ? date('Y-m-d H:i:s', time() + $ttl) : null;
$stmt = $this->pdo->prepare("
REPLACE INTO cache_items (cache_key, cache_value, expires_at)
VALUES (?, ?, ?)
");
return $stmt->execute([
$key,
serialize($value),
$expiresAt
]);
}
public function delete($key)
{
$stmt = $this->pdo->prepare("DELETE FROM cache_items WHERE cache_key = ?");
return $stmt->execute([$key]);
}
public function clear()
{
return $this->pdo->exec("DELETE FROM cache_items") !== false;
}
public function getMultiple($keys, $default = null)
{
$result = [];
foreach ($keys as $key) {
$result[$key] = $this->get($key, $default);
}
return $result;
}
public function setMultiple($values, $ttl = null)
{
foreach ($values as $key => $value) {
$this->set($key, $value, $ttl);
}
return true;
}
public function deleteMultiple($keys)
{
foreach ($keys as $key) {
$this->delete($key);
}
return true;
}
public function has($key)
{
$stmt = $this->pdo->prepare("
SELECT 1 FROM cache_items
WHERE cache_key = ? AND (expires_at IS NULL OR expires_at > NOW())
");
$stmt->execute([$key]);
return $stmt->fetchColumn() !== false;
}
}
// 使用示例
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$cache = new DatabaseCache($pdo);
$app->setCache($cache);
```
## 缓存性能优化建议
### 1. 选择合适的缓存驱动
- **Redis**: 适用于分布式环境,支持丰富的数据结构
- **Memcached**: 简单高效,适用于纯缓存场景
- **文件缓存**: 适用于单机环境或小型应用
- **数据库缓存**: 适用于需要持久化的场景
### 2. 合理设置缓存时间
```php
// 根据数据更新频率设置不同的缓存时间
$app->setCacheLifetime(7200); // Access Token 缓存 2 小时
```
### 3. 使用缓存前缀避免冲突
```php
// 为不同环境设置不同的命名空间
$app->setCacheNamespace('easywechat_prod'); // 生产环境
$app->setCacheNamespace('easywechat_dev'); // 开发环境
```
### 4. 监控缓存命中率
```php
// 在自定义缓存中添加统计功能
class MonitoredCache implements CacheInterface
{
private $hits = 0;
private $misses = 0;
public function get($key, $default = null)
{
$value = $this->actualCache->get($key, $default);
if ($value === $default) {
$this->misses++;
} else {
$this->hits++;
}
return $value;
}
public function getHitRate(): float
{
$total = $this->hits + $this->misses;
return $total > 0 ? $this->hits / $total : 0;
}
}
```
## 常见问题
### Q: 如何清空 EasyWeChat 的缓存?
```php
// 清空当前应用的所有缓存
$app->getCache()->clear();
// 删除特定缓存项
$app->getCache()->delete('specific_key');
```
### Q: 如何在不同的应用间共享缓存?
```php
// 使用相同的缓存实例
$sharedCache = new Psr16Cache(new RedisAdapter($redis));
$officialAccount->setCache($sharedCache);
$miniApp->setCache($sharedCache);
```
### Q: 缓存键冲突怎么办?
```php
// 为不同应用设置不同的命名空间
$officialAccount->setCacheNamespace('wechat_oa');
$miniApp->setCacheNamespace('wechat_mini');
```
通过合理配置缓存,你可以显著提升 EasyWeChat 应用的性能和响应速度。选择适合你业务场景的缓存方案,并根据实际使用情况进行优化调整。
================================================
FILE: docs/src/6.x/client.md
================================================
# API 调用
与以往版本不同的是,SDK 不再内置具体 API 的逻辑,所有的 API 均交由开发者自行调用,以更新用户备注为例:
```php
$api = $app->getClient();
$response = $api->post('/cgi-bin/user/info/updateremark', [
'json' => [
"openid" => "oDF3iY9ffA-hqb2vVvbr7qxf6A0Q",
"remark" => "pangzi"
]
]);
// or
// 如果参数中存在query之类的关键字建议使用上面的方法,不建议以下调用方式
$response = $api->postJson('/cgi-bin/user/info/updateremark', [
"openid" => "oDF3iY9ffA-hqb2vVvbr7qxf6A0Q",
"remark" => "pangzi"
]);
```
## 语法说明
```php
get(string $uri, array $options = []): Symfony\Contracts\HttpClient\ResponseInterface
post(string $uri, array $options = []): Symfony\Contracts\HttpClient\ResponseInterface
patch(string $uri, array $options = []): Symfony\Contracts\HttpClient\ResponseInterface
put(string $uri, array $options = []): Symfony\Contracts\HttpClient\ResponseInterface
delete(string $uri, array $options = []): Symfony\Contracts\HttpClient\ResponseInterface
```
同时还内置了一些便捷方法:
```php
postJson(string $url, array $data = [], array $options = []): Symfony\Contracts\HttpClient\ResponseInterface
patchJson(string $url, array $data = [], array $options = []): Symfony\Contracts\HttpClient\ResponseInterface
postXml(string $url, array $data = [], array $options = []): Symfony\Contracts\HttpClient\ResponseInterface
```
`$options` 为请求参数,可以指定 `query`/`body`/`json`/`xml`/`headers` 等等,具体请参考:[HttpClientInterface::OPTIONS_DEFAULTS](https://github.com/symfony/symfony/blob/6.1/src/Symfony/Contracts/HttpClient/HttpClientInterface.php)
---
## 请求参数
### GET
```php
$response = $api->get('/cgi-bin/user/list', [
'next_openid' => 'OPENID1',
]);
```
### POST
```php
$response = $api->post('/cgi-bin/user/info/updateremark', [
'body' => \json_encode([
"openid" => "oDF3iY9ffA-hqb2vVvbr7qxf6A0Q",
"remark" => "pangzi"
])
]);
```
或者可以简写为:
```php
$response = $api->postJson('/cgi-bin/user/info/updateremark', [
"openid" => "oDF3iY9ffA-hqb2vVvbr7qxf6A0Q",
"remark" => "pangzi"
]);
```
或者指定 xml 格式:
```php
$response = $api->postXml('/mmpaymkttransfers/promotion/transfers', [
'mch_appid' => $app->getConfig()['app_id'],
'mchid' => $app->getConfig()['mch_id'],
'partner_trade_no' => '202203081646729819743',
'openid' => 'ogn1H45HCRxVRiEMLbLLuABbxxxx',
'check_name' => 'FORCE_CHECK',
're_user_name'=> 'overtrue',
'amount' => 100,
'desc' => '理赔',
]);
```
### 请求证书
你可以在请求支付时指定证书,以微信支付 V2 为例:
```php
$response = $api->post('/mmpaymkttransfers/promotion/transfers', [
'xml' => [
'mch_appid' => $app->getConfig()['app_id'],
'mchid' => $app->getConfig()['mch_id'],
'partner_trade_no' => '202203081646729819743',
'openid' => 'ogn1H45HCRxVRiEMLbLLuABbxxxx',
'check_name' => 'FORCE_CHECK',
're_user_name'=> 'overtrue',
'amount' => 100,
'desc' => '理赔',
],
'local_cert' => $app->getConfig()['cert_path'],
'local_pk' => $app->getConfig()['key_path'],
]);
```
> 参考:[symfony/http-client#options](https://symfony.com/doc/current/reference/configuration/framework.html#local-cert)
### 文件上传
你有两种上传文件的方式可以选择:
#### 从指定路径上传
```php
use EasyWeChat\Kernel\Form\File;
use EasyWeChat\Kernel\Form\Form;
$options = Form::create(
[
'media' => File::fromPath('/path/to/image.jpg'),
]
)->toArray();
$response = $api->post('cgi-bin/media/upload?type=image', $options);
```
#### 从二进制内容上传
```php
use EasyWeChat\Kernel\Form\File;
use EasyWeChat\Kernel\Form\Form;
$options = Form::create(
[
'media' => File::withContents($contents, 'image.jpg'), // 注意:请指定文件名
]
)->toArray();
$response = $api->post('cgi-bin/media/upload?type=image', $options);
```
#### 简化写法 6.4.0+
上面的两种传法都可以简写为下面的方式:
```php
// withFile(string $localPath, string $formName = 'file', string $filename = null)
$media = $client->withFile($path, 'media')->post('cgi-bin/media/upload?type=image');
// withFileContents(string $contents, string $formName = 'file', string $filename = null)
$media = $client->withFileContents($contents, 'media', 'filename.png')->post('cgi-bin/media/upload?type=image');
```
## 自定义 access_token
自定义 Access Token 需要实现接口 `EasyWeChat\Kernel\Contracts\AccessToken`:
```php
class MyAccessToken implements EasyWeChat\Kernel\Contracts\AccessToken
{
public function getToken(): string
{
// 你的逻辑
return 'your token';
}
public function toQuery(): array
{
return ['access_token' => $this->getToken()];
}
}
```
```php
$client->withAccessToken(new MyAccessToken());
$client->get('xxxx');
$client->post('xxxx');
//...
```
## 预置参数的传递 6.4.0+
在调用 API 的时候难免有的需要传递账号的一些信息,尤其是支付相关的 API,例如[查询订单](https://pay.weixin.qq.com/doc/v3/merchant/4012791858):
```php
$client->get('v3/pay/transactions/id/1217752501201407033233368018', [
'mchid' => $app->getAccount()->getMchid(),
]);
```
不得不把商户号这种基础信息再读取传递一遍,比较麻烦,设计了如下的简化方案:
```php
$client->withMchId()->get('endpoint');
// 结果:endpoint?mchid=xxxxx
```
注意:`withMchId` 默认产生的结果为:`mch_id`,因为微信支付官方的各种不统一, 可能有的场景你需要的不是 `mch_id` 而是 `mchid`, 可以通过 `withMchIdAs('mchid')` 来指定,比如:
```php
$client->withMchIdAs('mchid')->get('v3/pay/transactions/id/1217752501201407033233368018');
// 结果:v3/pay/transactions/id/1217752501201407033233368018?mchid=xxxxx
```
原理就是 `with` + `配置 key`:
> 注意: 如果配置key含有下划线的,如 `app_id` 应该转换为大写 `withAppId`
```php
$client->withAppId()->post('/path/to/resources', [...]);
$client->withAppId()->withMchid()->post('/path/to/resources', [...]);
```
也可以自定义值:
```php
$client->withAppId('12345678')->post('/path/to/resources', [...]);
// or
$client->with('appid', '123456')->post('/path/to/resources', [...]);
```
还可以设置别名:把 `appid` 作为参数 `mch_appid` 值使用:
```php
$client->withAppIdAs('mch_appid')->post('/path/to/resources', [...]);
```
其它通用方法:
```php
$client->with('appid')->post(...)
$client->with(['appid', 'mchid'])->post(...)
$client->with(['appid' => '1234565', 'mchid'])->post(...)
```
---
## 处理响应
API Client 基于 [symfony/http-client](https://github.com/symfony/http-client) 实现,你可以通过以下方式对响应值进行访问:
### 异常处理 6.3.0+
当请求失败,例如状态码不为 200 时,默认访问响应内容都会抛出异常:
```php
$response->getContent(); // 这里会抛出异常
```
如果你不希望默认抛出异常,而希望自己处理,可以在配置文件指定 `http.throw` 参数为 `false`:
```php
$config = [
//...
'http' => [
'throw' => false,
//...
],
];
```
这样,你就可以在调用 API 时,自己处理异常:
```php
$options = [
'query' => [
'openid' => 'oDF3iY9ffA-hqb2vVvbr7qxf6A0Q',
]
];
$response = $api->get('/cgi-bin/user/get', $options);
if ($response->isFailed()) {
// 出错了,处理异常
}
return $response;
```
或者不改变默认配置的情况下,在调用请求时单独设置`throw(false)`,若该请求失败,也可以自己处理异常。
```php
// $options 同上文,这里省略
$response = $api->get('/cgi-bin/user/get', $options)->throw(false);
if ($response->isFailed()) {
// 出错了,处理异常
}
return $response;
```
### 数组式访问
EasyWeChat 增强了 API 响应对象,比如增加了数组式访问,你可以不用每次 `toArray` 后再取值,更加便捷美观:
```php
$response = $api->get('/foo/bar');
$response['foo']; // "bar"
isset($response['foo']); // true
```
### 获取状态码
```php
$response->getStatusCode();
// 200
```
### 判断业务是否成功/失败 6.3.0+
比如状态码是 200,但是公众号接口返回 40029 code 错误:
```php
$response->isSuccessful(); // false
$response->isFailed(); // true
```
### 获取响应头
```php
$response->getHeaders();
// ['content-type' => ['application/json;encoding=utf-8'], '...']
$response->getHeader('content-type');
// ['application/json;encoding=utf-8']
$response->getHeaderLine('content-type');
// 'application/json;encoding=utf-8'
```
### 获取响应内容
```php
$response->getContent();
$response->getContent(false); // 失败不抛出异常
// {"foo":"bar"}
// 获取 json 转换后的数组格式
$response->toArray();
$response->toArray(false); // 失败不抛出异常
// ["foo" => "bar"]
// 获取 json
$response->toJson();
$response->toJson(false);
// {"foo":"bar"}
// 将内容转换成流返回
$response->toStream();
$response->toStream(false); // 失败不抛出异常
```
### 转换为 PSR-7 Response 6.6.0+
如果你希望直接将 API 响应转换成 [PSR-7 规范](https://www.php-fig.org/psr/psr-7/) Response,可以使用 `toPsrResponse` 方法:
```php
$psrResponse = $response->toPsrResponse();
```
比如在 Laravel 中就可以这样使用:
```php
return $response->toPsrResponse();
```
### 保存到文件 6.3.0+
你可以方便的将内容直接存储到文件:
```php
$path = $response->saveAs('/path/to/file.jpg');
// /path/to/file.jpg
```
### 转换为 Data URLs 6.3.0+
你可以将内容转换为[Data URLs](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/Data_URIs)
```php
$dataUrl = $response->toDataUrl();
// data:image/png,%89PNG%0D%0A...
```
### 获取其他上下文信息
如:"response_headers", "redirect_count", "start_time", "redirect_url" 等:
```php
$httpInfo = $response->getInfo();
// 获取指定信息
$startTime = $response->getInfo('start_time');
// 获取请求日志
$httpLogs = $response->getInfo('debug');
```
:book: 更多使用请参考: [HTTP client: Processing Responses](https://symfony.com/doc/current/http_client.html#processing-responses)
---
## 异步请求
所有的请求都是异步的,当你第一次访问 `$response` 时才会真正的请求,比如:
```php
// 这段代码会立即执行,并不会发起网络请求
$response = $api->postJson('/cgi-bin/user/info/updateremark', [
"openid" => "oDF3iY9ffA-hqb2vVvbr7qxf6A0Q",
"remark" => "pangzi"
]);
// 当你尝试访问 $response 的信息时,才会发起请求并等待返回
$contentType = $response->getHeaders()['content-type'][0];
// 尝试获取响应内容将阻塞执行,直到接收到完整的响应内容
$content = $response->getContent();
```
## 并行请求
由于请求天然是异步的,那么你可以很简单实现并行请求:
```php
$responses = [
$api->get('/cgi-bin/user/get'),
$api->post('/cgi-bin/user/info/updateremark', ['body' => ...]),
$api->post('/cgi-bin/user/message/custom/send', ['body' => ...]),
];
// 访问任意一个 $response 时将执行并发请求:
foreach ($responses as $response) {
$content = $response->getContent();
// ...
}
```
当然你也可以给每个请求分配名字独立访问:
```php
$responses = [
'users' => $api->get('/cgi-bin/user/get'),
'remark' => $api->post('/cgi-bin/user/info/updateremark', ['body' => ...]),
'message' => $api->post('/cgi-bin/user/message/custom/send', ['body' => ...]),
];
// 访问任意一个 $response 时将执行并发请求:
$responses['users']->toArray();
```
## 失败重试 6.1.0+
默认在公众号、小程序开启了重试机制,你可以通过全局配置或者手动开启重试特性。
> 🚨 不建议在支付模块使用重试功能,因为一旦重试导致支付数据异常,可能造成无法挽回的损失。
### 方式一:全局配置
在支持重试的模块里增加如下配置可以完成重试机制的全局启用:
```php
'http' => [
//...
'retry' => true, // 使用默认配置
// 'retry' => [
// // 仅以下状态码重试
// 'status_codes' => [429, 500]
// 'max_retries' => 3
// // 请求间隔 (毫秒)
// 'delay' => 1000,
// // 如果设置,每次重试的等待时间都会增加这个系数
// // (例如. 首次:1000ms; 第二次: 3 * 1000ms; etc.)
// 'multiplier' => 0.1
// ],
],
```
### 方式二:手动开启
如果你不想使用基于配置的全局重试机制,你可以使用 `HttpClient::retry()` 方法来开启失败重试能力:
```php
$app->getClient()->retry()->get('/foo/bar');
```
当然,你可以在 `retry` 配置中自定义重试的配置,如下所示:
```php
$app->getClient()->retry([
'max_retries' => 2,
//...
])->get('/foo/bar');
```
### 自定义重试策略
如果觉得参数不能满足需求,你还可以自己实现 [`Symfony\Component\HttpClient\RetryStrategyInterface`](https://github.com/symfony/symfony/blob/6.1/src/Symfony/Component/HttpClient/Retry/RetryStrategyInterface.php) 接口来自定义重试策略,然后调用 `retryUsing` 方法来使用它。
> 💡 建议继承基类来拓展,以实现默认重试类的基础功能。
```php
class MyRetryStrategy extends \Symfony\Component\HttpClient\Retry\GenericRetryStrategy
{
public function shouldRetry(AsyncContext $context, ?string $responseContent, ?TransportExceptionInterface $exception): ?bool
{
// 你的自定义逻辑
// if (...) {
// return false;
// }
return parent::shouldRetry($context, $responseContent, $exception);
}
}
```
使用自定义重试策略:
```php
$app->getClient()->retryUsing(new MyRetryStrategy())->get('/foo/bar');
```
## 更多使用方法
:book: 更多使用请参考:[symfony/http-client](https://github.com/symfony/http-client)
================================================
FILE: docs/src/6.x/contributing.md
================================================
# 贡献代码
## 开发
我们欢迎广大开发者贡献大家的智慧,让我们共同让它变得更完美.
### 开始之前
请严格遵循以下代码标准:
> - [PSR-12](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-12-extended-coding-style-guide.md).
> - 使用 4 个空格作为缩进。
### 流程
1. Fork [w7corp/easywechat](https://github.com/w7corp/easywechat) 并 Clone 到本地.
2. 创建新的分支:
```shell:no-line-numbers
git checkout -b new_feature
```
3. 编写代码。
4. Push 到你的分支:
```shell:no-line-numbers
git push origin new_feature
```
5. 创建 Pull Request 并描述你完成的功能或者做出的修改。
> 注意:注释请使用英文
## 更新文档
我们的文档也是开源的,源代码在 [w7corp/EasyWeChat/docs](https://github.com/w7corp/easywechat/tree/6.x/docs)
### 流程
1. Fork [w7corp/EasyWeChat](https://github.com/w7corp/easywechat)
2. Clone 到你的电脑:
```shell:no-line-numbers
git clone https://github.com//site.git
cd docs
```
3. 创建新的分支,编辑文档
4. Push 到你的分支。
5. 创建 Pull Request 并描述你完成的功能或者做出的修改。
## 报告 Bug
当你在使用过程中遇到问题,请查阅 [疑难解答](troubleshooting.md) 或者在这里提问 [GitHub](https://github.com/w7corp/easywechat/issues). 如果还是不能解决你的问题,请到 GitHub 联系我们。
[w7corp/easywechat]: https://github.com/w7corp/easywechat
================================================
FILE: docs/src/6.x/index.md
================================================
> 👋🏼 您当前浏览的文档为 6.x,其它版本的文档请参考:[5.x](/5.x/)、[4.x](/4.x/)、[3.x](/3.x/)
# EasyWeChat
EasyWeChat 是一个开源的 [微信](http://www.wechat.com) 非官方 SDK。安装非常简单,因为它是一个标准的 [Composer](https://getcomposer.org/) 包,这意味着任何满足下列安装条件的 PHP 项目支持 Composer 都可以使用它。
## 环境需求
- PHP >= 8.0
- [PHP cURL 扩展](http://php.net/manual/en/book.curl.php)
- [PHP OpenSSL 扩展](http://php.net/manual/en/book.openssl.php)
- [PHP SimpleXML 扩展](http://php.net/manual/en/book.simplexml.php)
- [PHP fileinfo 拓展](http://php.net/manual/en/book.fileinfo.php)
## 安装
::: warning
阿里云的 Composer 源已经停止维护,请停止使用,或更换官方源,或者[腾讯软件源](https://mirrors.tencent.com/help/composer.html)
:::
```shell:no-line-numbers
composer require w7corp/easywechat:^6.17
```
## 使用
从 6.x 起,EasyWeChat 依然保持了它开箱即用的特性,同样只需要传入一个配置,初始化一个模块实例即可:
```php
use EasyWeChat\OfficialAccount\Application;
$config = [
'app_id' => 'wx3cf0f39249eb0exx',
'secret' => 'f1c242f4f28f735d4687abb469072axx',
'token' => 'easywechat',
'aes_key' => '' // 明文模式请勿填写 EncodingAESKey
//...
];
$app = new Application($config);
```
在创建实例后,所有的方法都几乎可以有 IDE 自动补全,当然,建议先阅读各模块的文档了解一下它们的区别,这里我们以调用公众号获取用户资料为例:
```php
$response = $app->getClient()->get("/cgi-bin/user/info?openid={$openid}&lang=zh_CN");
# 查看返回结果
var_dump($response->toArray());
```
## 开始之前
在你动手写代码之前,建议您首先阅读以下内容:
- [关于 6.x](./introduction.md)
- [API 调用](./client.md)
## 参与贡献
我们欢迎广大开发者贡献大家的智慧,让我们共同让它变得更完美。您可以在 GitHub 上提交 Pull Request,我们会尽快审核并公布。更多信息请参考 [贡献指南](contributing.md)。
## 开发者交流群
[EasyWeChat SDK 交流群](http://shang.qq.com/wpa/qunwpa?idkey=b4dcf3ec51a7e8c3c3a746cf450ce59895e5c4ec4fbcb0f80c2cd97c3c6e63e9) ID: 319502940
================================================
FILE: docs/src/6.x/introduction.md
================================================
---
aside: false
prev:
text: 参与贡献
link: ./contributing
---
# 版本说明
如果您是之前的老版本用户,你就会发现,6.x 版本是没办法从旧版轻松升级的,当然如果非必要,我也不建议你去动已有的项目升级。
## 关于 6.x
6.x 和之前的版本设计风格完全不一样,可以说是一个完全重写的版本,其中最大的变化点是:
### 不再封装业务接口
从 6.x 起 SDK 中不再内置具体业务的接口,仅封装底层基础部分,如认证、授权和 API 客户端。为什么不再封装业务接口,主要有以下几个原因:
##### 二次封装的学习成本
从使用者角度,首先需要了解微信的接口,然后再到 SDK 去寻找对应二次封装的新名称和新的用法,为啥会是新的名称呢?因为微信的接口起名太随意,很多名字无法表意或者有歧义,所以在以前的版本中我们精心设计了新的名字来掩盖这个问题,但是起名这件事情,相信写过代码的同学都知道,它是非常困难的,尤其微信这种杂乱的接口系统,越到后面越词穷。所以二次封装,不仅增加了用户的使用学习成本,也同时增加了 SDK 的封装成本。
##### 更新时效性不足
当有新接口,或者接口变化的时候,SDK 很难做到及时的更新,毕竟用爱发电的人也要工作和生活,大部分都需要好久才会有空把它同步更新过来,即使我已经很努力去尽可能做到快速更新,但还是无法满足使用者的诉求。虽然 SDK 在设计之初就已经考虑过这个问题提供了底层直接调用接口地址的能力,但很多人不知道。
### 去容器化设计
从 3.x 起我们重写了整个 SDK 的架构,引入了 [silexphp/Pimple](https://github.com/silexphp/Pimple) 作为服务容器,将各模块装载到服务容器,随取随用,一直沿用到 5.x。
6.x 开始,因为也不需要再二次封装业务接口,容器存在的必要性就不大了。最终去掉了容器这一层,将各个模块类以纯粹的独立类存在,使用依赖注入的模式传入需要的依赖对象,方便有自定义需求或者特殊运行环境的同学使用自己的类做替换和更方便的生命周期管理。为了方便大部分自定义需求少的使用者场景,在各生态模块外层,提供了工厂类以便于最小成本的完成开发对接。
### 几乎 100% 的自定义能力支持
在继续保持开箱即用的能力下,在 6.x 中你几乎可以做到任何模块的替换,每一个模块都以接口形式依赖,所以你可以轻松的替换任何一个你不满意的模块。当然也包括底层的 Http Client。
## 感谢
感谢所有 EasyWeChat 用户的热爱和支持,更要感谢所有的贡献者,因为爱好产生了 EasyWeChat,因为大家的热爱它才成为了今天拥有无数使用者的 EasyWeChat。希望在未来的路上我们能保持初心,一起努力,一起成长。
- [@overtrue](https://github.com/overtrue) 2022/02/25
### 感谢可爱的贡献者们
================================================
FILE: docs/src/6.x/logging.md
================================================
# 自定义 HTTP 客户端日志
在 6.x 版本中,虽然移除了默认的日志功能,但用户仍然可以通过自定义 HTTP 客户端来实现请求和响应的日志记录。
## 基本用法
所有的 Application 类都实现了 `LoggerAwareInterface`,你可以设置一个日志记录器,然后创建一个支持日志的 HTTP 客户端:
```php
use EasyWeChat\OfficialAccount\Application;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Symfony\Component\HttpClient\HttpClient;
use Psr\Log\LoggerAwareInterface;
$config = [
'app_id' => 'your-app-id',
'secret' => 'your-app-secret',
// 其他配置...
];
$app = new Application($config);
// 创建一个日志记录器
$logger = new Logger('easywechat');
$logger->pushHandler(new StreamHandler('/path/to/your/logfile.log', Logger::DEBUG));
// 设置日志记录器到应用实例
$app->setLogger($logger);
// 创建支持日志的 HTTP 客户端
$httpClient = HttpClient::create();
// 如果 HTTP 客户端支持 LoggerAwareInterface,将自动设置日志记录器
if ($httpClient instanceof LoggerAwareInterface) {
$httpClient->setLogger($logger);
}
// 设置自定义 HTTP 客户端
$app->setHttpClient($httpClient);
```
## 使用装饰器模式的日志客户端
你也可以创建一个装饰器来包装现有的 HTTP 客户端,添加日志功能:
```php
use Psr\Log\LoggerInterface;
use Psr\Log\LoggerAwareInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
class LoggingHttpClient implements HttpClientInterface, LoggerAwareInterface
{
private HttpClientInterface $client;
private ?LoggerInterface $logger = null;
public function __construct(HttpClientInterface $client)
{
$this->client = $client;
}
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
if ($this->client instanceof LoggerAwareInterface) {
$this->client->setLogger($logger);
}
}
public function request(string $method, string $url, array $options = []): ResponseInterface
{
// 记录请求日志
if ($this->logger) {
$this->logger->info('HTTP Request', [
'method' => $method,
'url' => $url,
'options' => $this->sanitizeOptions($options),
]);
}
$startTime = microtime(true);
try {
$response = $this->client->request($method, $url, $options);
// 记录响应日志
if ($this->logger) {
$duration = microtime(true) - $startTime;
$this->logger->info('HTTP Response', [
'method' => $method,
'url' => $url,
'status_code' => $response->getStatusCode(),
'duration' => round($duration * 1000, 2) . 'ms',
]);
}
return $response;
} catch (\Throwable $e) {
// 记录错误日志
if ($this->logger) {
$duration = microtime(true) - $startTime;
$this->logger->error('HTTP Request Failed', [
'method' => $method,
'url' => $url,
'error' => $e->getMessage(),
'duration' => round($duration * 1000, 2) . 'ms',
]);
}
throw $e;
}
}
public function stream($responses, float $timeout = null): iterable
{
return $this->client->stream($responses, $timeout);
}
private function sanitizeOptions(array $options): array
{
// 移除敏感信息,如密码、密钥等
if (isset($options['auth'])) {
$options['auth'] = '[HIDDEN]';
}
if (isset($options['headers']['Authorization'])) {
$options['headers']['Authorization'] = '[HIDDEN]';
}
return $options;
}
}
```
## 使用自定义日志客户端
```php
use EasyWeChat\OfficialAccount\Application;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Symfony\Component\HttpClient\HttpClient;
$config = [
'app_id' => 'your-app-id',
'secret' => 'your-app-secret',
];
$app = new Application($config);
// 创建日志记录器
$logger = new Logger('easywechat-http');
$logger->pushHandler(new StreamHandler('/var/log/easywechat-http.log', Logger::DEBUG));
// 创建装饰后的 HTTP 客户端
$baseClient = HttpClient::create();
$loggingClient = new LoggingHttpClient($baseClient);
$loggingClient->setLogger($logger);
// 设置到应用实例
$app->setHttpClient($loggingClient);
// 现在所有的 HTTP 请求都会被记录
$accessToken = $app->getAccessToken()->getToken();
```
## 日志输出示例
使用上述配置后,你的日志文件将包含类似以下的内容:
```
[2024-01-01 10:00:00] easywechat-http.INFO: HTTP Request {"method":"GET","url":"https://api.weixin.qq.com/cgi-bin/token","options":{"query":{"grant_type":"client_credential","appid":"your-app-id","secret":"[HIDDEN]"}}}
[2024-01-01 10:00:01] easywechat-http.INFO: HTTP Response {"method":"GET","url":"https://api.weixin.qq.com/cgi-bin/token","status_code":200,"duration":"156.75ms"}
```
## 注意事项
1. **敏感信息处理**:在记录日志时,请务必过滤掉敏感信息,如 `secret`、`access_token`、`password` 等。
2. **性能影响**:启用详细的 HTTP 日志记录可能会对性能产生影响,特别是在高并发场景下。建议在生产环境中适当调整日志级别。
3. **日志轮转**:确保配置适当的日志轮转策略,避免日志文件过大。
4. **自动设置**:当你在应用实例上设置日志记录器后,如果 HTTP 客户端实现了 `LoggerAwareInterface`,框架会自动将日志记录器设置到 HTTP 客户端上。
================================================
FILE: docs/src/6.x/mini-app/config.md
================================================
---
title: 配置 | 微信小程序开发
aside: false
---
# 配置
下面是一个完整的配置样例:
> 不建议你在配置的时候弄这么多,用到啥就配置啥才是最好的,因为大部分用默认值即可。
```php
[
/**
* 账号基本信息,请从微信公众平台/开放平台获取
*/
'app_id' => 'your-app-id', // AppID
'secret' => 'your-app-secret', // AppSecret
'token' => 'your-token', // Token
'aes_key' => '', // EncodingAESKey,兼容与安全模式下请一定要填写!!!
/**
* 是否使用 Stable Access Token
* 默认 false
* https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getStableAccessToken.html
* true 使用 false 不使用
*/
'use_stable_access_token' => false,
/**
* 接口请求相关配置,超时时间等,具体可用参数请参考:
* https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
*/
'http' => [
'throw' => true, // 状态码非 200、300 时是否抛出异常,默认为开启
'timeout' => 5.0,
// 'base_uri' => 'https://api.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用,根据不同的模块配置不同的 uri
'retry' => true, // 使用默认重试配置
// 'retry' => [
// // 仅以下状态码重试
// 'status_codes' => [429, 500]
// // 最大重试次数
// 'max_retries' => 3,
// // 请求间隔 (毫秒)
// 'delay' => 1000,
// // 如果设置,每次重试的等待时间都会增加这个系数
// // (例如. 首次:1000ms; 第二次: 3 * 1000ms; etc.)
// 'multiplier' => 3
// ],
],
]
```
> :heart: 安全模式下请一定要填写 `aes_key`
================================================
FILE: docs/src/6.x/mini-app/examples.md
================================================
---
aside: false
title: 微信小程序使用代码示例
---
# 示例
> 👏🏻 欢迎点击本页下方 "帮助我们改善此页面!" 链接参与贡献更多的使用示例!
生成小程序码(wxacode.getUnlimited)
[官方文档:wxacode.getUnlimited](https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html)
```php
try {
$response = $app->getClient()->postJson('/wxa/getwxacodeunlimit', [
'scene' => '123',
'page' => 'pages/index/index',
'width' => 430,
'check_path' => false,
]);
$path = $response->saveAs('/tmp/wxacode-123.png');
} catch (\Throwable $e) {
// 失败
echo $e->getMessage();
}
```
获取手机号(phonenumber.getPhoneNumber)
[官方文档:phonenumber.getPhoneNumber](https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/phonenumber/phonenumber.getPhoneNumber.html)
```php
// routes/api.php
use EasyWeChat\MiniApp\Application;
Route::post('getPhoneNumber', function () {
// $app 实例化步骤这里省略
$data = [
'code' => (string) request()->get('code'),
];
return $app->getClient()->postJson('wxa/business/getuserphonenumber', $data);
}
}
```
================================================
FILE: docs/src/6.x/mini-app/index.md
================================================
# 小程序
> 🚨 使用前建议熟读 [微信官方文档: 小程序](https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html)
常用的配置参数会比较少,因为除非你有特别的定制,否则基本上默认值就可以了:
```php
use EasyWeChat\MiniApp\Application;
$config = [
'app_id' => 'wx3cf0f39249eb0exx',
'secret' => 'f1c242f4f28f735d4687abb469072axx',
'token' => 'easywechat',
'aes_key' => '......',
/**
* 接口请求相关配置,超时时间等,具体可用参数请参考:
* https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
*/
'http' => [
'throw' => true, // 状态码非 200、300 时是否抛出异常,默认为开启
'timeout' => 5.0,
// 'base_uri' => 'https://api.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用,根据不同的模块配置不同的 uri
'retry' => true, // 使用默认重试配置
// 'retry' => [
// // 仅以下状态码重试
// 'status_codes' => [429, 500]
// // 最大重试次数
// 'max_retries' => 3,
// // 请求间隔 (毫秒)
// 'delay' => 1000,
// // 如果设置,每次重试的等待时间都会增加这个系数
// // (例如. 首次:1000ms; 第二次: 3 * 1000ms; etc.)
// 'multiplier' => 3
// ],
],
];
$app = new Application($config);
```
:book: 更多配置项请参考:[配置](config.md)
## API
Application 就是一个工厂类,所有的模块都是从 `$app` 中访问,并且几乎都提供了协议和 setter 可自定义修改。
### 服务端
服务端模块封装了服务端相关的便捷操作,隐藏了部分复杂的细节,基于中间件模式可以更方便的处理消息推送和服务端验证。
```php
$app->getServer();
```
:book: 更多说明请参阅:[服务端使用文档](server.md)
### API Client
封装了多种模式的 API 调用类,你可以选择自己喜欢的方式调用小程序任意 API,默认自动处理了 access_token 相关的逻辑。
```php
$app->getClient();
```
:book: 更多说明请参阅:[API 调用](../client.md)
### 配置
```php
$config = $app->getConfig();
```
你可以轻松使用 `$config->get($key, $default)` 读取配置,或使用 `$config->set($key, $value)` 在调用前修改配置项。
### AccessToken
access_token 是小程序 API 调用的必备条件,如果你想获取它的值,你可以通过以下方式拿到当前的 access_token:
```php
$accessToken = $app->getAccessToken();
$accessToken->getToken(); // string
```
当然你也可以使用自己的 AccessToken 类:
```php
$accessToken = new MyCustomAccessToken();
$app->setAccessToken($accessToken)
```
### 小程序账户
小程序账号类,提供一系列 API 获取小程序的基本信息:
```php
$account = $app->getAccount();
$account->getAppId();
$account->getSecret();
$account->getToken();
$account->getAesKey();
```
### 工具类
对于一些高频接口,我们提供了一个简单的工具类来简化大家的开发工作,可以通过下面的方法获取:
```php
$utils = $app->getUtils();
```
:book: 更多说明请参阅:[工具类](utils.md)
================================================
FILE: docs/src/6.x/mini-app/server.md
================================================
---
title: 服务端 | 微信小程序开发
aside: false
---
# 服务端
小程序的服务端推送和公众号一样,请参考:[公众号:服务端](../official-account/server.md)
================================================
FILE: docs/src/6.x/mini-app/utils.md
================================================
# 工具类 6.3.0+
为了简化大家对于一些高频基础的操作,我们提供了一些简单的工具类。你可以通过下面的方法获取工具类:
```php
$utils = $app->getUtils();
```
## 工具方法
### code2session
```php
$response = $utils->codeToSession($code);
// {
// "openid": "o6_bmjrPTlm6_2sgVt7hMZOPxxxx",
// "session_key": "tiihtNczf5v6AKRyjwExxxx=",
// "unionid": "o6_bmasdasdsad6_2sgVt7hMZOxxxx",
// "errcode": 0,
// "errmsg": "ok"
//}
```
### 解密会话信息
```php
$session = $utils->decryptSession($sessionKey, $iv, $encryptedData);
//{
// "openId": "oGZUI0egBJY1zhBYw2KhdUfwVJJE",
// "nickName": "Band",
// "gender": 1,
// "language": "zh_CN",
// "city": "Guangzhou",
// "province": "Guangdong",
// "country": "CN",
// "avatarUrl": "http://wx.qlogo.cn/mmopen/vi_32/aSKcBBPpibyKNicHNTMM0qJVh8Kjgiak2AHWr8MHM4WgMEm7GFhsf8OYrySdbvAMvTsw3mo8ibKicsnfN5pRjl1p8HQ/0",
// "unionId": "ocMvos6NjeKLIBqg5Mr9QjxrP1FA",
// "watermark": {
// "timestamp": 1477314187,
// "appid": "wx4f4bc4dec97d474b"
// }
//}
```
### 获取手机号
获取用户绑定的手机号,需先调用 `wx.login` 接口,然后通过 `getPhoneNumber` 方法获取用户手机号。
参考文档:https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/phone-number/getPhoneNumber.html
```php
$response = $utils->getPhoneNumber($code);
//{
// "errcode": 0,
// "errmsg": "ok",
// "phone_info": {
// "phoneNumber": "13800138000",
// "purePhoneNumber": "13800138000",
// "countryCode": "86",
// "watermark": {
// "timestamp": 1637744274,
// "appid": "xxxx"
// }
// }
//}
```
================================================
FILE: docs/src/6.x/oauth.md
================================================
# 网页授权
## 关于 OAuth2.0
OAuth 是一个关于授权(authorization)的开放网络标准,在全世界得到广泛应用,目前的版本是 2.0 版。
> 摘自:[RFC 6749](https://datatracker.ietf.org/doc/rfc6749/?include_text=1)
步骤解释:
(A)用户打开客户端以后,客户端要求用户给予授权。
(B)用户同意给予客户端授权。
(C)客户端使用上一步获得的授权,向认证服务器申请令牌。
(D)认证服务器对客户端进行认证以后,确认无误,同意发放令牌。
(E)客户端使用令牌,向资源服务器申请获取资源。
(F)资源服务器确认令牌无误,同意向客户端开放资源。
关于 OAuth 协议我们就简单了解到这里,如果还有不熟悉的同学,请 [Google 相关资料](https://www.google.com.hk/?gws_rd=ssl#safe=strict&q=OAuth2)
## 微信 OAuth
在微信里的 OAuth 其实有两种:[公众平台网页授权获取用户信息](http://mp.weixin.qq.com/wiki/9/01f711493b5a02f24b04365ac5d8fd95.html)、[开放平台网页登录](https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN)。
它们的区别有两处,授权地址不同,`scope` 不同。
> - **公众平台网页授权获取用户信息**
**授权 URL**: `https://open.weixin.qq.com/connect/oauth2/authorize`
**Scopes**: `snsapi_base` 与 `snsapi_userinfo`
> - **开放平台网页登录**
**授权 URL**: `https://open.weixin.qq.com/connect/qrconnect`
**Scopes**: `snsapi_login`
他们的逻辑都一样:
1. 用户尝试访问一个我们的业务页面,例如: `/user/profile`
2. 如果用户已经登录,则正常显示该页面
3. 系统检查当前访问的用户并未登录(从 session 或者其它方式检查),则跳转到**跳转到微信授权服务器**(上面的两种中一种**授权 URL** ),并告知微信授权服务器我的**回调 URL(redirect_uri=callback.php)**,此时用户看到蓝色的授权确认页面(`scope` 为 `snsapi_base` 时不显示)
4. 用户点击确定完成授权,浏览器跳转到**回调 URL**: `callback.php` 并带上 `code`: `?code=CODE&state=STATE`。
5. 在 `callback.php` 中得到 `code` 后,通过 `code` 再次向微信服务器请求得到 **网页授权 access_token** 与 `openid`
6. 你可以选择拿 `openid` 去请求 API 得到用户信息(可选)
7. 将用户信息写入 SESSION。
8. 跳转到第 3 步写入的 `intend_url` 页面(`/user/profile`)。
> 看懵了?没事,使用 SDK,你不用管这么多。:smile:
>
> 注意,上面的第 3 步:redirect_uri=callback.php 实际上我们会在 `callback.php` 后面还会带上授权目标页面 `user/profile`,所以完整的 `redirect_uri` 应该是下面的这样的 PHP 去拼出来:`'redirect_uri='.urlencode('callback.php?target=user/profile')`
> 结果:redirect_uri=callback.php%3Ftarget%3Duser%2Fprofile
## 逻辑组成
从上面我们所描述的授权流程来看,我们至少有 3 个页面:
1. **业务页面**,也就是需要授权才能访问的页面。
2. **发起授权页**,此页面其实可以省略,可以做成一个中间件,全局检查未登录就发起授权。
3. **授权回调页**,接收用户授权后的状态,并获取用户信息,写入用户会话状态(SESSION)。
## 开始之前
在开始之前请一定要记住,先登录公众号后台,找到**边栏 “开发”** 模块下的 **“接口权限”**,点击 **“网页授权获取用户基本信息”** 后面的修改,添加你的网页授权域名。
> 如果你的授权地址为:`http://www.abc.com/xxxxx`,那么请填写 `www.abc.com`,也就是说请填写与网址匹配的域名,前者如果填写 `abc.com` 是通过不了的。
### 发起授权
```php
$redirectUrl = $oauth->scopes(['snsapi_userinfo'])->redirect();
// 指定回调 URL,比如设置回调 URL 为当前页面
$redirectUrl = $oauth->scopes(['snsapi_userinfo'])->redirect($request->fullUrl());
```
返回值 `$redirectUrl` 是一个字符串 URL,请自行使用框架的跳转方法实现跳转,PHP 原生写法:
```php
header("Location: {$redirectUrl}");
```
在 [Laravel](http://laravel.com) 框架中控制器方法是要求返回响应值:
```php
return \redirect($redirectUrl);
```
### 处理授权回调
```php
$code = "微信回调URL携带的 code"; // $_GET['code']
$user = $oauth->userFromCode($code);
```
返回的 `$user` 是 [Overtrue\Socialite\User](https://github.com/overtrue/socialite/blob/master/src/User.php) 对象,你可以从该对象拿到[更多的信息](https://github.com/overtrue/socialite#user-interface)。
**$user 可以用的方法**
- `$user->getId(); ` 对应微信的 `openid`
- `$user->getNickname(); ` 对应微信的 `nickname`
- `$user->getName(); ` 对应微信的 `nickname`
- `$user->getAvatar(); ` 头像地址
- `$user->getRaw(); ` 原始 API 返回的结果
- `$user->getAccessToken(); ` `access_token`
- `$user->getRefreshToken(); ` `refresh_token`
- `$user->getExpiresIn(); ` `expires_in`,Access Token 过期时间
- `$user->getTokenResponse(); ` 返回 `access_token` 时的响应值
> `$user` 里没有`openid`, `$user->id` 便是 `openid`.
> 如果你想拿微信返回给你的原样的全部信息,请使用:$user->getRaw();
当 `scope` 为 `snsapi_base` 时 `$oauth->userFromCode($code);` 对象里只有 `id`,没有其它信息。
## 网页授权实例
我们这里来用公众号原生 PHP 写法举个例子,`oauth_callback` 是我们的授权回调 URL (未 urlencode 编码的 URL), `user/profile` 是我们需要授权才能访问的页面,它的 PHP 代码如下:
```php
// http://easywechat.com/user/profile
'wx3cf0f39249eb0exx',
'secret' => 'f1c242f4f28f735d4687abb469072axx',
'token' => 'easywechat',
'aes_key' => '......'
//...
];
$app = new Application($config);
$oauth = $app->getOauth();
// 未登录
//callback_url 是授权回调的URL
if (empty($_SESSION['wechat_user'])) {
$_SESSION['intend_url'] = 'user/profile';
//生成完整的授权URL
$redirectUrl = $oauth->redirect('callback_url');
header("Location: {$redirectUrl}");
exit;
} else {
// 已经登录过,则从 session 中取授权者信息
$user = $_SESSION['wechat_user'];
// ...
}
```
**授权回调页**
用户授权完成后浏览器调回的 URL 逻辑:
```php
// http://easywechat.com/oauth_callback
'wx3cf0f39249eb0exx',
'secret' => 'f1c242f4f28f735d4687abb469072axx',
'token' => 'easywechat',
'aes_key' => '......'
//...
];
$app = new Application($config);
$oauth = $app->getOauth();
// 获取 OAuth 授权用户信息
$user = $oauth->userFromCode($_GET['code']);
$_SESSION['wechat_user'] = $user->toArray();
$targetUrl = empty($_SESSION['intend_url']) ? '/' : $_SESSION['intend_url'];
header('Location:'. $targetUrl); // 跳转回授权前的目标页面:user/profile
```
上面的例子呢都是基于 `$_SESSION` 来保持会话的,在微信客户端中,你也可以结合 Cookies 来存储,但是有效期平台不一样时间也不一样,好像 Android 的失效会快一些,不过基本也够用了。
## 参考阅读
- 本模块基于 [overtrue/socialite](https://github.com/overtrue/socialite/) 实现,更多的使用请阅读该扩展包文档。
- state 参数的使用: [overtrue/socialite/#state](https://github.com/overtrue/socialite/#state)
================================================
FILE: docs/src/6.x/official-account/config.md
================================================
---
title: 配置 | 微信公众号开发
aside: false
---
# 配置
下面是一个完整的配置样例:
> 不建议你在配置的时候弄这么多,用到啥就配置啥才是最好的,因为大部分用默认值即可。
```php
[
/**
* 账号基本信息,请从微信公众平台/开放平台获取
*/
'app_id' => 'your-app-id', // AppID
'secret' => 'your-app-secret', // AppSecret
'token' => 'your-token', // Token
'aes_key' => '', // EncodingAESKey,兼容与安全模式下请一定要填写!!!
/**
* 是否使用 Stable Access Token
* 默认 false
* https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/getStableAccessToken.html
* true 使用 false 不使用
*/
'use_stable_access_token' => false,
/**
* OAuth 配置
*
* scopes:公众平台(snsapi_userinfo / snsapi_base),开放平台:snsapi_login
* redirect_url:OAuth授权完成后的回调页地址
*/
'oauth' => [
'scopes' => ['snsapi_userinfo'],
'redirect_url' => '/examples/oauth_callback.php',
],
/**
* 接口请求相关配置,超时时间等,具体可用参数请参考:
* https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
*/
'http' => [
'timeout' => 5.0,
// 'base_uri' => 'https://api.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用,根据不同的模块配置不同的 uri
'retry' => true, // 使用默认重试配置
// 'retry' => [
// // 仅以下状态码重试
// 'status_codes' => [429, 500]
// // 最大重试次数
// 'max_retries' => 3,
// // 请求间隔 (毫秒)
// 'delay' => 1000,
// // 如果设置,每次重试的等待时间都会增加这个系数
// // (例如. 首次:1000ms; 第二次: 3 * 1000ms; etc.)
// 'multiplier' => 3
// ],
],
]
```
> :heart: 安全模式下请一定要填写 `aes_key`
================================================
FILE: docs/src/6.x/official-account/examples.md
================================================
---
aside: false
title: 微信公众号使用代码示例
---
# 示例
> 👏🏻 欢迎点击本页下方 "帮助我们改善此页面!" 链接参与贡献更多的使用示例!
webman 服务端验证消息
```php
get(), $request->post(), [], $request->cookie(), [], [], $request->rawBody());
$symfony_request->headers = new HeaderBag($request->header());
$app->setRequestFromSymfonyRequest($symfony_request);//必须替换服务端请求
//$app->setCache(new Psr16Cache(new RedisAdapter(Redis::connection()->client())));//根据需要替换缓存,access_token公众号的全局唯一接口调用凭据会使用该缓存存储
$server = $app->getServer();
$response = $server->serve();
return response($response->getBody()->getContents(), $response->getStatusCode(), $response->getHeaders());
}
}
```
Hyperf 服务端验证消息
##### 方法一:
* 安装包: `composer require limingxinleo/easywechat-classmap`
* 在授权回调地址中使用:
```php
setRequest($request); //必须替换服务端请求
}
if (method_exists($app, 'setCache')) {
$app->setCache(ApplicationContext::getContainer()->get(CacheInterface::class)); //可选,根据实际需求替换缓存
}
$server = $app->getServer();
$server->with(function ($message, \Closure $next) {
return '谢谢关注!';
// 你的自定义逻辑
// return $next($message);
});
return $server->serve();
}
}
```
##### 方法二:
* 安装包: `composer require pengxuxu/hyperf-easywechat6`
> 包里已替换了服务端请求和缓存,并封装了公众号、微信支付、小程序等外观。
* 参照文档在授权回调地址和其他场景中直接使用。
================================================
FILE: docs/src/6.x/official-account/index.md
================================================
# 公众号
> 🚨 使用前建议熟读 [微信官方文档: 公众号](https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html)
常用的配置参数会比较少,因为除非你有特别的定制,否则基本上默认值就可以了:
```php
use EasyWeChat\OfficialAccount\Application;
$config = [
'app_id' => 'wx3cf0f39249eb0exx',
'secret' => 'f1c242f4f28f735d4687abb469072axx',
'token' => 'easywechat',
'aes_key' => '', // 明文模式请勿填写 EncodingAESKey
/**
* OAuth 配置
*
* scopes:公众平台(snsapi_userinfo / snsapi_base),开放平台:snsapi_login
* redirect_url:OAuth授权完成后的回调页地址
*/
'oauth' => [
'scopes' => ['snsapi_userinfo'],
'redirect_url' => '/examples/oauth_callback.php',
],
/**
* 接口请求相关配置,超时时间等,具体可用参数请参考:
* https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
*/
'http' => [
'timeout' => 5.0,
// 'base_uri' => 'https://api.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用,根据不同的模块配置不同的 uri
'retry' => true, // 使用默认重试配置
// 'retry' => [
// // 仅以下状态码重试
// 'status_codes' => [429, 500]
// // 最大重试次数
// 'max_retries' => 3,
// // 请求间隔 (毫秒)
// 'delay' => 1000,
// // 如果设置,每次重试的等待时间都会增加这个系数
// // (例如. 首次:1000ms; 第二次: 3 * 1000ms; etc.)
// 'multiplier' => 3
// ],
],
];
$app = new Application($config);
```
:book: 更多配置项请参考:[配置](config.md)
## API
Application 就是一个工厂类,所有的模块都是从 `$app` 中访问,并且几乎都提供了协议和 setter 可自定义修改。
### 服务端
服务端模块封装了服务端相关的便捷操作,隐藏了部分复杂的细节,基于中间件模式可以更方便的处理消息推送和服务端验证。
```php
$app->getServer();
```
:book: 更多说明请参阅:[服务端使用文档](server.md)
### API Client
封装了多种模式的 API 调用类,你可以选择自己喜欢的方式调用公众号任意 API,默认自动处理了 access_token 相关的逻辑。
```php
$app->getClient();
```
:book: 更多说明请参阅:[API 调用](../client.md)
### 配置
```php
$config = $app->getConfig();
```
你可以轻松使用 `$config->get($key, $default)` 读取配置,或使用 `$config->set($key, $value)` 在调用前修改配置项。
### AccessToken
access_token 是公众号 API 调用的必备条件,如果你想获取它的值,你可以通过以下方式拿到当前的 access_token:
```php
$accessToken = $app->getAccessToken();
$accessToken->getToken(); // string
```
当然你也可以使用自己的 AccessToken 类:
```php
$accessToken = new MyCustomAccessToken();
$app->setAccessToken($accessToken)
```
### 网页授权
```php
$oauth = $app->getOAuth();
```
:book: 详情请参考:[网页授权](../oauth.md)
### 公众号账户
公众号账号类,提供一系列 API 获取公众号的基本信息:
```php
$account = $app->getAccount();
$account->getAppId();
$account->getSecret();
$account->getToken();
$account->getAesKey();
```
================================================
FILE: docs/src/6.x/official-account/message.md
================================================
# 消息
公众号消息分为 [**服务端被动回复消息**](https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Passive_user_reply_message.html) 和 [**客服消息**](https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html) 两个场景。
需要注意的是两个场景的消息虽然类似,但是结构却有些差异,比如服务端使用 XML 结构,而客服消息使用 JSON 结构,且同样类似的消息类型,结构和名称都有些许差异,在使用时请勿混淆。
## 服务端消息结构
当你接收到用户发来的消息时,可能会提取消息中的相关属性,参考:
请求消息基本属性(以下所有消息都有的基本属性):
```
- `ToUserName` 接收方帐号(该公众号 ID)
- `FromUserName` 发送方帐号(OpenID, 代表用户的唯一标识)
- `CreateTime` 消息创建时间(时间戳)
- `MsgId` 消息 ID(64位整型)
```
### 文本
```
- `MsgType` text
- `Content` 文本消息内容
```
### 图片
```
- `MsgType` image
- `MediaId` 图片消息媒体id,可以调用多媒体文件下载接口拉取数据。
- `PicUrl` 图片链接
```
### 语音
```
- `MsgType` voice
- `MediaId` 语音消息媒体id,可以调用多媒体文件下载接口拉取数据。
- `Format` 语音格式,如 amr,speex 等
- `Recognition` * 开通语音识别后才有
```
> 请注意,开通语音识别后,用户每次发送语音给公众号时,微信会在推送的语音消息 XML 数据包中,增加一个 `Recongnition` 字段
### 视频
```
- `MsgType` video
- `MediaId` 视频消息媒体id,可以调用多媒体文件下载接口拉取数据。
- `ThumbMediaId` 视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。
```
### 小视频
```
- `MsgType` shortvideo
- `MediaId` 视频消息媒体id,可以调用多媒体文件下载接口拉取数据。
- `ThumbMediaId` 视频消息缩略图的媒体id,可以调用多媒体文件下载接口拉取数据。
```
### 事件消息
```
- `MsgType` event
- `Event` 事件类型 (如:subscribe(订阅)、unsubscribe(取消订阅) ..., CLICK 等)
```
#### 扫描带参数二维码事件
```
- `EventKey` 事件KEY值,比如:qrscene_123123,qrscene_为前缀,后面为二维码的参数值
- `Ticket` 二维码的 ticket,可用来换取二维码图片
```
#### 上报地理位置事件
```
- `Latitude` 23.137466 地理位置纬度
- `Longitude` 113.352425 地理位置经度
- `Precision` 119.385040 地理位置精度
```
#### 自定义菜单事件
```
- `EventKey` 事件KEY值,与自定义菜单接口中KEY值对应,如:CUSTOM_KEY_001, www.qq.com
```
### 地理位置
```
- `MsgType` location
- `Location_X` 地理位置纬度
- `Location_Y` 地理位置经度
- `Scale` 地图缩放大小
- `Label` 地理位置信息
```
### 链接
```
- `MsgType` link
- `Title` 消息标题
- `Description` 消息描述
- `Url` 消息链接
```
### 文件
```
- `MsgType` file
- `Title` 文件名
- `Description` 文件描述,可能为null
- `FileKey` 文件KEY
- `FileMd5` 文件MD5值
- `FileTotalLen` 文件大小,单位字节
```
## 客服消息结构
### 发送文本消息
```json
{
"touser": "OPENID",
"msgtype": "text",
"text": {
"content": "Hello World"
}
}
```
### 图片消息
```json
{
"touser": "OPENID",
"msgtype": "image",
"image": {
"media_id": "MEDIA_ID"
}
}
```
### 语音消息
```json
{
"touser": "OPENID",
"msgtype": "voice",
"voice": {
"media_id": "MEDIA_ID"
}
}
```
### 视频消息
```json
{
"touser": "OPENID",
"msgtype": "video",
"video": {
"media_id": "MEDIA_ID",
"thumb_media_id": "MEDIA_ID",
"title": "TITLE",
"description": "DESCRIPTION"
}
}
```
### 音乐消息
```json
{
"touser": "OPENID",
"msgtype": "music",
"music": {
"title": "MUSIC_TITLE",
"description": "MUSIC_DESCRIPTION",
"musicurl": "MUSIC_URL",
"hqmusicurl": "HQ_MUSIC_URL",
"thumb_media_id": "THUMB_MEDIA_ID"
}
}
```
### 图文消息(点击跳转到外链)
```json
{
"touser": "OPENID",
"msgtype": "news",
"news": {
"articles": [
{
"title": "Happy Day",
"description": "Is Really A Happy Day",
"url": "URL",
"picurl": "PIC_URL"
}
]
}
}
```
### 图文消息(点击跳转到图文消息页面)
```json
{
"touser": "OPENID",
"msgtype": "mpnews",
"mpnews": {
"media_id": "MEDIA_ID"
}
}
```
### 菜单消息
```json
{
"touser": "OPENID",
"msgtype": "msgmenu",
"msgmenu": {
"head_content": "您对本次服务是否满意呢? "
"list": [
{
"id": "101",
"content": "满意"
},
{
"id": "102",
"content": "不满意"
}
],
"tail_content": "欢迎再次光临"
}
}
```
### 卡券消息
```json
{
"touser": "OPENID",
"msgtype": "wxcard",
"wxcard": {
"card_id": "123dsdajkasd231jhksad"
}
}
```
> 请以官方文档为准。
================================================
FILE: docs/src/6.x/official-account/server.md
================================================
# 服务端
你可以通过 `$app->getServer()` 获取服务端模块,**服务端模块默认处理了服务端验证的逻辑**:
```php
use EasyWeChat\OfficialAccount\Application;
$config = [...];
$app = new Application($config);
$server = $app->getServer();
```
## 服务端验证
SDK 已经内置了服务端验证的实现,你不需要自己再去关心 `echostr` 怎么返回,直接像下面这样就可以完成服务端验证:
```php
return $server->serve();
```
> 🚨 注意
> `$response` 是一个 [Psr\Http\Message\ResponseInterface](https://github.com/php-fig/http-message/blob/master/src/ResponseInterface.php) 实现,所以请自己决定如何适配您的框架。
> 如果使用了 `thinkphp`、`workman` 等框架,需要先把框架请求转换成 Symfony 请求,再通过 `$app->setRequestFromSymfonyRequest($symfonyRequest)` 进行 request 对象替换,然后再调用 `getServer()`;
## 自助处理推送消息
> 🚨 注意:不要在返回 `$server->serve()` 前输出任何内容。
你可以通过下面的方式获取来自微信服务器的推送消息:
```php
$message = $server->getRequestMessage(); // 原始消息
```
你也可以获取解密后的消息 6.5.0+
```php
$message = $server->getDecryptedMessage();
```
`$message` 为一个 `EasyWeChat\OfficialAccount\Message` 实例。
你可以在处理完逻辑后自行创建一个响应,当然,在不同的框架里,响应写法也不一样,请自行实现,我建议使用下面的中间件模式来完成会更简单方便。
## 中间件模式
与 5.x 的设计类似,服务端使用中间件模式来依次调用开发者注册的中间件:
```php
$server->with(function($message, \Closure $next) {
// 你的自定义逻辑
return $next($message);
});
$response = $server->serve();
```
你可以注册多个中间件来处理不同的情况:
```php
$server
->with(function($message, \Closure $next) {
// 你的自定义逻辑1
return $next($message);
})
->with(function($message, \Closure $next) {
// 你的自定义逻辑2
return $next($message);
})
->with(function($message, \Closure $next) {
// 你的自定义逻辑3
return $next($message);
});
$response = $server->serve();
```
### 回复消息
当你在中间件里不回复消息时,你将要传递消息给下一个中间件:
```php
function($message, \Closure $next) {
// 你的自定义逻辑3
return $next($message);
}
```
如果此时你需要返回消息给用户,你可以直接像下面这样回复消息内容:
```php
function($message, \Closure $next) {
return '感谢你使用 EasyWeChat';
}
```
> 注意:回复消息后其他没运行的中间件将不再执行,所以请你将全局都需要执行的中间件优先提前注册。
其他类型的消息时,请直接参考 **[官方文档消息的 XML 结构](https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Passive_user_reply_message.html)** 以数组形式返回即可。
需要省略 `ToUserName`、`FromUserName` 和 `CreateTime`,以回复图片消息为例:
```php
function($message, \Closure $next) {
return [
'MsgType' => 'image',
'Image' => [
'MediaId' => 'media_id',
],
];
}
```
### 怎么发送多条消息?
服务端只能回复一条消息,如果你想在接收到消息时向用户发送多条消息,你可以调用 **[客服消息](https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html)** 接口来发送多条。
### 使用独立的中间件类
当然,中间件也支持多种类型,比如你可以使用一个独立的类作为中间件:
```php
class MyCustomHandler
{
public function __invoke($message, \Closure $next)
{
if ($message->MsgType === 'text') {
//...
}
return $next($message);
}
}
```
注册中间件:
```php
$server->with(MyCustomHandler::class);
// 或者
$server->with(new MyCustomHandler());
```
### 使用 callable 类型中间件
中间件支持 **[`callable`](http://php.net/manual/zh/language.types.callable.php)** 类型的参数,所以你不一定要传入一个闭包(Closure),你可以选择传入一个函数名,一个 `[$class, $method]` 或者 `Foo::bar` 这样的类型。
```php
$server->with([$object, 'method']);
$server->with('ClassName::method');
```
## 注册指定消息类型的消息处理器
为了方便开发者处理消息推送,server 类内置了两个便捷方法:
### 处理普通消息
当普通微信用户向公众账号发消息时被调用,且匹配对应的事件类型:
```php
$server->addMessageListener('text', function() { ... });
```
**参数**
- 参数 1 为消息类型,也就是 message 中的 `MsgType` 字段,例如:`image`;
- 参数 2 是中间件,也就是上面讲到的多种类型的中间件。
### 处理事件消息
事件消息中间件仅在推送事件消息时被调用,且匹配对应的事件类型:
```php
$server->addEventListener('subscribe', function() { ... });
```
**参数**
- 参数 1 为事件类型,也就是 message 中的 `Event` 字段,例如:`subscribe`;
- 参数 2 是中间件,也就是上面讲到的多种类型的中间件。
关于回复消息的结构,可以查阅 **[消息](message.md)** 章节了解更多。
## 完整示例
以下示例完成了服务端验证,自定义中间件回复等逻辑:
```php
use EasyWeChat\OfficialAccount\Application;
$config = [...];
$app = new Application($config);
$server = $app->getServer();
$server->addEventListener('subscribe', function($message, \Closure $next) {
return '感谢您关注 EasyWeChat!';
});
$response = $server->serve();
return $response;
```
> `$response` 是一个 [Psr\Http\Message\ResponseInterface](https://github.com/php-fig/http-message/blob/master/src/ResponseInterface.php) 实现,所以请自己决定如何适配您的框架。
> 如果使用了 `thinkphp`、`workman` 等框架,需要先把框架请求转换成 Symfony 请求,再通过 `$app->setRequestFromSymfonyRequest($symfonyRequest)` 进行 request 对象替换,然后再调用 `getServer()`;
================================================
FILE: docs/src/6.x/official-account/utils.md
================================================
# 工具
提供微信网页开发 JS-SDK 相关方法
## 配置
```php
getUtils();
```
## 生成 JS-SDK 签名
:book: [官方文档 - JS-SDK说明文档](https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html)
```php
$config = $utils->buildJsSdkConfig(
url: $url,
jsApiList: [],
openTagList: [],
debug: false,
);
// print
[
"appId" => "wx...",
"jsApiList" => [],
"nonceStr" => "string",
"openTagList" => [],
"signature" => "sign",
"timestamp" => "timestamp"
];
```
## 示例
页面生成js配置(1.4和1.6版本任选一即可):
```html
```
结果如下:
```html
```
================================================
FILE: docs/src/6.x/open-platform/examples.md
================================================
---
aside: false
title: 微信开放平台代码使用示例
---
# 示例
> 👏🏻 欢迎点击本页下方 "帮助我们改善此页面!" 链接参与贡献更多的使用示例!
Laravel 开放平台处理推送消息
> 注意:对应路由需要[排除 csrf 验证](https://laravel.com/docs/12.x/csrf#csrf-excluding-uris)。
假设你的开放平台第三方平台设置的授权事件接收 URL 为: `https://easywechat.com/open-platform` (其他事件推送同样会推送到这个 URL)
```php
// routes/web.php
Route::post('open-platform', function () {
// $app 为你实例化的开放平台对象,此处省略实例化步骤
return $app->server->serve(); // Done!
});
// 处理授权事件
Route::post('open-platform', function () {
$server = $app->getServer();
// 处理授权成功事件,其他事件同理
$server->handleAuthorized(function ($message) {
// $message 为微信推送的通知内容,不同事件不同内容,详看微信官方文档
// 获取授权公众号 AppId: $message['AuthorizerAppid']
// 获取 AuthCode:$message['AuthorizationCode']
// 然后进行业务处理,如存数据库等...
});
return $server->serve();
});
```
Laravel Octane(swoole) 开放平台处理推送消息
```php
// routes/web.php
use EasyWeChat\OpenPlatform\Application;
// 授权事件回调地址:http://easywechat.com/open-platform/server
Route::post('open-platform/server', function () {
$config = config('wechatv6.open_platform');
$app = new Application($config);
// 兼容octane
$app->setRequestFromSymfonyRequest(request());
$server = $app->getServer();
return $server->serve();
});
```
webman 开放平台处理推送消息
```php
namespace app\controller;
use EasyWeChat\OpenPlatform\Application;
use support\Request;
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
// 授权事件回调地址:http://easywechat.com/openPlatform/server
class OpenPlatform
{
public function server(Request $request)
{
$config = config('wechatv6.open_platform');
$app = new Application($config);
$symfony_request = new SymfonyRequest($request->get(), $request->post(), [], $request->cookie(), [], [], $request->rawBody());
$symfony_request->headers = new HeaderBag($request->header());
$app->setRequestFromSymfonyRequest($symfony_request);
$server = $app->getServer();
$response = $server->serve();
return $response->getBody()->getContents();
}
}
```
Laravel 开放平台PC版预授权6.3.0+
> [官方文档](https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Before_Develop/Authorization_Process_Technical_Description.html)
用例:
```php
// routes/web.php
// 授权落地页
Route::any('open-platform/auth', function(){
$auth_code = request()->get('auth_code');
// 完成授权写入数据库的逻辑省略。。。
})->name('open_platform.auth');
// 授权跳转页
Route::any('open-platform/preauth', function(){
// $app 为你实例化的开放平台对象,此处省略实例化步骤
$options=[
//1 表示手机端仅展示公众号;2 表示仅展示小程序,3 表示公众号和小程序都展示。如果为未指定,则默认小程序和公众号都展示。
// 'auth_type' => '',
// 指定的权限集id列表,如果不指定,则默认拉取当前第三方账号已经全网发布的权限集列表。
// 'category_id_list' => '',
];
$url = $app->createPreAuthorizationUrl(route('open_platform.auth'), $options);
return response("")->header('Content-Type', 'text/html');
});
```
Laravel 开放平台代公众号/小程序代调用示例6.3.0+
路由配置:
```php
// routes/web.php
// 例如:https://easywechat.com/open-platform/miniapp/get-phone-number/wx123212312313abc
Route::any('open-platform/miniapp/get-phone-number/{appid}', 'OpenPlatformController@getPhoneNumber');
Route::any('open-platform/officialAccount/get-user-list/{appid}', 'OpenPlatformController@getUsers');
```
对应控制器:`app/Http/Controllers/OpenPlatformController`:
```php
use App\Http\Controllers\Controller;
class OpenPlatformController extends Controller
{
public function mini(string $appid): \EasyWeChat\MiniApp\Application
{
$refreshToken = '授权后在缓存或数据库获取';
// $app 为你实例化的开放平台对象,此处省略实例化步骤
return $app->getMiniAppWithRefreshToken($appid, $refreshToken);
}
public function officialAccount(string $appid): \EasyWeChat\OfficialAccount\Application
{
$refreshToken = '授权后在缓存或数据库获取';
// $app 为你实例化的开放平台对象,此处省略实例化步骤
return $app->getOfficialAccountWithRefreshToken($appid, $refreshToken);
}
public function getUsers(string $appid)
{
return $this->officialAccount($appid)
->getClient()
->get('cgi-bin/users/list')
->toArray();
}
public function getPhoneNumber(string $appid)
{
$data = [
'code' => (string) request()->get('code'),
];
return $this->mini($appid)
->getClient()
->postJson('wxa/business/getuserphonenumber', $data)
->toArray();
}
}
```
Laravel 开放平台代公众号处理回调事件
```php
// 代公众号处理回调事件
Route::any('callback/{appid}', function ($appId) {
// $app 为你实例化的开放平台对象,此处省略实例化步骤
// $refreshToken 为授权后你缓存或数据库中的 authorizer_refresh_token,此处省略获取步骤
$refreshToken = '你已缓存或数据库中的 authorizer_refresh_token';
$server = $app->getOfficialAccountWithRefreshToken($appId, $refreshToken)->getServer();
$server->addMessageListener('text', function ($message) {
return sprintf("你对 overtrue 说:“%s”", $message->Content);
});
return $server->serve();
});
```
================================================
FILE: docs/src/6.x/open-platform/index.md
================================================
# 微信开放平台第三方平台
请仔细阅读并理解:[微信官方文档 - 开放平台 - 第三方平台](https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/product/Third_party_platform_appid.html)
## 实例化
请按如下格式配置你的开放平台账号信息,并实例化一个开放平台对象:
```php
'wx3cf0f39249eb0exx', // 开放平台账号的 appid
'secret' => 'f1c242f4f28f735d4687abb469072axx', // 开放平台账号的 secret
'token' => 'easywechat', // 开放平台账号的 token
'aes_key' => '', // 明文模式请勿填写 EncodingAESKey
/**
* 接口请求相关配置,超时时间等,具体可用参数请参考:
* https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
*/
'http' => [
'throw' => true, // 状态码非 200、300 时是否抛出异常,默认为开启
'timeout' => 5.0,
// 'base_uri' => 'https://api.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用,根据不同的模块配置不同的 uri
'retry' => true, // 使用默认重试配置
// 'retry' => [
// // 仅以下状态码重试
// 'status_codes' => [429, 500]
// // 最大重试次数
// 'max_retries' => 3,
// // 请求间隔 (毫秒)
// 'delay' => 1000,
// // 如果设置,每次重试的等待时间都会增加这个系数
// // (例如. 首次:1000ms; 第二次: 3 * 1000ms; etc.)
// 'multiplier' => 3
// ],
],
];
$app = new Application($config);
```
> 💡 请不要把公众号/小程序的配置信息用于初始化开放平台。
## API
Application 就是一个工厂类,所有的模块都是从 `$app` 中访问,并且几乎都提供了协议和 setter 可自定义修改。
### 服务端
服务端模块封装了服务端相关的便捷操作,隐藏了部分复杂的细节,基于中间件模式可以更方便的处理消息推送和服务端验证。
```php
$app->getServer();
```
:book: 更多说明请参阅:[服务端使用文档](server.md)
### API Client
封装了多种模式的 API 调用类,你可以选择自己喜欢的方式调用开放平台任意 API,默认自动处理了 access_token 相关的逻辑。
```php
$app->getClient();
```
:book: 更多说明请参阅:[API 调用](../client.md)
### 配置
```php
$config = $app->getConfig();
```
你可以轻松使用 `$config->all()` 获取整个配置的数组。
还可以使用 `$config->get($key, $default)` 读取单个配置,或使用 `$config->set($key, $value)` 在调用前修改配置项。
### ComponentAccessToken
access_token 是开放平台 API 调用的必备条件,如果你想获取它的值,你可以通过以下方式拿到当前的 access_token:
```php
$componentAccessToken = $app->getComponentAccessToken();
$componentAccessToken->getToken(); // string
```
当然你也可以使用自己的 ComponentAccessToken 类:
```php
$componentAccessToken = new MyCustomComponentAccessToken();
$app->setComponentAccessToken($componentAccessToken)
```
### VerifyTicket
你可以通过以下方式拿到当前 verify_ticket 类:
```php
$verifyTicket = $app->getVerifyTicket();
$verifyTicket->getTicket(); // strval
```
### 开放平台账户
开放平台账号类,提供一系列 API 获取开放平台的基本信息:
```php
$account = $app->getAccount();
$account->getAppId();
$account->getSecret();
$account->getToken();
$account->getAesKey();
```
## 第三方应用或网站网页授权
> 注意:不是代公众号/小程序授权。
第三方应用或者网站网页授权的逻辑和公众号的网页授权基本一样:
```php
$oauth = $app->getOAuth();
```
:book: 详情请参考:[网页授权](../oauth.md)
## 使用授权码获取授权信息
在用户在授权页授权流程完成后,授权页会自动跳转进入回调 URI,并在 URL 参数中返回授权码和过期时间,如:(`https://easywechat.com/callback?auth_code=xxx&expires_in=600`)
```php
$authorizationCode = '授权成功时返回给第三方平台的授权码';
$authorization = $app->getAuthorization($authorizationCode);
$authorization->getAppId(); // authorizer_appid
$authorization->getAccessToken(); // EasyWeChat\OpenPlatform\AuthorizerAccessToken
$authorization->getRefreshToken(); // authorizer_access_token
$authorization->toArray();
$authorization->toJson();
// {
// "authorization_info": {
// "authorizer_appid": "wxf8b4f85f3a79...",
// "authorizer_access_token": "QXjUqNqfYVH0yBE1iI_7vuN_9gQbpjfK7M...",
// "expires_in": 7200,
// "authorizer_refresh_token": "dTo-YCXPL4llX-u1W1pPpnp8Hgm4wpJt...",
// "func_info": [
// {
// "funcscope_category": {
// "id": 1
// }
// },
// //...
// ]
// }
// }
```
## 创建预授权码 6.3.0+
你可以通过下面的方式创建预授权码:
```php
$reponse = $app->createPreAuthorizationCode();
// {
// "pre_auth_code": "Cx_Dk6qiBE0Dmx4eKM-2SuzA...",
// "expires_in": 600
// }
```
## 生成授权页地址 6.3.0+
你可以通过下面方法生成一个授权页地址,引导用户进行授权:
```php
// 自动获取预授权码模式
$url = $app->createPreAuthorizationUrl('http://easywechat.com/callback');
// 或者指定预授权码
$preAuthCode = 'createPreAuthorizationCode 得到的预授权码 pre_auth_code';
$url = $app->createPreAuthorizationUrl('http://easywechat.com/callback', $preAuthCode);
```
## 获取/刷新接口调用令牌
在公众号/小程序接口调用令牌 `authorizer_access_token` 失效时,可以使用刷新令牌 `authorizer_refresh_token` 获取新的接口调用令牌。
> `authorizer_access_token` 有效期为 2 小时,开发者需要缓存 `authorizer_access_token`,避免获取/刷新接口调用令牌的 API 调用触发每日限额。
```php
$authorizerAppId = '授权方 appid';
$authorizerRefreshToken = '上一步得到的 authorizer_refresh_token';
$app->refreshAuthorizerToken($authorizerAppId, $authorizerRefreshToken)
// {
// "authorizer_access_token": "some-access-token",
// "expires_in": 7200,
// "authorizer_refresh_token": "refresh_token_value"
// }
```
---
## 代替公众号/小程序请求 API
代替公众号/小程序请求,需要首先拿到 `EasyWeChat\OpenPlatform\AuthorizerAccessToken`,用以代替公众号的 Access Token,官方流程说明:[开发前必读 /Token 生成介绍](https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Before_Develop/creat_token.html) 。
### 获取 AuthorizerAccessToken
你可以使用开放 **平台永久授权码** 换取授权者信息,然后换取 Authorizer Access Token:
```php
$authorizationCode = '授权成功时返回给第三方平台的授权码';
$authorization = $app->getAuthorization($authorizationCode);
$authorizerAccessToken = $authorization->getAccessToken();
```
> 🚨 Authorizer Access Token 只有 2 小时有效期,不建议将它存储到数据库,当然如果你不得不这么做,请记得参考上面 「**获取/刷新接口调用令牌**」章节刷新。
### 代公众号调用
**方式一:使用 authorizer_refresh_token** 6.3.0+
此方式适用于大部分场景,将授权信息存储到数据库中,代替调用时取出对应公众号的 authorizer_refresh_token 即可。
```php
$authorizerRefreshToken = '公众号授权时得到的 authorizer_refresh_token';
$officialAccount = $app->getOfficialAccountWithRefreshToken($appId, $authorizerRefreshToken);
```
**方式二:使用 authorizer_access_token** 6.3.0+
此方案适用于使用独立的中央授权服务单独维护授权信息的方式。
```php
$authorizerAccessToken = '公众号授权时得到的 authorizer_access_token';
$officialAccount = $app->getOfficialAccountWithAccessToken($appId, $authorizerAccessToken);
```
**方式三:使用 AuthorizerAccessToken 类**
不推荐,请使用方式一或者二,此方法由于设计之初没有充分考虑到使用场景,导致使用很麻烦。
```php
// $token 为你存到数据库的授权码 authorizer_access_token
$authorizerAccessToken = new AuthorizerAccessToken($authorizerAppId, $token);
$officialAccount = $app->getOfficialAccount($authorizerAccessToken);
使用以上方式初始化公众号对象后,可以直接调用公众号的 API 方法,如:
// 调用公众号接口
$response = $officialAccount->getClient()->get('cgi-bin/users/list');
```
> `$officialAccount` 为 `EasyWeChat\OfficialAccount\Application` 实例
:book: 更多公众号用法请参考:[公众号](../official-account/index.md)
### 代小程序调用
小程序和公众号使用方式一样,同样有三种方式:
```php
// 方式一:使用 authorizer_refresh_token
$authorizerRefreshToken = '小程序授权时得到的 authorizer_refresh_token';
$officialAccount = $app->getMiniAppWithRefreshToken($appId, $authorizerRefreshToken);
// 方式二:使用 authorizer_access_token
$authorizerAccessToken = '小程序授权时得到的 authorizer_access_token';
$officialAccount = $app->getMiniAppWithAccessToken($appId, $authorizerAccessToken);
// 方式三:不推荐
// $token 为你存到数据库的授权码 authorizer_access_token
$authorizerAccessToken = new AuthorizerAccessToken($authorizerAppId, $token);
$miniApp = $app->getMiniApp($authorizerAccessToken);
// 调用小程序接口
$response = $miniApp->getClient()->get('cgi-bin/users/list');
```
- [微信官方文档 - 开放平台代小程序实现小程序登录接口](https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/others/WeChat_login.html#请求地址)
:book: 更多小程序用法请参考:[小程序](../mini-app/index.md)
================================================
FILE: docs/src/6.x/open-platform/server.md
================================================
# 服务端
第三方平台的服务端推送和公众号一样,请参考:[公众号:服务端](../official-account/server.md)
## 第三方平台推送事件处理
公众号第三方平台推送的有四个事件:
> 如已经授权的公众号、小程序再次进行授权,而未修改已授权的权限的话,是没有相关事件推送的。
- 授权成功 `authorized`
- 授权更新 `updateauthorized`
- 授权取消 `unauthorized`
- VerifyTicket `component_verify_ticket`
SDK 默认会处理事件 `component_verify_ticket` ,并会缓存 `verify_ticket` 所以如果你暂时不需要处理其他事件,直接这样使用即可:
```php
$server = $app->getServer();
return $server->serve();
```
## 内置消息处理器
> _消息处理器详细说明见公众号开发 - 服务端一节_
### 处理授权成功事件
```php
$server->handleAuthorized(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### 处理授权更新事件
```php
$server->handleAuthorizeUpdated(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### 处理授权取消事件
```php
$server->handleUnauthorized(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### 处理 VerifyTicket 推送事件(已默认处理)
此推送已经默认处理(使用缓存存储和刷新),可以直接忽略。
> 注意:如果你自行处理了 VerifyTicket 推送,你必须同时设置 ComponentAccessToken 类,因为 ComponentAccessToken 依赖它。
```php
$server->handleVerifyTicketRefreshed(function($message, \Closure $next) {
// ...
return $next($message);
});
```
## 其它事件处理
以上便捷方法都只处理了特定事件,其它状态,可以通过自定义事件处理中间件的形式处理:
```php
$server->with(function($message, \Closure $next) {
// $message->event_type 事件类型
return $next($message);
});
```
## 自助处理推送消息
你可以通过下面的方式获取来自微信服务器的推送消息:
```php
$message = $server->getRequestMessage(); // 原始消息
```
你也可以获取解密后的消息 6.5.0+
```php
$message = $server->getDecryptedMessage();
```
`$message` 为一个 `EasyWeChat\OpenPlatform\Message` 实例。
你可以在处理完逻辑后自行创建一个响应,当然,在不同的框架里,响应写法也不一样,请自行实现。
================================================
FILE: docs/src/6.x/open-work/examples.md
================================================
---
aside: false
title: 企业微信开放平台使用代码示例
next:
text: 关于6.x
link: ../introduction
---
# 示例
> 👏🏻 欢迎点击本页下方 "帮助我们改善此页面!" 链接参与贡献更多的使用示例!
================================================
FILE: docs/src/6.x/open-work/index.md
================================================
# 企业微信服务商
请仔细阅读并理解:[企业微信 API - 第三方应用开发](https://open.work.weixin.qq.com/api/doc/90001/90142/90594)
## 实例化
```php
'wx3cf0f39249eb0exx',
'provider_secret' => 'f1c242f4f28f735d4687abb469072axx',
'token' => 'easywechat',
'aes_key' => '', // 明文模式请勿填写 EncodingAESKey
/**
* 接口请求相关配置,超时时间等,具体可用参数请参考:
* https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
*/
'http' => [
'throw' => true, // 状态码非 200、300 时是否抛出异常,默认为开启
'timeout' => 5.0,
// 'base_uri' => 'https://qyapi.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用,根据不同的模块配置不同的 uri
'retry' => true, // 使用默认重试配置
// 'retry' => [
// // 仅以下状态码重试
// 'status_codes' => [429, 500]
// // 最大重试次数
// 'max_retries' => 3,
// // 请求间隔 (毫秒)
// 'delay' => 1000,
// // 如果设置,每次重试的等待时间都会增加这个系数
// // (例如. 首次:1000ms; 第二次: 3 * 1000ms; etc.)
// 'multiplier' => 3
// ],
],
];
$app = new Application($config);
```
## API
Application 就是一个工厂类,所有的模块都是从 `$app` 中访问,并且几乎都提供了协议和 setter 可自定义修改。
### 服务端
服务端模块封装了服务端相关的便捷操作,隐藏了部分复杂的细节,基于中间件模式可以更方便的处理消息推送和服务端验证。
```php
$app->getServer();
```
:book: 更多说明请参阅:[服务端使用文档](server.md)
### API Client
封装了多种模式的 API 调用类,你可以选择自己喜欢的方式调用开放平台任意 API,默认自动处理了 access_token 相关的逻辑。
```php
$app->getClient();
```
:book: 更多说明请参阅:[API 调用](../client.md)
### 配置
```php
$config = $app->getConfig();
```
你可以轻松使用 `$config->get($key, $default)` 读取配置,或使用 `$config->set($key, $value)` 在调用前修改配置项。
### ProviderAccessToken
provider_access_token 是开放平台 API 调用的必备条件,如果你想获取它的值,你可以通过以下方式拿到当前的 provider_access_token:
```php
$providerAccessToken = $app->getProviderAccessToken();
$providerAccessToken->getToken(); // string
```
当然你也可以使用自己的 ProviderAccessToken 类:
```php
$providerAccessToken = new MyCustomProviderAccessToken();
$app->setProviderAccessToken($providerAccessToken)
```
### SuiteTicket
你可以通过以下方式拿到当前 suite_ticket 类:
```php
$suiteTicket = $app->getSuiteTicket();
$suiteTicket->getTicket(); // string
```
### 开放平台账户
开放平台账号类,提供一系列 API 获取开放平台的基本信息:
```php
$account = $app->getAccount();
$account->getCorpId();
$account->getProviderSecret();
$account->getToken();
$account->getAesKey();
```
## 第三方应用需要在打开的网页里面携带用户的身份信息
> [点此查看官方文档](https://open.work.weixin.qq.com/api/doc/90001/90143/91120#%E6%9E%84%E9%80%A0%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%94%E7%94%A8oauth2%E9%93%BE%E6%8E%A5)
第三方应用或者网站网页授权的逻辑和公众号的网页授权基本一样:
```php
$oauth = $app->getOAuth(string $suiteId, AccessTokenInterface $suiteAccessToken);
```
:book: 详情请参考:[网页授权](./oauth.md)
## 企业网页授权
> [点此查看官方文档](https://open.work.weixin.qq.com/api/doc/90001/90143/91120#%E6%9E%84%E9%80%A0%E4%BC%81%E4%B8%9Aoauth2%E9%93%BE%E6%8E%A5)
```php
$oauth = $app->getCorpOAuth(string $corpId, AccessTokenInterface $suiteAccessToken);
```
:book: 详情请参考:[网页授权](./oauth.md)
## 使用授权码获取授权信息
在用户在授权页授权流程完成后,授权页会自动跳转进入回调 URI,并在 URL 参数中返回授权码和过期时间,如:(`https://easywechat.com/callback?auth_code=xxx&expires_in=600`)
```php
$permanentCode = '企业永久授权码';
$suiteAccessToken = new SuiteAccessToken($suiteId, $suiteSecret);
$authorization = $app->getAuthorization($corpId, $authorizatpermanentCodeionCode, $suiteAccessToken);
$authorization->getCorpId(); // auth_corp_info.corpid
$authorization->toArray();
$authorization->toJson();
// {
// "errcode":0 ,
// "errmsg":"ok" ,
// "dealer_corp_info":
// {
// "corpid": "xxxx",
// "corp_name": "name"
// },
// "auth_corp_info":
// {
// "corpid": "xxxx",
// "corp_name": "name",
// "corp_type": "verified",
// "corp_square_logo_url": "yyyyy",
// "corp_user_max": 50,
// "corp_agent_max": 30,
// "corp_full_name":"full_name",
// "verified_end_time":1431775834,
// "subject_type": 1,
// "corp_wxqrcode": "zzzzz",
// "corp_scale": "1-50人",
// "corp_industry": "IT服务",
// "corp_sub_industry": "计算机软件/硬件/信息服务",
// "location":"广东省广州市"
// },
// "auth_info":
// {
// "agent" :
// [
// {
// "agentid":1,
// "name":"NAME",
// "round_logo_url":"xxxxxx",
// "square_logo_url":"yyyyyy",
// "appid":1,
// "auth_mode":1,
// "privilege":
// {
// "level":1,
// "allow_party":[1,2,3],
// "allow_user":["zhansan","lisi"],
// "allow_tag":[1,2,3],
// "extra_party":[4,5,6],
// "extra_user":["wangwu"],
// "extra_tag":[4,5,6]
// },
// "shared_from":
// {
// "corpid":"wwyyyyy"
// }
// },
// {
// "agentid":2,
// "name":"NAME2",
// "round_logo_url":"xxxxxx",
// "square_logo_url":"yyyyyy",
// "appid":5,
// "shared_from":
// {
// "corpid":"wwyyyyy"
// }
// }
// ]
// }
// }
```
## 获取企业凭证
在公众号/小程序接口调用令牌(`authorizer_access_token`)失效时,可以使用刷新令牌(authorizer_refresh_token)获取新的接口调用令牌。
> 注意: `authorizer_access_token` 有效期为 2 小时,开发者需要缓存 `authorizer_access_token`,避免获取/刷新接口调用令牌的 API 调用触发每日限额。缓存方法可以参考:
```php
$permanentCode = '企业永久授权码';
$suiteAccessToken = new SuiteAccessToken($suiteId, $suiteSecret);
$authorizerAccessToken = $app->getAuthorizerAccessToken($corpId, $permanentCode, $suiteAccessToken)
// {
// "errcode":0 ,
// "errmsg":"ok" ,
// "access_token": "xxxxxx",
// "expires_in": 7200
// }
$authorizerAccessToken->getToken(); // string
```
================================================
FILE: docs/src/6.x/open-work/oauth.md
================================================
# OAuth
第三方服务商网页授权有两种:
- [第三方应用网页授权](https://open.work.weixin.qq.com/api/doc/90001/90143/91120#%E6%9E%84%E9%80%A0%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%94%E7%94%A8oauth2%E9%93%BE%E6%8E%A5)
- [企业网页授权](https://open.work.weixin.qq.com/api/doc/90001/90143/91120#%E6%9E%84%E9%80%A0%E4%BC%81%E4%B8%9Aoauth2%E9%93%BE%E6%8E%A5)
创建实例:
```php
use EasyWeChat\Work\Application;
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxx', // 应用的 secret
];
$app = new Application($config);
```
## 获取 OAuth 模块实例
请根据你的场景选择对应的方法获取 OAuth 实例:
```php
// 第三方应用网页授权
$oauth = $app->getOAuth(string $suiteId, AccessTokenInterface $suiteAccessToken);
// 企业网页授权
$oauth = $app->getCorpOAuth(string $corpId, AccessTokenInterface $suiteAccessToken);
// 如需指定应用ID
$oauth = $oauth->withAgentId($agentId);
```
## 跳转授权
```php
// $callbackUrl 为授权回调地址
$callbackUrl = 'https://xxx.xxx'; // 需设置可信域名
// 返回授权跳转链接
$redirectUrl = $app->getOAuth()->redirect($callbackUrl);
```
## 获取授权用户信息
在回调页面中,你可以使用以下方式获取授权者信息:
```php
$code = "回调URL中的code";
$user = $app->getOAuth()->detailed()->userFromCode($code);
// 获取用户信息
$user->getId(); // 对应企业微信英文名(userid)
$user->getRaw(); // 获取企业微信接口返回的原始信息
```
:book: OAuth 详情请参考:[网页授权](../oauth.md)
获取用户其他信息需调用通讯录接口,参考:[企业微信通讯录 API](https://github.com/EasyWeChat/docs/blob/master/wework/contacts.md)
## 参考阅读
- 本模块基于 [overtrue/socialite](https://github.com/overtrue/socialite/) 实现,更多的使用请阅读该扩展包文档。
- state 参数的使用: [overtrue/socialite/#state](https://github.com/overtrue/socialite/#state)
================================================
FILE: docs/src/6.x/open-work/server.md
================================================
# 服务端
企业微信第三方服务端推送和公众号一样,请参考:[公众号:服务端](../official-account/server.md)
## 第三方平台推送事件处理
企业微信第三方数据推送的有以下事件:
- suite_ticket 推送 `suite_ticket`
- 授权成功 `create_auth`
- 授权变更 `change_auth`
- 授权取消 `cancel_auth`
- 通讯录变更(InfoType) `change_contact`
- ChangeType
- 成员变更
- 新增成员 `create_user`
- 更新成员 `update_user`
- 删除成员 `delete_user`
- 部门变更
- 新增部门 `create_party`
- 更新部门 `update_party`
- 删除部门 `delete_party`
- 标签变更
- 成员标签变更 `update_tag`
- 共享应用事件回调 `share_agent_change`
- 重置永久授权码通知 `reset_permanent_code`
- 应用管理员变更通知 `change_app_admin`
## 内置消息处理器
> _消息处理器详细说明见:公众号开发 - 服务端一节_
### 授权成功事件
```php
$server->handleAuthCreated(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### 授权变更事件
```php
$server->handleAuthChanged(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### 授权取消事件
```php
$server->handleAuthCancelled(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### 通讯录变更事件
```php
$server->handleContactChanged(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### 成员变更事件
```php
// 新增成员
$server->handleUserCreated(function($message, \Closure $next) {
// ...
return $next($message);
});
// 更新成员
$server->handleUserUpdated(function($message, \Closure $next) {
// ...
return $next($message);
});
// 删除成员
$server->handleUserDeleted(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### 部门变更事件
```php
// 新增部门
$server->handlePartyCreated(function($message, \Closure $next) {
// ...
return $next($message);
});
// 更新部门
$server->handlePartyUpdated(function($message, \Closure $next) {
// ...
return $next($message);
});
// 删除部门
$server->handlePartyDeleted(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### 成员标签变更事件
```php
$server->handleUserTagUpdated(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### 共享应用事件
```php
$server->handleShareAgentChanged(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### 重置永久授权码通知
```php
$server->handleResetPermanentCode(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### 应用管理员变更通知
```php
$server->handleChangeAppAdmin(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### suite_ticket 推送事件
此推送已经默认处理(使用缓存存储和刷新),可以直接忽略。
> 注意:如果你自行处理了 SuiteTicket 推送,你必须同时设置 ProviderAccessToken 类,因为 ProviderAccessToken 依赖它。
```php
$server->handleSuiteTicketRefreshed(callable | string $handler);
```
## 其它事件处理
以上便捷方法都只处理了特定事件,其它状态,可以通过自定义事件处理中间件的形式处理:
```php
$server->with(function($message, \Closure $next) {
// $message->event_type 事件类型
return $next($message);
});
```
## 自助处理推送消息
你可以通过下面的方式获取来自微信服务器的推送消息:
```php
$message = $server->getRequestMessage(); // 原始消息
```
你也可以获取解密后的消息 6.5.0+
```php
$message = $server->getDecryptedMessage();
```
`$message` 为一个 `EasyWeChat\OpenWork\Message` 实例。
你可以在处理完逻辑后自行创建一个响应,当然,在不同的框架里,响应写法也不一样,请自行实现。
================================================
FILE: docs/src/6.x/pay/examples.md
================================================
---
aside: false
---
# 示例
> 👏🏻 欢迎点击本页下方 "帮助我们改善此页面!" 链接参与贡献更多的使用示例!
JSAPI 下单
> [官方文档](https://pay.weixin.qq.com/doc/v3/merchant/4012791856)
```php
$response = $app->getClient()->postJson("v3/pay/transactions/jsapi", [
"mchid" => "1518700000", // <---- 请修改为您的商户号
"out_trade_no" => "native12177525012012070352333'.rand(1,1000).'",
"appid" => "wx6222e9f48a0xxxxx", // <---- 请修改为服务号的 appid
"description" => "Image形象店-深圳腾大-QQ公仔",
"notify_url" => "https://weixin.qq.com/",
"amount" => [
"total" => 1,
"currency" => "CNY"
],
"payer" => [
"openid" => "o4GgauInH_RCEdvrrNGrnxxxxxx" // <---- 请修改为服务号下单用户的 openid
]
]);
\dd($response->toArray(false));
```
Native 下单
> [官方文档](https://pay.weixin.qq.com/doc/v3/merchant/4012791877)
```php
$response = $app->getClient()->postJson('v3/pay/transactions/native', [
'mchid' => (string)$app->getMerchant()->getMerchantId(),
'out_trade_no' => 'native20210720xxx',
'appid' => 'wxe2fb06xxxxxxxxxx6',
'description' => 'Image形象店-深圳腾大-QQ公仔',
'notify_url' => 'https://weixin.qq.com/',
'amount' => [
'total' => 1,
'currency' => 'CNY',
]
]);
print_r($response->toArray(false));
```
查询订单(商户订单号)
> [官方文档](https://pay.weixin.qq.com/doc/v3/merchant/4012791859)
```php
$outTradeNo = 'native20210720xxx';
$response = $app->getClient()->get("v3/pay/transactions/out-trade-no/{$outTradeNo}", [
'query'=>[
'mchid' => $app->getMerchant()->getMerchantId()
]
]);
print_r($response->toArray());
```
查询订单(微信订单号)
> [官方文档](https://pay.weixin.qq.com/doc/v3/merchant/4012791858)
```php
$transactionId = '217752501201407033233368018';
$response = $app->getClient()->get("v3/pay/transactions/id/{$transactionId}", [
'query'=>[
'mchid' => $app->getMerchant()->getMerchantId()
]
]);
print_r($response->toArray());
```
Laravel 中处理微信支付回调
> 记得需要将此类路由 [排除 csrf 验证](https://laravel.com/docs/12.x/csrf#csrf-excluding-uris)。
```php
// 假设你设置的通知地址notify_url为: https://easywechat.com/payment_notify
// 注意:通知地址notify_url必须为https协议
Route::post('payment_notify', function () {
// $app 为你实例化的支付对象,此处省略实例化步骤
$server = $app->getServer();
// 处理支付结果事件
$server->handlePaid(function ($message) {
// $message 为微信推送的通知结果,详看微信官方文档
// 微信支付订单号 $message['transaction_id']
// 商户订单号 $message['out_trade_no']
// 商户号 $message['mchid']
// 具体看微信官方文档...
// 进行业务处理,如存数据库等...
});
// 处理退款结果事件
$server->handleRefunded(function ($message) {
// 同上,$message 详看微信官方文档
// 进行业务处理,如存数据库等...
});
return $server->serve();
});
```
付款(V2)
> [官方文档](https://pay.weixin.qq.com/doc/v2/merchant/4011989673)
```php
$response = $api->post('/mmpaymkttransfers/promotion/transfers', [
'xml' => [
'mch_appid' => $app->getConfig()['app_id'], //注意在配置文件中加上app_id
'mchid' => $app->getConfig()['mch_id'], //商户号
'partner_trade_no' => '202203081646729819743', // 商户订单号,需保持唯一性(只能是字母或者数字,不能包含有符号)
'openid' => 'ogn1H45HCRxVRiEMLbLLuABbxxxx', //用户openid
'check_name' => 'FORCE_CHECK', // NO_CHECK:不校验真实姓名, FORCE_CHECK:强校验真实姓名
're_user_name'=> '用户真实姓名', // 如果 check_name 设置为 FORCE_CHECK 则必填用户真实姓名
'amount' => '100', //金额
'desc' => '理赔', // 企业付款操作说明信息。必填
],
'local_cert' => $app->getConfig()['certificate'], //v2证书绝对路径
'local_pk' => $app->getConfig()['private_key'], //v2证书密钥绝对路径
]);
print_r($response->toArray());
```
JSAPI下单(服务商)
> [官方文档](https://pay.weixin.qq.com/doc/v3/partner/4012738519)
```php
$response = $app->getClient()->postJson("v3/pay/partner/transactions/jsapi", [
"sp_appid" => $appId, // 服务商应用ID
"sp_mchid" => '********', // 服务商户号
'sub_mchid' => '*********', // 子商户号/二级商户号
"sub_appid" => '********', // 子商户/二级商户应用ID(选填)
"description" => $this->payDesc($from), // 商品描述
"out_trade_no" => $order['pay_sn'], // 商户订单号
"notify_url" => $this->config['notify_url'], // 通知地址
"amount" => [
"total" => intval($order['order_amount'] * 100), // 总金额
], // 订单金额信息
"payer" => [
"sp_openid" => $this->auth['openid'], // 用户服务标识,户在服务商AppID下的唯一标识
"sub_openid" => $this->auth['openid'] // 用户子标识,用户在子商户AppID下的唯一标识。若传sub_openid,那sub_appid必填。下单前需获取到用户的OpenID
], // 支付者,(sp_openid 和 sub_openid 二选一)
'attach' => $from
]);
print_r($response->toArray());
```
敏感信息加密 6.17.0+
> [官方文档](https://pay.weixin.qq.com/doc/v3/merchant/4013053257)
> 使用默认公钥 ID
```php
$utils = $app->getUtils();
$response = $app->getClient()->withSerialHeader()->postJson("v3/applyment4sub/applyment/", [
"business_code" => "12345678",
'contact_info' => [
'contact_name' => $utils->encryptWithRsaPublicKey('张三'),
//...
],
//...
]);
print_r($response->toArray());
```
或指定平台证书序列号/微信支付公钥 ID (必须在配置项`platform_certs`内)
```php
$utils = $app->getUtils();
$response = $app->getClient()->withSerialHeader("PUB_KEY_ID_123456")->postJson("v3/applyment4sub/applyment/", [
"business_code" => "12345678",
'contact_info' => [
'contact_name' => $utils->encryptWithRsaPublicKey("张三","PUB_KEY_ID_123456"),
//...
],
//...
]);
print_r($response->toArray());
```
================================================
FILE: docs/src/6.x/pay/index.md
================================================
# 微信支付
请仔细阅读并理解:[微信官方文档 - 微信支付](https://pay.weixin.qq.com/doc/v3/merchant/4012062524)
> [!NOTE]
> 2024 年 Q3,微信支付官方开启了「微信支付公钥」平替「平台证书」方案,初始化所需的参数仅需配置上 **微信支付公钥 ID** 及 **微信支付公钥** 即完全兼容支持,CLI/API 下载 **平台证书** 已不是一个必要步骤,可略过。
> **微信支付公钥 ID** 及 **微信支付公钥** 均可在 [微信支付商户平台](https://pay.weixin.qq.com/) -> 账户中心 -> API 安全 查看及/或下载。
## 实例化 {#init}
```php
1360649000,
// 商户证书
'private_key' => __DIR__ . '/certs/apiclient_key.pem',
'certificate' => __DIR__ . '/certs/apiclient_cert.pem',
// v3 API 秘钥
'secret_key' => '43A03299A3C3FED3D8CE7B820Fxxxxx',
// v2 API 秘钥
'v2_secret_key' => '26db3e15cfedb44abfbb5fe94fxxxxx',
// 平台证书:微信支付 APIv3 平台证书,需要使用工具下载
// 下载工具:https://github.com/wechatpay-apiv3/CertificateDownloader
'platform_certs' => [
// 如果是「平台证书」模式
// 使用 Key/Value 结构, key 为 平台证书的序列号,value 为微信支付平台证书的绝对路径
// "{SerialNo}" => '/path/to/wechatpay/cert.pem'
// 如果是「微信支付公钥」模式
// 使用 Key/Value 结构, key 为微信支付公钥 ID(PUB_KEY_ID 开头),value 为微信支付公钥文件绝对路径
// "{$pubKeyId}" => '/path/to/wechatpay/pubkey.pem',
],
/**
* 接口请求相关配置,超时时间等,具体可用参数请参考:
* https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
*/
'http' => [
'throw' => true, // 状态码非 200、300 时是否抛出异常,默认为开启
'timeout' => 5.0,
// 如果你在国外想要覆盖默认的 url 的时候才使用,根据不同的模块配置不同的 base_uri
// 'base_uri' => 'https://api.mch.weixin.qq.com/',
],
];
$app = new Application($config);
```
## API {#api}
Application 就是一个工厂类,所有的模块都是从 `$app` 中访问,并且几乎都提供了协议和 setter 可自定义修改。
### API Client {#client}
封装了多种模式的 API 调用类,你可以选择自己喜欢的方式调用开放平台任意 API,默认自动处理了 access_token 相关的逻辑。
```php
$app->getClient();
```
:book: 更多说明请参阅:[API 调用](../client.md)
### 工具 {#tools}
为了方便开发者生成各种调起支付所需配置,你可以使用工具类:
```php
$app->getUtils();
```
:book: 更多说明请参阅:[工具](utils.md)
### 配置 {#config}
```php
$config = $app->getConfig();
```
你可以轻松使用 `$config->get($key, $default)` 读取配置,或使用 `$config->set($key, $value)` 在调用前修改配置项。
### 支付账户 {#merchant}
支付账户类,提供一系列 API 获取支付的基本信息:
```php
$account = $app->getMerchant();
$account->getMerchantId();
$account->getPrivateKey();
$account->getCertificate();
$account->getSecretKey();
$account->getV2SecretKey();
$account->getPlatformCert($serial);
$account->getPlatformCerts();
```
### 一些可能会用到的 {#others}
#### 签名验证 {#validation}
按官方说法,建议在拿到**微信接口响应**和**接收到微信支付的回调通知**时,对通知的签名进行验证,以确保通知是微信支付发送的。
你可以通过以下方式获取签名验证器:
```php
$app->getValidator();
```
##### 推送消息的签名验证 {#webhook}
```php
$server = $app->getServer();
$server->handlePaid(function (Message $message, \Closure $next) use ($app) {
// $message->out_trade_no 获取商户订单号
// $message->payer['openid'] 获取支付者 openid
try{
$app->getValidator()->validate($app->getRequest());
// 验证通过,业务处理
} catch(Exception $e){
// 验证失败
}
return $next($message);
});
// 默认返回 ['code' => 'SUCCESS', 'message' => '成功']
return $server->serve();
```
##### API 返回值的签名验证 {#verify-response}
```php
// API 请求示例
$response = $app->getClient()->postJson("v3/pay/transactions/jsapi", [...]);
try{
$app->getValidator()->validate($response->toPsrResponse());
// 验证通过
} catch(Exception $e){
// 验证失败
}
```
#### 获取证书序列号 {#x509-serial-no}
```bash
openssl x509 -in /path/to/merchant/apiclient_cert.pem -noout -serial | awk -F= '{print $2}'
```
================================================
FILE: docs/src/6.x/pay/media.md
================================================
## 文件上传 6.10.0+
由于微信 v3 对文件类上传使用特殊的签名机制,参见:[微信支付 - 图片上传API](https://pay.weixin.qq.com/doc/v3/merchant/4012557233)。
因此,我们提供了一个媒体上传方法,方便开发者使用。
```php
$path = '/path/to/your/files/demo.jpg';
$api->uploadMedia('/v3/marketing/favor/media/image-upload', $path);
```
## 自定义 meta 信息
部分接口使用的签名 meta 不一致,所以可以自行传入:
```php
$url = '/v3/...';
$path = '/path/to/your/files/demo.jpg';
$meta = [
'bank_type' => 'CFT',
'filename' => 'demo.jpg',
'sha256' => 'xxxxxxxxxxx',
];
$api->uploadMedia($url, $path, $meta);
```
## 关于 sha256
- 文件,用 `hash_file('sha256', $path)` 计算
- 字符串,用 `hash('sha256', $string)` 计算
================================================
FILE: docs/src/6.x/pay/server.md
================================================
# 服务端
支付推送和公众号几乎一样,请参考:[公众号:服务端](../official-account/server.md)。
## 官方文档
- [基础下单支付结果通知文档](https://pay.weixin.qq.com/doc/v3/merchant/4012284311)
- [合单支付结果通知文档](https://pay.weixin.qq.com/doc/v3/partner/4012237246)
- [退款结果通知文档](https://pay.weixin.qq.com/doc/v3/merchant/4012791865)
## 内置事件处理器
SDK 内置了两个便捷方法以便于开发者快速处理支付推送事件:
> `$message` 属性已经默认解密,可直接访问解密后的属性;
>
> 成功状态 SDK 默认会返回 success, 你可以不用返回任何东西;
### 支付成功事件
🚨 切记:推送信息不一定靠谱,可能是伪造的,所以拿到推送通知,只取订单号等必要信息,其它信息忽略,拿订单号重新查询微信支付订单的最新状态再做处理。
> :book: [官方文档:支付结果通知](https://pay.weixin.qq.com/doc/v3/merchant/4012284311)
```php
$server = $app->getServer();
$server->handlePaid(function (Message $message, \Closure $next) {
// $message->out_trade_no 获取商户订单号
// $message->payer['openid'] 获取支付者 openid
// 🚨🚨🚨 注意:推送信息不一定靠谱哈,请务必验证
// 建议是拿订单号调用微信支付查询接口,以查询到的订单状态为准
return $next($message);
});
// 默认返回 ['code' => 'SUCCESS', 'message' => '成功']
return $server->serve();
```
### 退款成功事件
> :book: [官方文档:退款结果通知](https://pay.weixin.qq.com/doc/v3/merchant/4012791865)
```php
$server = $app->getServer();
$server->handleRefunded(function (Message $message, \Closure $next) {
// $message->out_trade_no 获取商户订单号
// $message->payer['openid'] 获取支付者 openid
return $next($message);
});
// 默认返回 ['code' => 'SUCCESS', 'message' => '成功']
return $server->serve();
```
🚨 注意:经网友发现官方仍存在[使用 v2 模式的退款推送](https://pay.weixin.qq.com/doc/v2/merchant/4011985425),所以如果你的退款逻辑有异常,请参考以下方式实现(需要配置 v2 API key):
> 网友反馈的[问题:#2737](https://github.com/w7corp/easywechat/issues/2737)
> 目前已知的情况是:微信商户平台填写的 API 回调地址,然后在商户平台手动处理退款的。
```php
// 建议使用单独的路由处理退款!
$server = $app->getServer();
// 推送消息,已解密
// 结构参考:https://pay.weixin.qq.com/doc/v2/merchant/4011985425
$message = $server->getRequestMessage();
// 你的逻辑...
// 返回 SUCCESS 或者 FAIL 等其他状态
return new \Nyholm\Psr7\Response(
200, [],
\EasyWeChat\Kernel\Support\Xml::build([
'return_code' => 'SUCCESS',
'return_msg' => 'OK'
])
);
```
## 其它事件处理
以上便捷方法都只处理了**成功状态**,其它状态,可以通过自定义事件处理中间件的形式处理:
```php
$server->with(function($message, \Closure $next) {
// $message->event_type 事件类型
return $next($message);
});
```
## 自助处理推送消息
你可以通过下面的方式获取来自微信服务器的推送消息:
```php
$message = $server->getRequestMessage();
```
`$message` 为一个 `EasyWeChat\Pay\Message` 实例。
你可以在处理完逻辑后自行创建一个响应,当然,在不同的框架里,响应写法也不一样,请自行实现。
## 回调消息
微信推送的回调消息是默认密文的,可参考[文档](https://pay.weixin.qq.com/doc/v3/merchant/4012071382),但是 SDK 已经帮你解密好了,所以以上例子中的 `$message` 默认访问的属性都是明文的,例如:
```json
{
"transaction_id":"1217752501201407033233368018",
"amount":{
"payer_total":100,
"total":100,
"currency":"CNY",
"payer_currency":"CNY"
},
"mchid":"1230000109",
"trade_state":"SUCCESS",
"bank_type":"CMC",
"promotion_detail":[...],
"success_time":"2018-06-08T10:34:56+08:00",
"payer":{
"openid":"oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"
},
"out_trade_no":"1217752501201407033233368018",
"appid":"wxd678efh567hg6787",
"trade_state_desc":"支付成功",
"trade_type":"MICROPAY",
"attach":"自定义数据",
"scene_info":{
"device_id":"013467007045764"
}
}
```
所以你可以直接使用 `$message->transaction_id` 或者 `$message['transaction_id']` 来访问以上属性。
#### 怎么获取密文属性呢?
`$message` 对象提供了 `$message->getOriginalAttributes()` 来获取加密前的数据:
```json
{
"id": "EV-2018022511223320873",
"create_time": "2015-05-20T13:29:35+08:00",
"resource_type": "encrypt-resource",
"event_type": "TRANSACTION.SUCCESS",
"summary": "支付成功",
"resource": {
"original_type": "transaction",
"algorithm": "AEAD_AES_256_GCM",
"ciphertext": "",
"associated_data": "",
"nonce": ""
}
}
```
当然我们还特别封装了用于获取事件类型的方法:
```php
$message->getEventType(); // TRANSACTION.SUCCESS
```
================================================
FILE: docs/src/6.x/pay/utils.md
================================================
---
title: 工具 | 微信支付
aside: false
---
# 工具
提供各种支付需要的配置生成方法。
## 配置
```php
getUtils();
```
> 注意
## 生成支付 JS 配置
有四种发起支付的方式:WeixinJSBridge, JSSDK, 小程序支付, APP
### WeixinJSBridge 调起支付 API
:book: [官方文档 - WeixinJSBridge 调起支付](https://pay.weixin.qq.com/doc/v3/merchant/4012791857)
```php
$appId = '商户申请的公众号对应的 appid,由微信支付生成,可在公众号后台查看';
$signType = 'RSA'; // 默认RSA,v2要传MD5
$config = $utils->buildBridgeConfig($prepayId, $appId, $signType); // 返回数组
```
调用示例
```js
WeixinJSBridge.invoke(
'getBrandWCPayRequest',
{
timeStamp: "= $config['timeStamp'] ?>", //注意 timeStamp 的格式
nonceStr: "= $config['nonceStr'] ?>",
package: "= $config['package'] ?>",
signType: "= $config['signType'] ?>",
paySign: "= $config['paySign'] ?>" // 支付签名
},
function (res) {
if (res.err_msg == 'get_brand_wcpay_request:ok') {
// 使用以上方式判断前端返回,微信团队郑重提示:
// res.err_msg将在用户支付成功后返回
// ok,但并不保证它绝对可靠。
}
}
)
```
### JSSDK 调起支付 API
:book: [官方文档 - wx.chooseWXPay 调起支付](https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#58)
```php
$appId = '商户申请的公众号对应的 appid,由微信支付生成,可在公众号后台查看';
$signType = 'RSA'; // 默认RSA,v2要传MD5
$config = $utils->buildSdkConfig($prepayId, $appId, $signType); // 返回数组
```
调用实例:
```js
wx.chooseWXPay({
timestamp: "= $config['timestamp'] ?>",
nonceStr: "= $config['nonceStr'] ?>",
package: "= $config['package'] ?>",
signType: "= $config['signType'] ?>",
paySign: "= $config['paySign'] ?>",
success: function (res) {
// 支付成功后的回调函数
}
})
```
### 小程序调起支付 API
:book: [官方文档 - 小程序调起支付 API](https://pay.weixin.qq.com/doc/v3/merchant/4012791898)
```php
$appId = '商户申请的小程序对应的appid,由微信支付生成,可在小程序后台查看';
$signType = 'RSA'; // 默认RSA,v2要传MD5
$config = $utils->buildMiniAppConfig($prepayId, $appId, $signType); // 返回数组
```
调用示例:
```js
wx.requestPayment({
timeStamp: "= $config['timeStamp'] ?>",
nonceStr: "= $config['nonceStr'] ?>",
package: "= $config['package'] ?>",
signType: "= $config['signType'] ?>",
paySign: "= $config['paySign'] ?>",
success: function (res) {
// 支付成功后的回调函数
}
})
```
### APP 调起支付 API
:book: [官方文档 - APP 调起支付 API](https://pay.weixin.qq.com/doc/v3/merchant/4013070351)
```php
$appId = '商户申请的公众号对应的appid,由微信支付生成,可在公众号后台查看';
$config = $utils->buildAppConfig($prepayId, $appId); // 返回数组
```
调用示例:[官方文档 - APP 调起支付 API](https://pay.weixin.qq.com/doc/v3/merchant/4013070351)
### 使用微信支付公钥加密敏感字段 6.17.0+
:book: [官方文档 - 如何使用微信支付公钥加密敏感字段](https://pay.weixin.qq.com/doc/v3/merchant/4012153196)
```php
$config = [
'platform_certs' => [
// 如果是「平台证书」模式
// 可简写使用平台证书文件绝对路径
// '/path/to/wechatpay/cert.pem',
// 如果是「平台公钥」模式
// 使用Key/Value结构, key为平台公钥ID,value为平台公钥文件绝对路径
// "{$pubKeyId}" => '/path/to/wechatpay/pubkey.pem',
],
];
//使用微信支付公钥加密敏感字段可传入$serial(即 $pubKeyId),或不传默认取第一个证书
$encrypted = $utils->encryptWithRsaPublicKey($plaintext, $serial); // 返回加密后数据
```
调用示例:[官方文档 - 如何使用微信支付公钥加密敏感字段](https://pay.weixin.qq.com/doc/v3/merchant/4013053257)
# 二维码生成工具推荐
> :heart: 建议由前端生成二维码
确实需要用 PHP 生成二维码,那么以下这些供参考:
- [endroid/QrCode](https://github.com/endroid/QrCode)
- [Bacon/BaconQrCode](https://github.com/Bacon/BaconQrCode)
- [SimpleSoftwareIO/simple-qrcode](https://github.com/SimpleSoftwareIO/simple-qrcode) Bacon/BaconQrCode 的 Laravel 版本
- [aferrandini/PHPQRCode](https://github.com/aferrandini/PHPQRCode)
================================================
FILE: docs/src/6.x/sidebar.js
================================================
exports = module.exports = [
{
text: '开始使用',
collapsible: true,
items: [
{ text: '关于6.x', link: '/6.x/introduction.html' },
{ text: '立即开始', link: '/6.x/index.html' },
{ text: '常见问题汇总', link: '/6.x/troubleshooting.html' },
{ text: '参与贡献', link: '/6.x/contributing.html' }
]
},
{
text: '公众号',
collapsible: true,
items: [
{ text: '入门', link: '/6.x/official-account/index.html' },
{ text: '配置', link: '/6.x/official-account/config.html' },
{ text: 'API 调用', link: '/6.x/client.html' },
{ text: '服务端', link: '/6.x/official-account/server.html' },
{ text: '消息', link: '/6.x/official-account/message.html' },
{ text: '网页授权', link: '/6.x/oauth.html' },
{ text: '工具', link: '/6.x/official-account/utils.html' },
{ text: '代码示例', link: '/6.x/official-account/examples.html' }
]
},
{
text: '微信支付',
collapsible: true,
items: [
{ text: '入门', link: '/6.x/pay/index.html' },
{ text: 'API 调用', link: '/6.x/client.html' },
{ text: '回调通知', link: '/6.x/pay/server.html' },
{ text: '工具', link: '/6.x/pay/utils.html' },
{ text: '文件上传', link: '/6.x/pay/media.html' },
{ text: '代码示例', link: '/6.x/pay/examples.html' }
]
},
{
text: '小程序',
collapsible: true,
items: [
{ text: '入门', link: '/6.x/mini-app/index.html' },
{ text: 'API 调用', link: '/6.x/client.html' },
{ text: '配置', link: '/6.x/mini-app/config.html' },
{ text: '服务端', link: '/6.x/mini-app/server.html' },
{ text: '工具', link: '/6.x/mini-app/utils.html' },
{ text: '代码示例', link: '/6.x/mini-app/examples.html' }
]
},
{
text: '开放平台',
collapsible: true,
items: [
{ text: '入门', link: '/6.x/open-platform/index.html' },
{ text: 'API 调用', link: '/6.x/client.html' },
{ text: '服务端', link: '/6.x/open-platform/server.html' },
{ text: '代码示例', link: '/6.x/open-platform/examples.html' }
]
},
{
text: '企业微信',
collapsible: true,
items: [
{ text: '入门', link: '/6.x/work/index.html' },
{ text: 'API 调用', link: '/6.x/client.html' },
{ text: '服务端', link: '/6.x/work/server.html' },
{ text: '网页授权', link: '/6.x/work/oauth.html' },
{ text: '工具', link: '/6.x/work/utils.html' },
{ text: '代码示例', link: '/6.x/work/examples.html' }
]
},
{
text: '企业微信开放平台',
collapsible: true,
items: [
{ text: '入门', link: '/6.x/open-work/index.html' },
{ text: 'API 调用', link: '/6.x/client.html' },
{ text: '服务端', link: '/6.x/open-work/server.html' },
{ text: '网页授权', link: '/6.x/open-work/oauth.html' },
{ text: '代码示例', link: '/6.x/open-work/examples.html' }
]
},
{
text: '通用',
collapsible: true,
items: [
{ text: 'API 调用', link: '/6.x/client.html' },
{ text: '网页授权', link: '/6.x/oauth.html' },
{ text: '自定义缓存', link: '/6.x/cache.html' },
{ text: '日志', link: '/6.x/logging.html' }
]
}
]
================================================
FILE: docs/src/6.x/troubleshooting.md
================================================
# 疑难解答
在微信公众平台开发的道路上,遍布着各种大大小小的坑,有的人掉坑里,几经折腾又爬出来了,然后拍拍屁股走人。然而坑还在那里,还会继续有后来人掉进去……
这,是我们不愿看到的。
所以在这里,我们将陆续将微信开发中可能遇到的各种疑难问题进行汇总,并给出对应的解决办法。一般情况下,这些问题都可以对号入座,轻松地解决。但也不排除特殊情况,这时候你遇到的问题与文中某一个症状一致,但文中所给的解决方案并不奏效,这种情况下就需要发挥你自己的智慧,去……折腾了……
我们期待这一版块为各位的开发带来便利,同时也希望各位本着开源、分享的精神对其进行补充和完善,将各种坑一一填小、填平,让微信开发变得不那么痛苦,甚至,变成一件快乐的事……
## 时区不对
使用命令 `date` 可以在服务器上查看当前时间,如果发现时区不对则需要修改时区:[Setting The Correct Timezone In CentOS And Ubuntu Servers With NTP](https://www.liberiangeek.net/2013/02/setting-the-correct-timezone-in-centos-and-ubuntu-servers-with-ntp/)
## curl: (60) SSL certificate problem: unable to get local issuer certificate
这是 SSL 证书问题所致,在使用 SDK 调用微信支付等相关的操作时可能会遇到报 “SSL certificate problem: unable to get local issuer certificate” 的错误。
微信公众平台提供的文档中建议对部分较敏感的操作接口使用 https 协议进行访问,例如微信支付和红包等接口中涉及到操作商户资金的一些操作。
wechat SDK 遵循了官方建议,所以在调用这些接口时,除了按照官方文档设置操作证书文件外,还需要保证服务器正确安装了 CA 证书。
1. 下载 CA 证书
你可以从 http://curl.haxx.se/ca/cacert.pem 下载,或者使用操作系统提供的包管理器比如`brew install ca-certificates`安装或者更新CA根证书。
2. 在 `php.ini` 中配置 CA 证书
只需要将上面下载好的 CA 证书放置到您的服务器上某个位置,然后修改 `php.ini` 的 `curl.cainfo` 为该路径(**绝对路径!**),重启 `php-fpm` 服务即可。
```ini
curl.cainfo = /path/to/downloaded/cacert.pem
```
> 注意证书文件**路径为绝对路径**!以自己实际情况为准。
其它修改 HTTP 类源文件的方式是不允许的。
## cURL error 56: SSLRead() return error -9806
目前在 OSX 下,发现使用 HomeBrew 装的 PHP 7.0 有这个问题,解决方案是重新 brew 安装 PHP:
```shell
$ brew install homebrew/php/php70 --with-homebrew-openssl --with-homebrew-curl --without-snmp -vvv
```
验证:
```shell
$ php -i | grep 'OpenSSL support'
OpenSSL support => enabled
OpenSSL support => enabled
```
## 支付失败!当前页面的 URL 未注册
这是由于微信支付授权目录未正确配置引起的。此时开发者应该登录微信公众平台,进入**【微信支付】->【开发设置】**进行设置。
1. 公众号可添加 3 个支付授权目录,满足不同应用使用同一个公众号进行支付的业务需求。
2. 正确的**【支付授权目录】**应以 `http://` 或 `https://` 开头,并以正斜杠 `/` 结尾,授权目录所包含的域名**必须经过 ICP 备案**。
3. 支付授权目录需**细化至二级或三级目录**。
4. 所有**实际调起微信支付请求的页面都必须要所配置的支付授权目录之下**。
5. 在开发过程中,也可以使用测试授权目录进行开发测试,此时还**应该将参与测试的个人微信号添加到测试白名单中**,否则将出现对应的错误提示……
> 配置前请先理解**页面**、**目录**、**URL **以及**域名**等几个基本概念,并对自己所使用的框架的路由机制有一个大致了解。这样你才会知道自己正在配置的参数是个啥玩意儿,有什么卵用…… :smile:
## redirect_url 参数错误
这是由于程序使用了**网页授权**而公众号没有正确配置**【网页授权域名】**所致。此时你需要登录[微信公众平台](https://mp.weixin.qq.com/),在【开发】->【接口权限】页面找到**网页授权获取用户基本信息**进行配置并保存。
1. 网页授权域名应该为通过 ICP 备案的有效域名,否则保存时无法通过安全监测。
2. 网页授权域名即程序完成授权获得授权 code 后跳转到的页面的域名,一般情况下为你的业务域名。
3. 网页授权域名配置成功后会立即生效。
4. 公众号的网页授权域名只可配置一个,请合理规划你的业务,否则你会发现……授权域名不够用哈。
## [JSAPI] config: invalid url domain
在使用 JS-SDK 进行开发时,每个页面都需要调用 wx.config() 方法配置 JSPAI 参数。如果没有正确配置 **JSAPI 安全域名**并且开启了调试模式,此时就报此错误。遇到这个问题时,开发者需要登录微信公众平台,进入【公众号设置】->【功能设置】页面,将项目所使用的域名添加至 **【JSAPI 安全域名】**列表中。
1. 一个公众号同时最多可绑定**三个**安全域名,并且这些域名必须为通过 **ICP 备案**的**一级或一级以上**的有效域名。
2. JSAPI 安全域名每个月**限修改三次**,修改任何一个都算,所以,请谨慎操作。
3. 如果需要使用 JSAPI 调起支付功能,则支付目录必须也在所配置的**安全域名之下**,并且需要将支付目录添加至**支付授权目录**。
## token 验证失败、向公众号发送消息无任何反应
相信对接公众号一般是微信开发者进行开发过程中最先进行的工作,而在这看似简单的配置操作中,也可能会掉坑里。
最常见的两种情况就如下:
1. 确认你 “**启用**” 了开发模式, token 验证通过不代表启用,保存后也不代表启用。看到红色 “**停用**” 才真正的是启用了。
2. 配置好 URL(服务器地址)以及 Token(令牌)后,点击保存时提示**token 验证失败**,出现这种情况的原因有多种,其中之一便是网络不稳定,所以**可尝试多次保存**,若始终无法通过再排查其它可能因素。
3. 配置保存成功之后,向公众号发送消息无任何反应,自己的消息处理程序也没有被调用的记录(无对应日志)。这种情况下如果你尝试**反复停用和启用服务器配置**,可能突然间惊奇地了现,问题莫名其妙的解决了。
4. 使用在线调试工具的消息接口,[https://mp.weixin.qq.com/debug/](https://mp.weixin.qq.com/debug/),只要返回绿色的“**请求成功**”,就代表你的代码没有问题,请**重复上面第 3 项**再测试。
5. **如果你在用什么本地开发工具,或者什么 ngrok 代理到本机这样的开发方式,那么失败就很正常了,微信服务器到你机器的网络延迟太大(还是用服务器开发吧)。**
> 请开发者理解服务器 TOKEN 验证原理(官方文档有说明)并谨记服务器验证时使用 GET 方式访问,而公众平台向你的服务器发送消息/数据则使用 POST 方式,所以服务器验证成功之后,在某些启用了 CSRF 验证的框架里,接收消息时可能还会遇到 CSRF 相关的问题,请根据自己项目实际情况进行排查。
> 另外有的朋友的 Laravel 里使用了 laravel-debugbar,这个组件的原理是在页面输出时在后面添加 HTML 来实现的,所以它会改变我们返回给微信的内容,此时要么卸载,要么禁用掉它。
## Maximum function nesting level of '100' reached, aborting!
在使用了 Xdebug 的环境下可能出现这个问题。这是由于 Xdebug 限制函数嵌套的最大层级数(默认为 100),当嵌套次数达到该值便会触发 Xdebug 跳出嵌套并报此错误。
为避免这个问题,**可以将 Xdebug 的 max_nesting_level 参数适当设置大一些**,通常设置为 200 就可以了(当然可根据自己实际情况设置为更大的值)。
如下,修改 php.ini 配置文件后,重启 Apache 或 php-fpm 服务即可。
```ini
xdebug.max_nesting_level=200
```
## 扫码支付 获取商户订单信息超时或商户返回 httpcode 非 200!
1.确定签名正确,使用 SDK 基本上不会出什么问题 2.微信调用扫码支付回调链接,使用 POST 方式,确定服务器回调方法是否取消 csrf 验证
## Request access_token fail:{"errcode":61023,"errmsg":"refresh_token is invalid hint: [zDNUIA07582974]"}!
在用户授权时会获得该 authorizer_refresh_token 刷新令牌,而当缓存或数据库存储的该 authorizer_refresh_token 刷新令牌丢失后,可能会出现该问题,微信文档中说明
1.接口调用凭据刷新令牌(在授权的公众号具备 API 权限时,才有此返回值),刷新令牌主要用于第三方平台获取和刷新已授权用户的 access_token,只会在授权时刻提供,请妥善保存。
2.一旦丢失,只能让用户重新授权,才能再次拿到新的刷新令牌(https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1453779503&token=&lang=)。
3.为避免该问题,请将存储该刷新令牌的缓存有效期设置为 0(永久存储),并尽量不要去将该缓存或数据库清空。
如下:以 redis 为例。
```php
'expire' => 0,
```
================================================
FILE: docs/src/6.x/work/examples.md
================================================
---
aside: false
title: 企业微信使用代码示例
---
# 示例
> 👏🏻 欢迎点击本页下方 "帮助我们改善此页面!" 链接参与贡献更多的使用示例!
被动回复一个图片信息
> [官方文档](https://developer.work.weixin.qq.com/document/path/90241)
```php
$server->with(function ($message) {
return [
'MsgType' => 'image',
'Image' => [
'MediaId' => $message['MediaId'],
],
]);
};
```
`$server` 见[这里](server),`media_id` 需提前由 [企业微信>素材管理](https://developer.work.weixin.qq.com/document/path/91054) 接口产生。
================================================
FILE: docs/src/6.x/work/index.md
================================================
# 企业微信
请仔细阅读并理解:[企业微信 API - 企业内部开发](https://open.work.weixin.qq.com/api/doc/90000/90135/90664)
## 实例化
```php
'wx3cf0f39249eb0exx',
'secret' => 'f1c242f4f28f735d4687abb469072axx',
'token' => 'easywechat',
'aes_key' => '35d4687abb469072a29f1c242xxxxxx',
// 记得配置suite_id,不然suite_ticket不能自动存储
'suite_id' => 'ww9f1388bf664xxxxx',
'suite_secret' => 'reuXvCX_5FhDVm_sOslJEHRVxxxxxxx'
/**
* 接口请求相关配置,超时时间等,具体可用参数请参考:
* https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
*/
'http' => [
'throw' => true, // 状态码非 200、300 时是否抛出异常,默认为开启
'timeout' => 5.0,
// 'base_uri' => 'https://qyapi.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用,根据不同的模块配置不同的 uri
'retry' => true, // 使用默认重试配置
// 'retry' => [
// // 仅以下状态码重试
// 'status_codes' => [429, 500]
// // 最大重试次数
// 'max_retries' => 3,
// // 请求间隔 (毫秒)
// 'delay' => 1000,
// // 如果设置,每次重试的等待时间都会增加这个系数
// // (例如. 首次:1000ms; 第二次: 3 * 1000ms; etc.)
// 'multiplier' => 3
// ],
],
];
$app = new Application($config);
```
## API
Application 就是一个工厂类,所有的模块都是从 `$app` 中访问,并且几乎都提供了协议和 setter 可自定义修改。
### 服务端
服务端模块封装了服务端相关的便捷操作,隐藏了部分复杂的细节,基于中间件模式可以更方便的处理消息推送和服务端验证。
```php
$app->getServer();
```
:book: 更多说明请参阅:[服务端使用文档](server.md)
### API Client
封装了多种模式的 API 调用类,你可以选择自己喜欢的方式调用开放平台任意 API,默认自动处理了 access_token 相关的逻辑。
```php
$app->getClient();
```
:book: 更多说明请参阅:[API 调用](../client.md)
### 配置
```php
$config = $app->getConfig();
```
你可以轻松使用 `$config->get($key, $default)` 读取配置,或使用 `$config->set($key, $value)` 在调用前修改配置项。
### getAccessToken
access_token 是 API 调用的必备条件,如果你想获取它的值,你可以通过以下方式拿到当前的 access_token:
```php
$accessToken = $app->getAccessToken();
$accessToken->getToken(); // string
```
当然你也可以使用自己的 getAccessToken 类:
```php
$accessToken = new MyCustomAccessToken();
$app->getAccessToken($accessToken)
```
### 企业账户
企业账号类,提供一系列 API 获取企业的基本信息:
```php
$account = $app->getAccount();
$account->getCorpId();
$account->getSecret();
$account->getToken();
$account->getAesKey();
```
## 企业网页授权
> [点此查看官方文档](https://open.work.weixin.qq.com/api/doc/90000/90135/91020)
```php
$oauth = $app->getOAuth();
```
:book: 详情请参考:[网页授权](./oauth.md)
================================================
FILE: docs/src/6.x/work/oauth.md
================================================
# OAuth
> 此文档为企业微信内部应用开发的网页授权,非第三方应用网页授权
[企业微信官方文档](https://work.weixin.qq.com/api/doc#90000/90135/91020)
创建实例:
```php
use EasyWeChat\Work\Application;
$config = [
'corp_id' => 'xxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxx', // 应用的 secret
];
$app = new Application($config);
```
## 跳转授权
```php
// $callbackUrl 为授权回调地址
$callbackUrl = 'https://xxx.xxx'; // 需设置可信域名
// 返回授权跳转链接
$redirectUrl = $app->getOAuth()->redirect($callbackUrl);
```
## 获取授权用户信息
在回调页面中,你可以使用以下方式获取授权者信息:
```php
$code = "回调URL中的code";
$user = $app->getOAuth()->detailed()->userFromCode($code);
// 获取用户信息
$user->getId(); // 对应企业微信英文名(userid)
$user->getRaw(); // 获取企业微信接口返回的原始信息
```
:book: OAuth 详情请参考:[网页授权](../oauth.md)
获取用户其他信息需调用通讯录接口,参考:[企业微信通讯录 API](https://github.com/EasyWeChat/docs/blob/master/wework/contacts.md)
## 参考阅读
- 本模块基于 [overtrue/socialite](https://github.com/overtrue/socialite/) 实现,更多的使用请阅读该扩展包文档。
- state 参数的使用: [overtrue/socialite/#state](https://github.com/overtrue/socialite/#state)
================================================
FILE: docs/src/6.x/work/server.md
================================================
# 服务端
企业微信服务端推送和公众号一样,请参考:[公众号:服务端](../official-account/server.md)
## 第三方平台推送事件
企业微信数据推送的有以下事件:
- 通讯录变更(Event) `change_contact`
- ChangeType
- 成员变更
- 新增成员 `create_user`
- 更新成员 `update_user`
- 删除成员 `delete_user`
- 部门变更
- 新增部门 `create_party`
- 更新部门 `update_party`
- 删除部门 `delete_party`
- 标签变更
- 成员标签变更 `update_tag`
- 批量任务执行完成 `batch_job_result`
## 内置消息处理器
### 处理通讯录变更事件(包括成员变更、部门变更、成员标签变更)
```php
$server->handleContactChanged(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### 处理任务执行完成事件
```php
$server->handleBatchJobsFinished(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### 成员变更事件
```php
// 新增成员
$server->handleUserCreated(function($message, \Closure $next) {
// ...
return $next($message);
});
// 更新成员
$server->handleUserUpdated(function($message, \Closure $next) {
// ...
return $next($message);
});
// 删除成员
$server->handleUserDeleted(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### 部门变更事件
```php
// 新增部门
$server->handlePartyCreated(function($message, \Closure $next) {
// ...
return $next($message);
});
// 更新部门
$server->handlePartyUpdated(function($message, \Closure $next) {
// ...
return $next($message);
});
// 删除部门
$server->handlePartyDeleted(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### 成员标签变更事件
```php
$server->handleUserTagUpdated(function($message, \Closure $next) {
// ...
return $next($message);
});
```
### 智能机器人事件
因智能机器人消息变更为JSON格式,需要在获取 `server` 对象时指定消息格式为json:
```php
// 指定消息格式 JSON
$server = $app->getServer(messageType: 'json');
// 获取解密后的机器人消息
$message = $server->getDecryptedMessage();
// 回复消息
$server->with(function($message, \Closure $next) {
return [
'msgtype' => 'stream',
'stream' => [
'id' => 'id00001',
'finish' => true,
'content' => '信息已收到',
],
];
});
```
回复消息具体格式请参考官方文档:[企业微信智能机器人文档](https://developer.work.weixin.qq.com/document/path/101039)
## 其它事件处理
以上便捷方法都只处理了特定事件,其它状态,可以通过自定义事件处理中间件的形式处理:
```php
$server->with(function($message, \Closure $next) {
// $message->event_type 事件类型
return $next($message);
});
```
## 自助处理推送消息
你可以通过下面的方式获取来自微信服务器的推送消息:
```php
$message = $server->getRequestMessage(); // 原始消息
```
你也可以获取解密后的消息 6.5.0+
```php
$message = $server->getDecryptedMessage();
```
`$message` 为一个 `EasyWeChat\Work\Message` 实例。
你可以在处理完逻辑后自行创建一个响应,当然,在不同的框架里,响应写法也不一样,请自行实现。
================================================
FILE: docs/src/6.x/work/utils.md
================================================
# 工具6.7.1+
提供企业微信网页开发 JS-SDK 相关方法
## 配置
```php
getUtils();
```
## 生成 config 接口配置
:book: [官方文档 - config 接口配置 说明文档](https://open.work.weixin.qq.com/api/doc/90001/90144/90547)
```php
$config = $utils->buildJsSdkConfig(
string $url,
array $jsApiList,
array $openTagList = [],
bool $debug = false,
bool $beta = true
);
// print
[
'jsApiList' => ['api1','api2'],
'openTagList' => ['openTag1','openTag2'],
'debug' => false,
'beta' => true,
'url' => 'https://easywechat.com/',
'nonceStr' => 'mock-nonce',
'timestamp' => 1601234567,
'appId' => 'mock-appid',
'signature' => '22772d2fb393ab9f7f6a5a54168a566fbf1ab767'
];
```
## 生成 agentConfig 接口配置
:book: [官方文档 - agentConfig 接口配置 说明文档](https://open.work.weixin.qq.com/api/doc/90001/90144/94325)
```php
$config = $utils->buildJsSdkAgentConfig(
int $agentId,
string $url,
array $jsApiList,
array $openTagList = [],
bool $debug = false
);
// print
[
'jsApiList' => ['api1','api2'],
'openTagList' => ['openTag1','openTag2'],
'debug' => false,
'url' => 'https://easywechat.com/',
'nonceStr' => 'mock-nonce',
'timestamp' => 1601234567,
'corpid' => 'mock-corpid',
'agentid' => 100001,
'signature' => '22772d2fb393ab9f7f6a5a54168a566fbf1ab767'
];
```
================================================
FILE: docs/src/index.md
================================================
---
layout: page
pageClass: im-home
title: EasyWeChat - 一个 PHP 微信开发 SDK
---
每一个细节,都经过精心打磨,只为了提供更好的开发体验。
composer require w7corp/easywechat
立即开始
================================================
FILE: docs/tailwind.config.js
================================================
module.exports = {
darkMode: 'class',
theme: {
extend: {}
},
variants: {},
plugins: [],
content: [
'./src/**/*.md',
'./.vitepress/theme/components/*.vue',
'./.vitepress/theme/styles/*.scss',
],
}
================================================
FILE: docs/tsconfig.json
================================================
{
"compilerOptions": {
"outDir": "dist",
"target": "esnext",
"moduleResolution": "node",
"esModuleInterop": true,
"resolveJsonModule": true,
"allowJs": true,
"strict": true,
"baseUrl": ".",
"paths": {
"/@theme/*": [".vitepress/theme/*"]
}
},
"include": ["env.d.ts", "src/**/*", ".vitepress/**/*"]
}
================================================
FILE: phpstan.neon
================================================
parameters:
level: 9
paths:
- src
inferPrivatePropertyTypeFromConstructor: true
ignoreErrors:
-
identifier: missingType.iterableValue
-
message: '#Property EasyWeChat\\Kernel\\Config::\$items \(array\) does not accept array#'
path: src/Kernel/Config.php
-
message: '#\$client .*? does not accept#'
path: src/Kernel/HttpClient/AccessTokenAwareClient.php
-
message: '#ServerResponse::with.*? should return static\(EasyWeChat\\Kernel\\ServerResponse\) but returns Psr\\Http\\Message\\ResponseInterface#'
path: src/Kernel/ServerResponse.php
-
message: '#Parameter \#1 \$object of function spl_object_hash expects object, callable given#'
path: src/Kernel/Traits/InteractWithHandlers.php
-
message: '#Call to function is_callable\(\) with callable\(\): mixed will always evaluate to true#'
path: src/Kernel/Traits/InteractWithHandlers.php
-
message: '#Parameter \$stable of class EasyWeChat\\MiniApp\\AccessToken constructor expects bool\|null, mixed given#'
path: src/MiniApp/Application.php
-
message: '#Parameter \#1 \$options of static method EasyWeChat\\Kernel\\HttpClient\\RequestUtil::mergeDefaultRetryOptions\(\) expects array#'
path: src/MiniApp/Application.php
-
message: '#Method EasyWeChat\\MiniApp\\Decryptor::decrypt\(\) should return array but returns array#'
path: src/MiniApp/Decryptor.php
-
message: '#Parameter \$stable of class EasyWeChat\\OfficialAccount\\(AccessToken|JsApiTicket) constructor expects bool\|null, mixed given#'
path: src/OfficialAccount/Application.php
-
message: '#Parameter \#1 \$options of static method EasyWeChat\\Kernel\\HttpClient\\RequestUtil::mergeDefaultRetryOptions\(\) expects array#'
path: src/OfficialAccount/Application.php
-
message: '#Parameter \#1 \$scopes of method Overtrue\\Socialite\\Providers\\Base::scopes\(\) expects array#'
path: src/OfficialAccount/Application.php
-
message: '#Parameter \#1 \$scopes of method Overtrue\\Socialite\\Providers\\Base::scopes\(\) expects array#'
path: src/OpenPlatform/Application.php
-
message: '#Parameter \#1 \$scopes of method Overtrue\\Socialite\\Providers\\Base::scopes\(\) expects array#'
path: src/OpenWork/Application.php
-
message: '#Parameter \#3 \$defaultOptions of class EasyWeChat\\Pay\\Client constructor expects array#'
path: src/Pay/Application.php
-
message: '#Property .*?\$client \(Symfony\\Contracts\\HttpClient\\HttpClientInterface\) does not accept Mockery\\Mock\|Symfony\\Contracts\\HttpClient\\HttpClientInterface#'
path: src/Pay/Client.php
-
message: '#Method EasyWeChat\\Pay\\Client::createMockClient\(\) should return Mockery\\Mock\|Symfony\\Contracts\\HttpClient\\HttpClientInterface but returns Mockery\\LegacyMockInterface#'
path: src/Pay/Client.php
-
message: '#Parameter \#1 \$scopes of method Overtrue\\Socialite\\Providers\\Base::scopes\(\) expects array#'
path: src/Work/Application.php
-
message: '#Trait .*? is used zero times and is not analysed#'
path: src/Kernel/Traits/DecryptJsonMessage.php
-
message: '#Trait .*? is used zero times and is not analysed#'
path: src/Kernel/Traits/DecryptXmlMessage.php
================================================
FILE: phpunit.xml
================================================
./tests/
src/
src/
src/
src/Kernel/Support
src/Encryption
src/Support
================================================
FILE: pint.json
================================================
{
"rules": {
"single_line_empty_body": false
}
}
================================================
FILE: src/Kernel/Config.php
================================================
*/
class Config implements ArrayAccess, ConfigInterface
{
/**
* @var array
*/
protected array $requiredKeys = [];
/**
* @param array $items
*
* @throws InvalidArgumentException
*/
public function __construct(
protected array $items = [],
) {
$this->checkMissingKeys();
}
#[\JetBrains\PhpStorm\Pure]
public function has(string $key): bool
{
return Arr::has($this->items, $key);
}
/**
* @param array|string $key
*/
#[\JetBrains\PhpStorm\Pure]
public function get(array|string $key, mixed $default = null): mixed
{
if (is_array($key)) {
return $this->getMany($key);
}
return Arr::get($this->items, $key, $default);
}
/**
* @param array $keys
* @return array
*/
#[\JetBrains\PhpStorm\Pure]
public function getMany(array $keys): array
{
$config = [];
foreach ($keys as $key => $default) {
if (is_numeric($key)) {
[$key, $default] = [$default, null];
}
$config[$key] = Arr::get($this->items, $key, $default);
}
return $config;
}
public function set(string $key, mixed $value = null): void
{
Arr::set($this->items, $key, $value);
}
/**
* @return array
*/
public function all(): array
{
return $this->items;
}
#[\JetBrains\PhpStorm\Pure]
public function offsetExists(mixed $offset): bool
{
return $this->has(strval($offset));
}
#[\JetBrains\PhpStorm\Pure]
public function offsetGet(mixed $offset): mixed
{
return $this->get(strval($offset));
}
public function offsetSet(mixed $offset, mixed $value): void
{
$this->set(strval($offset), $value);
}
public function offsetUnset(mixed $offset): void
{
$this->set(strval($offset), null);
}
/**
* @throws InvalidArgumentException
*/
public function checkMissingKeys(): bool
{
if (empty($this->requiredKeys)) {
return true;
}
$missingKeys = [];
foreach ($this->requiredKeys as $key) {
if (! $this->has($key)) {
$missingKeys[] = $key;
}
}
if (! empty($missingKeys)) {
throw new InvalidArgumentException(sprintf("\"%s\" cannot be empty.\r\n", implode(',', $missingKeys)));
}
return true;
}
}
================================================
FILE: src/Kernel/Contracts/AccessToken.php
================================================
*/
public function toQuery(): array;
}
================================================
FILE: src/Kernel/Contracts/AccessTokenAwareHttpClient.php
================================================
*/
public function toArray(): array;
}
================================================
FILE: src/Kernel/Contracts/Config.php
================================================
*/
interface Config extends ArrayAccess
{
/**
* @return array
*/
public function all(): array;
public function has(string $key): bool;
public function set(string $key, mixed $value = null): void;
/**
* @param array|string $key
*/
public function get(array|string $key, mixed $default = null): mixed;
}
================================================
FILE: src/Kernel/Contracts/JsApiTicket.php
================================================
*/
public function configSignature(string $url, string $nonce, int $timestamp): array;
}
================================================
FILE: src/Kernel/Contracts/Jsonable.php
================================================
appId = $appId;
$this->token = $token;
$this->receiveId = $receiveId;
$this->aesKey = base64_decode($aesKey.'=', true) ?: '';
}
public function getToken(): string
{
return $this->token;
}
/**
* @throws RuntimeException
* @throws Exception
*/
public function encrypt(string $plaintext, ?string $nonce = null, int|string|null $timestamp = null, string $messageType = 'xml'): string
{
return $messageType === 'xml' ?
$this->encryptAsXml($plaintext, $nonce, $timestamp) :
$this->encryptAsJson($plaintext, $nonce, $timestamp);
}
public function encryptAsXml(string $plaintext, ?string $nonce = null, int|string|null $timestamp = null): string
{
$encrypted = $this->encryptAsArray($plaintext, $nonce, $timestamp);
$response = [
'Encrypt' => $encrypted['ciphertext'],
'MsgSignature' => $encrypted['signature'],
'TimeStamp' => $encrypted['timestamp'],
'Nonce' => $encrypted['nonce'],
];
return Xml::build($response);
}
public function encryptAsJson(string $plaintext, ?string $nonce = null, int|string|null $timestamp = null): string
{
$encrypted = $this->encryptAsArray($plaintext, $nonce, $timestamp);
$response = [
'encrypt' => $encrypted['ciphertext'],
'msgsignature' => $encrypted['signature'],
'timestamp' => $encrypted['timestamp'],
'nonce' => $encrypted['nonce'],
];
$jsonStr = json_encode($response, JSON_UNESCAPED_UNICODE);
if ($jsonStr === false) {
throw new RuntimeException('Invalid json data.', self::ERROR_JSON_BUILD);
}
return $jsonStr;
}
/**
* @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
*/
public function encryptAsArray(string $plaintext, ?string $nonce = null, int|string|null $timestamp = null): array
{
try {
$plaintext = Pkcs7::padding(
random_bytes(self::BLOCK_SIZE).pack('N', strlen($plaintext)).$plaintext.$this->appId,
blockSize: strlen($this->aesKey)
);
$ciphertext = base64_encode(
openssl_encrypt(
$plaintext,
'aes-256-cbc',
$this->aesKey,
OPENSSL_NO_PADDING,
iv: substr($this->aesKey, 0, self::BLOCK_SIZE)
) ?: ''
);
} catch (Throwable $e) {
throw new RuntimeException($e->getMessage(), self::ERROR_ENCRYPT_AES);
}
$nonce ??= Str::random();
$timestamp ??= time();
return [
'ciphertext' => $ciphertext,
'signature' => $this->createSignature($this->token, $timestamp, $nonce, $ciphertext),
'timestamp' => $timestamp,
'nonce' => $nonce,
];
}
public function createSignature(mixed ...$attributes): string
{
sort($attributes, SORT_STRING);
return sha1(implode($attributes));
}
/**
* @throws RuntimeException
*/
public function decrypt(string $ciphertext, string $msgSignature, string $nonce, int|string $timestamp): string
{
$signature = $this->createSignature($this->token, $timestamp, $nonce, $ciphertext);
if ($signature !== $msgSignature) {
throw new RuntimeException('Invalid Signature.', self::ERROR_INVALID_SIGNATURE);
}
$plaintext = Pkcs7::unpadding(
openssl_decrypt(
base64_decode($ciphertext, true) ?: '',
'aes-256-cbc',
$this->aesKey,
OPENSSL_NO_PADDING,
iv: substr($this->aesKey, 0, self::BLOCK_SIZE)
) ?: '',
blockSize: strlen($this->aesKey)
);
$plaintext = substr($plaintext, self::BLOCK_SIZE);
$contentLength = (unpack('N', substr($plaintext, 0, 4)) ?: [])[1];
if ($this->receiveId && trim(substr($plaintext, $contentLength + 4)) !== $this->receiveId) {
throw new RuntimeException('Invalid appId.', self::ERROR_INVALID_APP_ID);
}
return substr($plaintext, 4, $contentLength);
}
}
================================================
FILE: src/Kernel/Exceptions/BadMethodCallException.php
================================================
response = $response;
if ($response) {
$response->getBody()->rewind();
}
}
}
================================================
FILE: src/Kernel/Exceptions/InvalidArgumentException.php
================================================
getMimeTypes($ext)[0] ?? 'application/octet-stream';
} else {
$tmp = tempnam(sys_get_temp_dir(), 'easywechat');
if (! $tmp) {
throw new RuntimeException('Failed to create temporary file.');
}
file_put_contents($tmp, $contents);
$contentType = $mimeTypes->guessMimeType($tmp) ?? 'application/octet-stream';
$filename = md5($contents).'.'.($mimeTypes->getExtensions($contentType)[0] ?? null);
}
}
return new self($contents, $filename, $contentType, $encoding);
}
/**
* @throws RuntimeException
*
* @deprecated since EasyWeChat 7.0, use fromContents() instead
*/
public static function withContents(
string $contents,
?string $filename = null,
?string $contentType = null,
?string $encoding = null
): DataPart {
return self::fromContents($contents, $filename, $contentType, $encoding);
}
}
================================================
FILE: src/Kernel/Form/Form.php
================================================
$fields
*/
public function __construct(protected array $fields)
{
}
/**
* @param array $fields
*/
public static function create(array $fields): Form
{
return new self($fields);
}
/**
* @return array{headers:array,body:string}
*/
#[\JetBrains\PhpStorm\ArrayShape(['headers' => 'array', 'body' => 'string'])]
public function toArray(): array
{
return $this->toOptions();
}
/**
* @return array{headers:array,body:string}
*/
#[\JetBrains\PhpStorm\ArrayShape(['headers' => 'array', 'body' => 'string'])]
public function toOptions(): array
{
$formData = new FormDataPart($this->fields);
return [
'headers' => $formData->getPreparedHeaders()->toArray(),
'body' => $formData->bodyToString(),
];
}
}
================================================
FILE: src/Kernel/HttpClient/AccessTokenAwareClient.php
================================================
client = $client ?? HttpClient::create();
}
public function withAccessToken(AccessTokenInterface $accessToken): static
{
$this->accessToken = $accessToken;
return $this;
}
/**
* @param array $options
*/
public function request(string $method, string $url, array $options = []): Response
{
if ($this->accessToken) {
$options['query'] = array_merge((array) ($options['query'] ?? []), $this->accessToken->toQuery());
}
$options = RequestUtil::formatBody($this->mergeThenResetPrepends($options));
return new Response(
response: $this->client->request($method, ltrim($url, '/'), $options),
failureJudge: $this->failureJudge,
throw: $this->throw
);
}
/**
* @param array $arguments
*/
public function __call(string $name, array $arguments): mixed
{
if (\str_starts_with($name, 'with')) {
return $this->handleMagicWithCall($name, $arguments[0] ?? null);
}
return $this->client->$name(...$arguments);
}
public static function createMockClient(MockHttpClient $mockHttpClient): HttpClientInterface
{
return new self($mockHttpClient);
}
}
================================================
FILE: src/Kernel/HttpClient/AccessTokenExpiredRetryStrategy.php
================================================
accessToken = $accessToken;
return $this;
}
public function decideUsing(Closure $decider): static
{
$this->decider = $decider;
return $this;
}
public function shouldRetry(
AsyncContext $context,
?string $responseContent,
?TransportExceptionInterface $exception
): ?bool {
if ($responseContent && $this->decider && ($this->decider)($context, $responseContent, $exception)) {
if ($this->accessToken instanceof RefreshableAccessTokenInterface) {
return (bool) $this->accessToken->refresh();
}
return false;
}
return parent::shouldRetry($context, $responseContent, $exception);
}
}
================================================
FILE: src/Kernel/HttpClient/HttpClientMethods.php
================================================
$options
*
* @throws TransportExceptionInterface
*/
public function get(string $url, array $options = []): Response|ResponseInterfaceAlias
{
return $this->request('GET', $url, RequestUtil::formatOptions($options, 'GET'));
}
/**
* @param array $options
*
* @throws TransportExceptionInterface
*/
public function post(string $url, array $options = []): Response|ResponseInterfaceAlias
{
return $this->request('POST', $url, RequestUtil::formatOptions($options, 'POST'));
}
/**
* @throws TransportExceptionInterface
*/
public function postJson(string $url, array $data = [], array $options = []): Response|ResponseInterfaceAlias
{
$options['headers']['Content-Type'] = 'application/json';
$options['json'] = $data;
return $this->request('POST', $url, RequestUtil::formatOptions($options, 'POST'));
}
/**
* @throws TransportExceptionInterface
*/
public function postXml(string $url, array $data = [], array $options = []): Response|ResponseInterfaceAlias
{
$options['headers']['Content-Type'] = 'text/xml';
if (array_key_exists('xml', $data)) {
$data = $data['xml'];
}
$options['xml'] = $data;
return $this->request('POST', $url, RequestUtil::formatOptions($options, 'POST'));
}
/**
* @param array $options
*
* @throws TransportExceptionInterface
*/
public function patch(string $url, array $options = []): Response|ResponseInterfaceAlias
{
return $this->request('PATCH', $url, RequestUtil::formatOptions($options, 'PATCH'));
}
/**
* @throws TransportExceptionInterface
*/
public function patchJson(string $url, array $options = []): Response|ResponseInterfaceAlias
{
$options['headers']['Content-Type'] = 'application/json';
return $this->request('PATCH', $url, RequestUtil::formatOptions($options, 'PATCH'));
}
/**
* @param array $options
*
* @throws TransportExceptionInterface
*/
public function put(string $url, array $options = []): Response|ResponseInterfaceAlias
{
return $this->request('PUT', $url, RequestUtil::formatOptions($options, 'PUT'));
}
/**
* @param array $options
*
* @throws TransportExceptionInterface
*/
public function delete(string $url, array $options = []): Response|ResponseInterfaceAlias
{
return $this->request('DELETE', $url, RequestUtil::formatOptions($options, 'DELETE'));
}
}
================================================
FILE: src/Kernel/HttpClient/RequestUtil.php
================================================
$options
* @return array
*/
#[\JetBrains\PhpStorm\ArrayShape([
'status_codes' => 'array',
'delay' => 'int',
'max_delay' => 'int',
'max_retries' => 'int',
'multiplier' => 'float',
'jitter' => 'float',
])]
public static function mergeDefaultRetryOptions(array $options): array
{
return \array_merge([
'status_codes' => GenericRetryStrategy::DEFAULT_RETRY_STATUS_CODES,
'delay' => 1000,
'max_delay' => 0,
'max_retries' => 3,
'multiplier' => 2.0,
'jitter' => 0.1,
], $options);
}
/**
* @param array $options
* @return array
*/
public static function formatDefaultOptions(array $options): array
{
$defaultOptions = \array_filter(
array: $options,
callback: fn ($key) => array_key_exists($key, HttpClientInterface::OPTIONS_DEFAULTS),
mode: ARRAY_FILTER_USE_KEY
);
/** @phpstan-ignore-next-line */
if (! isset($options['headers']['User-Agent']) && ! isset($options['headers']['user-agent'])) {
/** @phpstan-ignore-next-line */
$defaultOptions['headers']['User-Agent'] = UserAgent::create();
}
return $defaultOptions;
}
public static function formatOptions(array $options, string $method): array
{
if (array_key_exists('query', $options) && is_array($options['query']) && empty($options['query'])) {
return $options;
}
if (array_key_exists('body', $options)
|| array_key_exists('json', $options)
|| array_key_exists('xml', $options)
) {
return $options;
}
$contentType = $options['headers']['Content-Type'] ?? $options['headers']['content-type'] ?? null;
$name = in_array($method, ['GET', 'HEAD', 'DELETE']) ? 'query' : 'body';
if ($contentType === 'application/json') {
$name = 'json';
}
if ($contentType === 'text/xml') {
$name = 'xml';
}
foreach ($options as $key => $value) {
if (! array_key_exists($key, HttpClientInterface::OPTIONS_DEFAULTS)) {
$options[$name][trim($key, '"')] = $value;
unset($options[$key]);
}
}
return $options;
}
/**
* @param array{headers?:array, xml?:mixed, body?:array|string, json?:mixed} $options
* @return array{headers?:array|array>, xml?:array|string, body?:array|string}
*
* @throws InvalidArgumentException
*/
public static function formatBody(array $options): array
{
$contentType = $options['headers']['Content-Type'] ?? $options['headers']['content-type'] ?? null;
if (array_key_exists('xml', $options)) {
if (is_array($options['xml'])) {
$options['xml'] = Xml::build($options['xml']);
}
if (! is_string($options['xml'])) {
throw new InvalidArgumentException('The type of `xml` must be string or array.');
}
if (! $contentType) {
$options['headers']['Content-Type'] = 'text/xml';
}
$options['body'] = $options['xml'];
unset($options['xml']);
}
if (array_key_exists('json', $options)) {
if (is_array($options['json'])) {
/** XXX: 微信的 JSON 是比较奇葩的,比如菜单不能把中文 encode 为 unicode */
$options['json'] = json_encode(
$options['json'],
empty($options['json']) ? JSON_FORCE_OBJECT : JSON_UNESCAPED_UNICODE
);
}
if (! is_string($options['json'])) {
throw new InvalidArgumentException('The type of `json` must be string or array.');
}
if (! $contentType) {
$options['headers']['Content-Type'] = 'application/json';
}
$options['body'] = $options['json'];
unset($options['json']);
}
return $options;
}
public static function createDefaultServerRequest(): ServerRequestInterface
{
$psr17Factory = new Psr17Factory;
$creator = new ServerRequestCreator(
serverRequestFactory: $psr17Factory,
uriFactory: $psr17Factory,
uploadedFileFactory: $psr17Factory,
streamFactory: $psr17Factory
);
return $creator->fromGlobals();
}
}
================================================
FILE: src/Kernel/HttpClient/RequestWithPresets.php
================================================
*/
protected array $prependHeaders = [];
/**
* @var array
*/
protected array $prependParts = [];
/**
* @var array
*/
protected array $presets = [];
/**
* @param array $presets
*/
public function setPresets(array $presets): static
{
$this->presets = $presets;
return $this;
}
public function withHeader(string $key, string $value): static
{
$this->prependHeaders[$key] = $value;
return $this;
}
public function withHeaders(array $headers): static
{
foreach ($headers as $key => $value) {
$this->withHeader($key, $value);
}
return $this;
}
/**
* @throws InvalidArgumentException
*/
public function with(string|array $key, mixed $value = null): static
{
if (\is_array($key)) {
// $client->with(['appid', 'mchid'])
// $client->with(['appid' => 'wx1234567', 'mchid'])
foreach ($key as $k => $v) {
if (\is_int($k) && is_string($v)) {
[$k, $v] = [$v, null];
}
$this->with($k, $v ?? $this->presets[$k] ?? null);
}
return $this;
}
$this->prependParts[$key] = $value ?? $this->presets[$key] ?? null;
return $this;
}
/**
* @throws RuntimeException
*/
public function withFile(string $pathOrContents, string $formName = 'file', ?string $filename = null): static
{
$file = is_file($pathOrContents) ? File::fromPath(
$pathOrContents,
$filename
) : File::fromContents($pathOrContents, $filename);
/**
* @var array{headers: array, body: string} $options
*/
$options = Form::create([$formName => $file])->toOptions();
$this->withHeaders($options['headers']);
return $this->withOptions([
'body' => $options['body'],
]);
}
/**
* @throws RuntimeException
*/
public function withFileContents(string $contents, string $formName = 'file', ?string $filename = null): static
{
return $this->withFile($contents, $formName, $filename);
}
/**
* @throws RuntimeException
*/
public function withFiles(array $files): static
{
foreach ($files as $key => $value) {
$this->withFile($value, $key);
}
return $this;
}
/**
* @return array{xml?:array|string,json?:array|string,body?:array|string,query?:array,headers?:array}
*/
public function mergeThenResetPrepends(array $options, string $method = 'GET'): array
{
$name = in_array(strtoupper($method), ['GET', 'HEAD', 'DELETE']) ? 'query' : 'body';
if (($options['headers']['Content-Type'] ?? $options['headers']['content-type'] ?? null) === 'application/json' || ! empty($options['json'])) {
$name = 'json';
}
if (($options['headers']['Content-Type'] ?? $options['headers']['content-type'] ?? null) === 'text/xml' || ! empty($options['xml'])) {
$name = 'xml';
}
if (! empty($this->prependParts)) {
$options[$name] = array_merge($this->prependParts, $options[$name] ?? []);
}
if (! empty($this->prependHeaders)) {
$options['headers'] = array_merge($this->prependHeaders, $options['headers'] ?? []);
}
$this->prependParts = [];
$this->prependHeaders = [];
return $options;
}
/**
* @throws InvalidArgumentException
*/
public function handleMagicWithCall(string $method, mixed $value = null): static
{
// $client->withAppid();
// $client->withAppid('wxf8b4f85f3a794e77');
// $client->withAppidAs('sub_appid');
if (! str_starts_with($method, 'with')) {
throw new InvalidArgumentException(sprintf('The method "%s" is not supported.', $method));
}
$key = Str::snakeCase(substr($method, 4));
// $client->withAppidAs('sub_appid');
if (str_ends_with($key, '_as')) {
$key = substr($key, 0, -3);
[$key, $value] = [is_string($value) ? $value : $key, $this->presets[$key] ?? null];
}
return $this->with($key, $value);
}
}
================================================
FILE: src/Kernel/HttpClient/Response.php
================================================
*
* @see \Symfony\Contracts\HttpClient\ResponseInterface
*/
class Response implements Arrayable, ArrayAccess, Jsonable, ResponseInterface, StreamableInterface
{
public function __construct(
protected ResponseInterface $response,
protected ?Closure $failureJudge = null,
protected bool $throw = true
) {
}
public function throw(bool $throw = true): static
{
$this->throw = $throw;
return $this;
}
public function throwOnFailure(): static
{
return $this->throw(true);
}
public function quietly(): static
{
return $this->throw(false);
}
public function judgeFailureUsing(callable $callback): static
{
$this->failureJudge = $callback instanceof Closure ? $callback : fn (Response $response) => $callback($response);
return $this;
}
public function isSuccessful(): bool
{
return ! $this->isFailed();
}
public function isFailed(): bool
{
if ($this->is('text') && $this->failureJudge) {
return (bool) ($this->failureJudge)($this);
}
try {
return $this->getStatusCode() >= 400;
} catch (Throwable $e) {
return true;
}
}
/**
* @throws BadResponseException
*/
public function toArray(?bool $throw = null): array
{
$throw ??= $this->throw;
if ('' === $content = $this->response->getContent($throw)) {
throw new BadResponseException('Response body is empty.');
}
$contentType = $this->getHeaderLine('content-type', $throw);
if (str_contains($contentType, 'text/xml')
|| str_contains($contentType, 'application/xml')
|| str_starts_with($content, '')) {
try {
return Xml::parse($content) ?? [];
} catch (Throwable $e) {
throw new BadResponseException('Response body is not valid xml.', 400, $e);
}
}
return $this->response->toArray($throw);
}
public function toJson(?bool $throw = null): string|false
{
return json_encode($this->toArray($throw), JSON_UNESCAPED_UNICODE);
}
/**
* {@inheritdoc}
*
* @throws BadMethodCallException
*/
public function toStream(?bool $throw = null)
{
if ($this->response instanceof StreamableInterface) {
return $this->response->toStream($throw ?? $this->throw);
}
if ($throw) {
throw new BadMethodCallException(sprintf('%s does\'t implements %s', \get_class($this->response), StreamableInterface::class));
}
return StreamWrapper::createResource(new MockResponse);
}
/**
* @throws \LogicException
*/
public function toDataUrl(): string
{
return 'data:'.$this->getHeaderLine('content-type').';base64,'.base64_encode($this->getContent());
}
public function toPsrResponse(?ResponseFactoryInterface $responseFactory = null, ?StreamFactoryInterface $streamFactory = null): \Psr\Http\Message\ResponseInterface
{
$streamFactory ??= $responseFactory instanceof StreamFactoryInterface ? $responseFactory : null;
if ($responseFactory === null || $streamFactory === null) {
if (! class_exists(Psr17Factory::class) && ! class_exists(Psr17FactoryDiscovery::class)) {
throw new \LogicException('You cannot use the "Symfony\Component\HttpClient\Psr18Client" as no PSR-17 factories have been provided. Try running "composer require nyholm/psr7".');
}
try {
$psr17Factory = class_exists(Psr17Factory::class, false) ? new Psr17Factory : null;
$responseFactory ??= $psr17Factory ?? Psr17FactoryDiscovery::findResponseFactory(); /** @phpstan-ignore-line */
$streamFactory ??= $psr17Factory ?? Psr17FactoryDiscovery::findStreamFactory(); /** @phpstan-ignore-line */
/** @phpstan-ignore-next-line */
} catch (NotFoundException $e) {
throw new \LogicException('You cannot use the "Symfony\Component\HttpClient\HttplugClient" as no PSR-17 factories have been found. Try running "composer require nyholm/psr7".', 0, $e);
}
}
$psrResponse = $responseFactory->createResponse($this->getStatusCode());
foreach ($this->getHeaders(false) as $name => $values) {
foreach ($values as $value) {
$psrResponse = $psrResponse->withAddedHeader($name, $value);
}
}
$body = $this->response instanceof StreamableInterface ? $this->toStream(false) : StreamWrapper::createResource($this->response);
$body = $streamFactory->createStreamFromResource($body);
if ($body->isSeekable()) {
$body->seek(0);
}
return $psrResponse->withBody($body);
}
/**
* @throws BadResponseException
*/
public function saveAs(string $filename): string
{
try {
file_put_contents($filename, $this->response->getContent(true));
} catch (Throwable $e) {
throw new BadResponseException(sprintf(
'Cannot save response to %s: %s',
$filename,
$this->response->getContent(false)
), $e->getCode(), $e);
}
return '';
}
public function offsetExists(mixed $offset): bool
{
return array_key_exists($offset, $this->toArray());
}
public function offsetGet(mixed $offset): mixed
{
return $this->toArray()[$offset] ?? null;
}
/**
* @throws BadMethodCallException
*/
public function offsetSet(mixed $offset, mixed $value): void
{
throw new BadMethodCallException('Response is immutable.');
}
/**
* @throws BadMethodCallException
*/
public function offsetUnset(mixed $offset): void
{
throw new BadMethodCallException('Response is immutable.');
}
/**
* @param array $arguments
*/
public function __call(string $name, array $arguments): mixed
{
return $this->response->{$name}(...$arguments);
}
public function getStatusCode(): int
{
return $this->response->getStatusCode();
}
public function getHeaders(?bool $throw = null): array
{
return $this->response->getHeaders($throw ?? $this->throw);
}
public function getContent(?bool $throw = null): string
{
return $this->response->getContent($throw ?? $this->throw);
}
public function cancel(): void
{
$this->response->cancel();
}
public function getInfo(?string $type = null): mixed
{
return $this->response->getInfo($type);
}
public function __toString(): string
{
return $this->toJson() ?: '';
}
public function hasHeader(string $name, ?bool $throw = null): bool
{
return isset($this->getHeaders($throw)[$name]);
}
/**
* @return array
*/
public function getHeader(string $name, ?bool $throw = null): array
{
$name = strtolower($name);
$throw ??= $this->throw;
return $this->hasHeader($name, $throw) ? $this->getHeaders($throw)[$name] : [];
}
public function getHeaderLine(string $name, ?bool $throw = null): string
{
$name = strtolower($name);
$throw ??= $this->throw;
return $this->hasHeader($name, $throw) ? implode(',', $this->getHeader($name, $throw)) : '';
}
public function is(string $type): bool
{
$contentType = $this->getHeaderLine('content-type');
return match (strtolower($type)) {
'json' => str_contains($contentType, '/json'),
'xml' => str_contains($contentType, '/xml'),
'html' => str_contains($contentType, '/html'),
'image' => str_contains($contentType, 'image/'),
'audio' => str_contains($contentType, 'audio/'),
'video' => str_contains($contentType, 'video/'),
'text' => str_contains($contentType, 'text/')
|| str_contains($contentType, '/json')
|| str_contains($contentType, '/xml'),
default => false,
};
}
}
================================================
FILE: src/Kernel/HttpClient/RetryableClient.php
================================================
$config
*/
public function retry(array $config = []): static
{
$config = RequestUtil::mergeDefaultRetryOptions($config);
$strategy = new GenericRetryStrategy(
// @phpstan-ignore-next-line
(array) $config['status_codes'],
// @phpstan-ignore-next-line
(int) $config['delay'],
// @phpstan-ignore-next-line
(float) $config['multiplier'],
// @phpstan-ignore-next-line
(int) $config['max_delay'],
// @phpstan-ignore-next-line
(float) $config['jitter']
);
/** @phpstan-ignore-next-line */
return $this->retryUsing($strategy, (int) $config['max_retries']);
}
public function retryUsing(
RetryStrategyInterface $strategy,
int $maxRetries = 3,
?LoggerInterface $logger = null
): static {
$this->client = new RetryableHttpClient($this->client, $strategy, $maxRetries, $logger);
return $this;
}
}
================================================
FILE: src/Kernel/HttpClient/ScopingHttpClient.php
================================================
client = $client;
$this->defaultOptionsByRegexp = $defaultOptionsByRegexp;
}
public function request(string $method, string $url, array $options = []): ResponseInterface
{
foreach ($this->defaultOptionsByRegexp as $regexp => $defaultOptions) {
if (preg_match($regexp, $url)) {
$options = self::mergeDefaultOptions($options, $defaultOptions, true);
break;
}
}
return $this->client->request($method, $url, $options);
}
public function stream(ResponseInterface|iterable $responses, ?float $timeout = null): ResponseStreamInterface
{
return $this->client->stream($responses, $timeout);
}
/**
* @return void
*/
public function reset()
{
if ($this->client instanceof ResetInterface) {
$this->client->reset();
}
}
public function setLogger(LoggerInterface $logger): void
{
if ($this->client instanceof LoggerAwareInterface) {
$this->client->setLogger($logger);
}
}
}
================================================
FILE: src/Kernel/Message.php
================================================
*/
abstract class Message implements \JsonSerializable, ArrayAccess, Jsonable
{
use HasAttributes;
/**
* @param array $attributes
*/
final public function __construct(array $attributes = [], protected ?string $originContent = '')
{
$this->attributes = $attributes;
}
/**
* @throws BadRequestException
*/
public static function createFromRequest(ServerRequestInterface $request): Message
{
return static::createFromStringContent(strval($request->getBody()));
}
/**
* @throws BadRequestException
*/
public static function createFromStringContent(string $originContent): Message
{
$attributes = MessageParser::parse($originContent);
return new static($attributes, $originContent);
}
public function getOriginalContents(): string
{
return $this->originContent ?? '';
}
public function __toString()
{
return $this->toJson() ?: '';
}
}
================================================
FILE: src/Kernel/ServerResponse.php
================================================
response->getBody()->rewind();
}
public static function make(ResponseInterface $response): ServerResponse
{
if ($response instanceof ServerResponse) {
return $response;
}
return new self($response);
}
public function getProtocolVersion(): string
{
return $this->response->getProtocolVersion();
}
public function withProtocolVersion($version): ServerResponse|ResponseInterface
{
return $this->response->withProtocolVersion($version);
}
public function getHeaders(): array
{
return $this->response->getHeaders();
}
public function hasHeader($name): bool
{
return $this->response->hasHeader($name);
}
public function getHeader($name): array
{
return $this->response->getHeader($name);
}
public function getHeaderLine($name): string
{
return $this->response->getHeaderLine($name);
}
public function withHeader($name, $value): ServerResponse|ResponseInterface
{
return $this->response->withHeader($name, $value);
}
public function withAddedHeader($name, $value): ServerResponse|ResponseInterface
{
return $this->response->withAddedHeader($name, $value);
}
public function withoutHeader($name): ServerResponse|ResponseInterface
{
return $this->response->withoutHeader($name);
}
public function getBody(): StreamInterface
{
return $this->response->getBody();
}
public function withBody(StreamInterface $body): ServerResponse|ResponseInterface
{
return $this->response->withBody($body);
}
public function getStatusCode(): int
{
return $this->response->getStatusCode();
}
public function withStatus($code, $reasonPhrase = ''): ServerResponse|ResponseInterface
{
$this->response->withStatus($code, $reasonPhrase);
return $this;
}
public function getReasonPhrase(): string
{
return $this->response->getReasonPhrase();
}
/**
* @link https://github.com/symfony/http-foundation/blob/6.1/Response.php
*/
public function send(): static
{
$this->sendHeaders();
$this->sendContent();
if (\function_exists('fastcgi_finish_request')) {
\fastcgi_finish_request();
} elseif (\function_exists('litespeed_finish_request')) {
\litespeed_finish_request();
} elseif (! \in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) {
static::closeOutputBuffers(0, true);
}
return $this;
}
public function sendHeaders(): static
{
// headers have already been sent by the developer
if (\headers_sent()) {
return $this;
}
foreach ($this->getHeaders() as $name => $values) {
$replace = \strcasecmp($name, 'Content-Type') === 0;
foreach ($values as $value) {
header($name.': '.$value, $replace, $this->getStatusCode());
}
}
header(
header: sprintf(
'HTTP/%s %s %s',
$this->getProtocolVersion(),
$this->getStatusCode(),
$this->getReasonPhrase()
),
replace: true,
response_code: $this->getStatusCode()
);
return $this;
}
public function sendContent(): static
{
echo (string) $this->getBody();
return $this;
}
/**
* Cleans or flushes output buffers up to target level.
*
* Resulting level can be greater than target level if a non-removable buffer has been encountered.
*
* @link https://github.com/symfony/http-foundation/blob/6.1/Response.php
*
* @final
*/
public static function closeOutputBuffers(int $targetLevel, bool $flush): void
{
$status = ob_get_status(true);
$level = count($status);
$flags = PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? PHP_OUTPUT_HANDLER_FLUSHABLE : PHP_OUTPUT_HANDLER_CLEANABLE);
while ($level-- > $targetLevel && ($s = $status[$level]) && (! isset($s['del']) ? ! isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) {
if ($flush) {
ob_end_flush();
} else {
ob_end_clean();
}
}
}
public function __toString(): string
{
$headers = $this->getHeaders();
$headersString = '';
if (! empty($headers)) {
ksort($headers);
$max = max(array_map('strlen', array_keys($headers))) + 1;
foreach ($headers as $name => $values) {
$name = ucwords($name, '-');
foreach ($values as $value) {
$headersString .= sprintf("%-{$max}s %s\r\n", $name.':', $value);
}
}
}
return sprintf(
'HTTP/%s %s %s',
$this->getProtocolVersion(),
$this->getStatusCode(),
$this->getReasonPhrase()
)."\r\n".
$headersString."\r\n".
$this->getBody();
}
}
================================================
FILE: src/Kernel/Support/AesCbc.php
================================================
$array
*/
public static function exists(array $array, string|int $key): bool
{
return array_key_exists($key, $array);
}
/**
* @param array $array
* @return array
*/
public static function set(array &$array, string|int|null $key, mixed $value): array
{
if (! is_string($key)) {
$key = (string) $key;
}
$keys = explode('.', $key);
while (count($keys) > 1) {
$key = array_shift($keys);
// If the key doesn't exist at this depth, we will just create an empty array
// to hold the next value, allowing us to create the arrays to hold final
// values at the correct depth. Then we'll keep digging into the array.
if (! isset($array[$key]) || ! is_array($array[$key])) {
$array[$key] = [];
}
$array = &$array[$key];
}
$array[array_shift($keys)] = $value;
return $array;
}
/**
* @param array $array
* @return array
*/
public static function dot(array $array, string $prepend = ''): array
{
$results = [];
foreach ($array as $key => $value) {
if (is_array($value) && ! empty($value)) {
$results = array_merge($results, static::dot($value, $prepend.$key.'.'));
} else {
$results[$prepend.$key] = $value;
}
}
return $results;
}
/**
* @param array $array
* @param string|int|array|null $keys
*/
#[\JetBrains\PhpStorm\Pure]
public static function has(array $array, string|int|array|null $keys): bool
{
if (is_null($keys)) {
return false;
}
$keys = (array) $keys;
if (empty($array)) {
return false;
}
if ($keys === []) {
return false;
}
foreach ($keys as $key) {
$subKeyArray = $array;
/** @phpstan-ignore-next-line */
if (static::exists($array, $key)) {
continue;
}
/** @phpstan-ignore-next-line */
foreach (explode('.', (string) $key) as $segment) {
/** @phpstan-ignore-next-line */
if (static::exists($subKeyArray, $segment)) {
/** @phpstan-ignore-next-line */
$subKeyArray = $subKeyArray[$segment];
} else {
return false;
}
}
}
return true;
}
}
================================================
FILE: src/Kernel/Support/MessageParser.php
================================================
*
* @throws BadRequestException
*/
public static function parse(string $content): array
{
$content = trim($content);
// Try JSON format first
$parsed = json_decode($content, true);
if (json_last_error() === JSON_ERROR_NONE && is_array($parsed) && ! empty($parsed)) {
/** @var array $parsed */
return $parsed;
}
// If JSON decode failed or result is not an array, try XML format
$parsed = Xml::parse($content);
if (is_array($parsed) && ! empty($parsed)) {
/** @var array $parsed */
return $parsed;
}
throw new BadRequestException('Failed to decode content. Content must be valid XML or JSON.');
}
}
================================================
FILE: src/Kernel/Support/Pkcs7.php
================================================
32) {
throw new InvalidArgumentException('$blockSize may not be more than 32 bytes(256 bits)');
}
$padding = $blockSize - (strlen($contents) % $blockSize);
$pattern = chr($padding);
return $contents.str_repeat($pattern, $padding);
}
public static function unpadding(string $contents, int $blockSize): string
{
$pad = ord(substr($contents, -1));
if ($pad < 1 || $pad > $blockSize) {
$pad = 0;
}
return substr($contents, 0, (strlen($contents) - $pad));
}
}
================================================
FILE: src/Kernel/Support/PrivateKey.php
================================================
key = "file://{$key}";
}
}
public function getKey(): string
{
if (str_starts_with($this->key, 'file://')) {
return file_get_contents($this->key) ?: '';
}
return $this->key;
}
public function getPassphrase(): ?string
{
return $this->passphrase;
}
#[\JetBrains\PhpStorm\Pure]
public function __toString(): string
{
return $this->getKey();
}
}
================================================
FILE: src/Kernel/Support/PublicKey.php
================================================
certificate = "file://{$certificate}";
}
}
/**
* @throws InvalidConfigException
*/
public function getSerialNo(): string
{
$info = openssl_x509_parse($this->certificate);
if ($info === false) {
throw new InvalidConfigException('Read the $certificate failed, please check it whether or nor correct');
}
return strtoupper($info['serialNumberHex']);
}
public function __toString(): string
{
if (str_starts_with($this->certificate, 'file://')) {
return file_get_contents($this->certificate) ?: '';
}
return $this->certificate;
}
}
================================================
FILE: src/Kernel/Support/Str.php
================================================
$appends
*/
public static function create(array $appends = []): string
{
$value = array_map('strval', $appends);
if (defined('HHVM_VERSION')) {
array_unshift($value, 'HHVM/'.constant('HHVM_VERSION'));
}
$disabledFunctions = explode(',', ini_get('disable_functions') ?: '');
if (extension_loaded('curl') && function_exists('curl_version')) {
array_unshift($value, 'curl/'.(curl_version() ?: ['version' => 'unknown'])['version']);
}
if (! ini_get('safe_mode')
&& function_exists('php_uname')
&& ! in_array('php_uname', $disabledFunctions, true)
) {
$osName = 'OS/'.php_uname('s').'/'.php_uname('r');
array_unshift($value, $osName);
}
if (class_exists(InstalledVersions::class)) {
array_unshift($value, 'easywechat-sdk/'.((string) InstalledVersions::getVersion('w7corp/easywechat')));
}
return trim(implode(' ', $value));
}
}
================================================
FILE: src/Kernel/Support/Xml.php
================================================
Encrypt ?? $message->encrypt ?? null;
if (! is_string($ciphertext) || $ciphertext === '') {
throw new BadRequestException('Request ciphertext must not be empty.');
}
$this->validateSignature($encryptor->getToken(), $ciphertext, $signature, $timestamp, $nonce);
$plaintext = $encryptor->decrypt(
ciphertext: $ciphertext,
msgSignature: $signature,
nonce: $nonce,
timestamp: $timestamp
);
$attributes = MessageParser::parse($plaintext);
$message->merge($attributes);
return $message;
}
/**
* Validate the request signature.
*
* @throws BadRequestException
*/
protected function validateSignature(
string $token,
string $ciphertext,
string $signature,
int|string $timestamp,
string $nonce
): void {
if (empty($signature)) {
throw new BadRequestException('Request signature must not be empty.');
}
$params = [$token, $timestamp, $nonce, $ciphertext];
sort($params, SORT_STRING);
if ($signature !== sha1(implode($params))) {
throw new BadRequestException('Invalid request signature.');
}
}
}
================================================
FILE: src/Kernel/Traits/DecryptXmlMessage.php
================================================
*/
protected array $attributes = [];
/**
* @param array $attributes
*/
public function __construct(array $attributes)
{
$this->attributes = $attributes;
}
/**
* @return array
*/
public function toArray(): array
{
return $this->attributes;
}
public function toJson(): string|false
{
return json_encode($this->attributes);
}
public function has(string $key): bool
{
return array_key_exists($key, $this->attributes);
}
/**
* @param array $attributes
*/
public function merge(array $attributes): static
{
$this->attributes = array_merge($this->attributes, $attributes);
return $this;
}
/**
* @return array $attributes
*/
public function jsonSerialize(): array
{
return $this->attributes;
}
public function __set(string $attribute, mixed $value): void
{
$this->attributes[$attribute] = $value;
}
public function __get(string $attribute): mixed
{
return $this->attributes[$attribute] ?? null;
}
public function offsetExists(mixed $offset): bool
{
/** @phpstan-ignore-next-line */
return array_key_exists($offset, $this->attributes);
}
public function offsetGet(mixed $offset): mixed
{
return $this->attributes[$offset];
}
public function offsetSet(mixed $offset, mixed $value): void
{
if ($offset === null) {
$this->attributes[] = $value;
} else {
$this->attributes[$offset] = $value;
}
}
public function offsetUnset(mixed $offset): void
{
unset($this->attributes[$offset]);
}
}
================================================
FILE: src/Kernel/Traits/InteractWithCache.php
================================================
cacheLifetime;
}
public function setCacheLifetime(int $cacheLifetime): void
{
$this->cacheLifetime = $cacheLifetime;
}
public function getCacheNamespace(): string
{
return $this->cacheNamespace;
}
public function setCacheNamespace(string $cacheNamespace): void
{
$this->cacheNamespace = $cacheNamespace;
}
public function setCache(CacheInterface $cache): static
{
$this->cache = $cache;
return $this;
}
public function getCache(): CacheInterface
{
if (! $this->cache) {
$this->cache = new Psr16Cache(new FilesystemAdapter($this->cacheNamespace, $this->cacheLifetime));
}
return $this->cache;
}
}
================================================
FILE: src/Kernel/Traits/InteractWithClient.php
================================================
client) {
$this->client = $this->createClient();
}
return $this->client;
}
public function setClient(AccessTokenAwareClient $client): static
{
$this->client = $client;
return $this;
}
abstract public function createClient(): AccessTokenAwareClient;
}
================================================
FILE: src/Kernel/Traits/InteractWithConfig.php
================================================
|ConfigInterface $config
*/
public function __construct(array|ConfigInterface $config)
{
$this->config = is_array($config) ? new Config($config) : $config;
}
public function getConfig(): ConfigInterface
{
return $this->config;
}
public function setConfig(ConfigInterface $config): static
{
$this->config = $config;
return $this;
}
}
================================================
FILE: src/Kernel/Traits/InteractWithHandlers.php
================================================
*/
protected array $handlers = [];
/**
* @return array
*/
public function getHandlers(): array
{
return $this->handlers;
}
public function with(callable|string $handler): static
{
return $this->withHandler($handler);
}
/**
* @throws InvalidArgumentException
*/
public function withHandler(callable|string $handler): static
{
$this->handlers[] = $this->createHandlerItem($handler);
return $this;
}
/**
* @return array{hash: string, handler: callable}
*/
#[\JetBrains\PhpStorm\ArrayShape(['hash' => 'string', 'handler' => 'callable'])]
public function createHandlerItem(callable|string $handler): array
{
return [
'hash' => $this->getHandlerHash($handler),
'handler' => $this->makeClosure($handler),
];
}
/**
* @throws InvalidArgumentException
*/
protected function getHandlerHash(callable|array|string $handler): string
{
return match (true) {
is_string($handler) => $handler,
is_array($handler) => is_string($handler[0])
? $handler[0].'::'.$handler[1]
: get_class($handler[0]).$handler[1],
$handler instanceof Closure => spl_object_hash($handler),
is_callable($handler) => spl_object_hash($handler),
default => throw new InvalidArgumentException('Invalid handler: '.gettype($handler)),
};
}
/**
* @throws InvalidArgumentException
*/
protected function makeClosure(callable|string $handler): callable
{
if (is_callable($handler)) {
return $handler;
}
if (class_exists($handler) && method_exists($handler, '__invoke')) {
/**
* @psalm-suppress InvalidFunctionCall
*
* @phpstan-ignore-next-line https://github.com/phpstan/phpstan/issues/5867
*/
return fn (): mixed => (new $handler)(...func_get_args());
}
throw new InvalidArgumentException(sprintf('Invalid handler: %s.', $handler));
}
public function prepend(callable|string $handler): static
{
return $this->prependHandler($handler);
}
public function prependHandler(callable|string $handler): static
{
array_unshift($this->handlers, $this->createHandlerItem($handler));
return $this;
}
/**
* @throws InvalidArgumentException
*/
public function without(callable|string $handler): static
{
return $this->withoutHandler($handler);
}
/**
* @throws InvalidArgumentException
*/
public function withoutHandler(callable|string $handler): static
{
$index = $this->indexOf($handler);
if ($index > -1) {
unset($this->handlers[$index]);
}
return $this;
}
public function indexOf(callable|string $handler): int
{
foreach ($this->handlers as $index => $item) {
if ($item['hash'] === $this->getHandlerHash($handler)) {
return $index;
}
}
return -1;
}
public function when(mixed $value, callable|string $handler): static
{
if (is_callable($value)) {
$value = call_user_func($value, $this);
}
if ($value) {
return $this->withHandler($handler);
}
return $this;
}
public function handle(mixed $result, mixed $payload = null): mixed
{
$next = $result = is_callable($result) ? $result : fn (mixed $p): mixed => $result;
foreach (array_reverse($this->handlers) as $item) {
$next = fn (mixed $p): mixed => $item['handler']($p, $next) ?? $result($p);
}
return $next($payload);
}
public function has(callable|string $handler): bool
{
return $this->indexOf($handler) > -1;
}
}
================================================
FILE: src/Kernel/Traits/InteractWithHttpClient.php
================================================
httpClient) {
$this->httpClient = $this->createHttpClient();
}
return $this->httpClient;
}
public function setHttpClient(HttpClientInterface $httpClient): static
{
$this->httpClient = $httpClient;
if ($this instanceof LoggerAwareInterface && $httpClient instanceof LoggerAwareInterface
&& $this->logger instanceof LoggerInterface) {
$httpClient->setLogger($this->logger);
}
return $this;
}
protected function createHttpClient(): HttpClientInterface
{
$options = $this->getHttpClientDefaultOptions();
$optionsByRegexp = Arr::get($options, 'options_by_regexp', []);
unset($options['options_by_regexp']);
$client = HttpClient::create(RequestUtil::formatDefaultOptions($options));
if (is_array($optionsByRegexp) && ! empty($optionsByRegexp)) {
$client = new ScopingHttpClient($client, $optionsByRegexp);
}
return $client;
}
/**
* @return array
*/
protected function getHttpClientDefaultOptions(): array
{
return [];
}
}
================================================
FILE: src/Kernel/Traits/InteractWithServerRequest.php
================================================
request) {
$this->request = RequestUtil::createDefaultServerRequest();
}
return $this->request;
}
public function setRequest(ServerRequestInterface $request): static
{
$this->request = $request;
return $this;
}
public function setRequestFromSymfonyRequest(Request $symfonyRequest): static
{
$psr17Factory = new Psr17Factory;
$psrHttpFactory = new PsrHttpFactory($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory);
$this->request = $psrHttpFactory->createRequest($symfonyRequest);
return $this;
}
}
================================================
FILE: src/Kernel/Traits/MockableHttpClient.php
================================================
$headers
*/
public static function mock(
string $response = '',
?int $status = 200,
array $headers = [],
string $baseUri = 'https://example.com'
): object {
$mockResponse = new MockResponse(
$response,
array_merge([
'http_code' => $status,
'content_type' => 'application/json',
], $headers)
);
$client = self::createMockClient(new MockHttpClient($mockResponse, $baseUri));
// @phpstan-ignore-next-line
return new class($client, $mockResponse)
{
use DecoratorTrait;
public function __construct(Mock|HttpClientInterface $client, public MockResponse $mockResponse)
{
$this->client = $client;
}
/**
* @param array $arguments
*/
public function __call(string $name, array $arguments): mixed
{
return $this->client->$name(...$arguments);
}
#[\JetBrains\PhpStorm\Pure]
public function getRequestMethod(): string
{
return $this->mockResponse->getRequestMethod();
}
#[\JetBrains\PhpStorm\Pure]
public function getRequestUrl(): string
{
return $this->mockResponse->getRequestUrl();
}
/**
* @return array
*/
#[\JetBrains\PhpStorm\Pure]
public function getRequestOptions(): array
{
return $this->mockResponse->getRequestOptions();
}
};
}
}
================================================
FILE: src/Kernel/Traits/RespondJsonMessage.php
================================================
createJsonResponse(
attributes: $this->normalizeJsonResponse($response),
encryptor: $encryptor
);
}
/**
* @throws InvalidArgumentException
*/
protected function normalizeJsonResponse(mixed $response): array
{
if (! is_string($response) && is_callable($response)) {
$response = $response();
}
if (is_array($response)) {
if (! isset($response['msgtype'])) {
throw new InvalidArgumentException('msgtype cannot be empty.');
}
return $response;
}
throw new InvalidArgumentException(
sprintf('Invalid Response type "%s".', gettype($response))
);
}
/**
* @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
*/
protected function createJsonResponse(array $attributes, ?Encryptor $encryptor = null): ResponseInterface
{
$jsonStr = json_encode($attributes, JSON_UNESCAPED_UNICODE);
if (is_string($jsonStr)) {
return new Response(200, ['Content-Type' => 'application/json'], $encryptor ? $encryptor->encrypt($jsonStr, messageType: $this->messageType) : $jsonStr);
}
throw new InvalidArgumentException(
sprintf('Invalid Response content "%s".', implode(',', $attributes))
);
}
}
================================================
FILE: src/Kernel/Traits/RespondXmlMessage.php
================================================
createXmlResponse(
attributes: array_filter(
array_merge(
[
'ToUserName' => $message->FromUserName,
'FromUserName' => $message->ToUserName,
'CreateTime' => time(),
],
$this->normalizeResponse($response),
)
),
encryptor: $encryptor
);
}
/**
* @return array
*
* @throws InvalidArgumentException
*/
protected function normalizeResponse(mixed $response): array
{
if (! is_string($response) && is_callable($response)) {
$response = $response();
}
if (is_array($response)) {
if (! isset($response['MsgType'])) {
throw new InvalidArgumentException('MsgType cannot be empty.');
}
return $response;
}
if (is_string($response) || is_numeric($response)) {
return [
'MsgType' => 'text',
'Content' => $response,
];
}
throw new InvalidArgumentException(
sprintf('Invalid Response type "%s".', gettype($response))
);
}
/**
* @param array $attributes
*
* @throws RuntimeException
*/
protected function createXmlResponse(array $attributes, ?Encryptor $encryptor = null): ResponseInterface
{
$xml = Xml::build($attributes);
return new Response(200, ['Content-Type' => 'application/xml'], $encryptor ? $encryptor->encrypt($xml) : $xml);
}
}
================================================
FILE: src/MiniApp/AccessToken.php
================================================
account) {
$this->account = new Account(
appId: (string) $this->config->get('app_id'), /** @phpstan-ignore-line */
secret: (string) $this->config->get('secret'), /** @phpstan-ignore-line */
token: (string) $this->config->get('token'), /** @phpstan-ignore-line */
aesKey: (string) $this->config->get('aes_key'),/** @phpstan-ignore-line */
);
}
return $this->account;
}
public function setAccount(AccountInterface $account): static
{
$this->account = $account;
return $this;
}
/**
* @throws InvalidConfigException
*/
public function getEncryptor(): Encryptor
{
if (! $this->encryptor) {
$token = $this->getAccount()->getToken();
$aesKey = $this->getAccount()->getAesKey();
if (empty($token) || empty($aesKey)) {
throw new InvalidConfigException('token or aes_key cannot be empty.');
}
$this->encryptor = new Encryptor(
appId: $this->getAccount()->getAppId(),
token: $token,
aesKey: $aesKey,
receiveId: $this->getAccount()->getAppId()
);
}
return $this->encryptor;
}
public function setEncryptor(Encryptor $encryptor): static
{
$this->encryptor = $encryptor;
return $this;
}
public function getServer(): Server|ServerInterface
{
if (! $this->server) {
$this->server = new Server(
request: $this->getRequest(),
encryptor: $this->getAccount()->getAesKey() ? $this->getEncryptor() : null
);
}
return $this->server;
}
public function setServer(ServerInterface $server): static
{
$this->server = $server;
return $this;
}
public function getAccessToken(): AccessTokenInterface
{
if (! $this->accessToken) {
$this->accessToken = new AccessToken(
appId: $this->getAccount()->getAppId(),
secret: $this->getAccount()->getSecret(),
cache: $this->getCache(),
httpClient: $this->getHttpClient(),
stable: $this->config->get('use_stable_access_token', false)
);
}
return $this->accessToken;
}
public function setAccessToken(AccessTokenInterface $accessToken): static
{
$this->accessToken = $accessToken;
return $this;
}
#[\JetBrains\PhpStorm\Pure]
public function getUtils(): Utils
{
return new Utils($this);
}
public function createClient(): AccessTokenAwareClient
{
$httpClient = $this->getHttpClient();
if ($this->config->get('http.retry', false)) {
$httpClient = new RetryableHttpClient(
$httpClient,
$this->getRetryStrategy(),
(int) $this->config->get('http.max_retries', 2) // @phpstan-ignore-line
);
}
return (new AccessTokenAwareClient(
client: $httpClient,
accessToken: $this->getAccessToken(),
failureJudge: fn (
Response $response
) => ($response->toArray()['errcode'] ?? 0) || ! is_null($response->toArray()['error'] ?? null),
throw: (bool) $this->config->get('http.throw', true),
))->setPresets($this->config->all());
}
public function getRetryStrategy(): AccessTokenExpiredRetryStrategy
{
$retryConfig = RequestUtil::mergeDefaultRetryOptions((array) $this->config->get('http.retry', []));
return (new AccessTokenExpiredRetryStrategy($retryConfig))
->decideUsing(function (AsyncContext $context, ?string $responseContent): bool {
return ! empty($responseContent)
&& str_contains($responseContent, '42001')
&& str_contains($responseContent, 'access_token expired');
});
}
/**
* @return array
*/
protected function getHttpClientDefaultOptions(): array
{
return array_merge(
['base_uri' => 'https://api.weixin.qq.com/'],
(array) $this->config->get('http', [])
);
}
}
================================================
FILE: src/MiniApp/Contracts/Account.php
================================================
*
* @throws DecryptException
*/
public static function decrypt(string $sessionKey, string $iv, string $ciphertext): array
{
try {
$decrypted = AesCbc::decrypt(
$ciphertext,
base64_decode($sessionKey, false),
base64_decode($iv, false)
);
$decrypted = json_decode($decrypted, true);
if (! $decrypted || ! is_array($decrypted)) {
throw new DecryptException('The given payload is invalid.');
}
} catch (Throwable $e) {
throw new DecryptException(sprintf('The given payload is invalid: %s', $e->getMessage()));
}
return $decrypted;
}
}
================================================
FILE: src/MiniApp/Server.php
================================================
app->getHttpClient()->request('GET', '/sns/jscode2session', [
'query' => [
'appid' => $this->app->getAccount()->getAppId(),
'secret' => $this->app->getAccount()->getSecret(),
'js_code' => $code,
'grant_type' => 'authorization_code',
],
])->toArray(false);
if (empty($response['openid'])) {
throw new HttpException('code2Session error: '.json_encode($response, JSON_UNESCAPED_UNICODE));
}
return $response;
}
public function decryptSession(string $sessionKey, string $iv, string $ciphertext): array
{
return Decryptor::decrypt($sessionKey, $iv, $ciphertext);
}
/**
* @throws HttpException
*/
public function getPhoneNumber(string $code): array
{
$response = $this->app->createClient()->request('POST', '/wxa/business/getuserphonenumber', [
'json' => [
'code' => $code,
],
])->toArray(false);
if (isset($response['errcode']) && $response['errcode'] !== 0) {
throw new HttpException('getPhoneNumber error: '.json_encode($response, JSON_UNESCAPED_UNICODE));
}
if (empty($response['phone_info'])) {
throw new HttpException('getPhoneNumber error: '.json_encode($response, JSON_UNESCAPED_UNICODE));
}
return $response;
}
}
================================================
FILE: src/OfficialAccount/AccessToken.php
================================================
httpClient = $httpClient ?? HttpClient::create(['base_uri' => 'https://api.weixin.qq.com/']);
$this->cache = $cache ?? new Psr16Cache(new FilesystemAdapter(namespace: 'easywechat', defaultLifetime: 1500));
}
public function getKey(): string
{
return $this->key ?? $this->key = sprintf('%s.access_token.%s.%s.%s', static::CACHE_KEY_PREFIX, $this->appId, $this->secret, (int) $this->stable);
}
public function setKey(string $key): static
{
$this->key = $key;
return $this;
}
public function getToken(): string
{
$token = $this->cache->get($this->getKey());
if ($token && is_string($token)) {
return $token;
}
return $this->refresh();
}
/**
* @return array{access_token:string}
*/
#[\JetBrains\PhpStorm\ArrayShape(['access_token' => 'string'])]
public function toQuery(): array
{
return ['access_token' => $this->getToken()];
}
public function refresh(): string
{
return $this->stable ? $this->getStableAccessToken() : $this->getAccessToken();
}
/**
* @throws HttpException
*/
public function getStableAccessToken(bool $force_refresh = false): string
{
$response = $this->httpClient->request(
'POST',
'https://api.weixin.qq.com/cgi-bin/stable_token',
[
'json' => [
'grant_type' => 'client_credential',
'appid' => $this->appId,
'secret' => $this->secret,
'force_refresh' => $force_refresh,
],
]
)->toArray(false);
if (empty($response['access_token'])) {
throw new HttpException('Failed to get stable access_token: '.json_encode($response, JSON_UNESCAPED_UNICODE));
}
$this->cache->set($this->getKey(), $response['access_token'], intval($response['expires_in']));
return $response['access_token'];
}
/**
* @throws HttpException
*/
public function getAccessToken(): string
{
$response = $this->httpClient->request(
'GET',
'cgi-bin/token',
[
'query' => [
'grant_type' => 'client_credential',
'appid' => $this->appId,
'secret' => $this->secret,
],
]
)->toArray(false);
if (empty($response['access_token'])) {
throw new HttpException('Failed to get access_token: '.json_encode($response, JSON_UNESCAPED_UNICODE));
}
$this->cache->set($this->getKey(), $response['access_token'], intval($response['expires_in']));
return $response['access_token'];
}
}
================================================
FILE: src/OfficialAccount/Account.php
================================================
appId;
}
/**
* @throws RuntimeException
*/
public function getSecret(): string
{
if ($this->secret === null) {
throw new RuntimeException('No secret configured.');
}
return $this->secret;
}
public function getToken(): ?string
{
return $this->token;
}
public function getAesKey(): ?string
{
return $this->aesKey;
}
}
================================================
FILE: src/OfficialAccount/Application.php
================================================
account) {
$this->account = new Account(
appId: (string) $this->config->get('app_id'), /** @phpstan-ignore-line */
secret: (string) $this->config->get('secret'), /** @phpstan-ignore-line */
token: (string) $this->config->get('token'), /** @phpstan-ignore-line */
aesKey: (string) $this->config->get('aes_key'),/** @phpstan-ignore-line */
);
}
return $this->account;
}
public function setAccount(AccountInterface $account): static
{
$this->account = $account;
return $this;
}
/**
* @throws InvalidConfigException
*/
public function getEncryptor(): Encryptor
{
if (! $this->encryptor) {
$token = $this->getAccount()->getToken();
$aesKey = $this->getAccount()->getAesKey();
if (empty($token) || empty($aesKey)) {
throw new InvalidConfigException('token or aes_key cannot be empty.');
}
$this->encryptor = new Encryptor(
appId: $this->getAccount()->getAppId(),
token: $token,
aesKey: $aesKey,
receiveId: $this->getAccount()->getAppId()
);
}
return $this->encryptor;
}
public function setEncryptor(Encryptor $encryptor): static
{
$this->encryptor = $encryptor;
return $this;
}
public function getServer(): Server|ServerInterface
{
if (! $this->server) {
$this->server = new Server(
request: $this->getRequest(),
encryptor: $this->getAccount()->getAesKey() ? $this->getEncryptor() : null
);
}
return $this->server;
}
public function setServer(ServerInterface $server): static
{
$this->server = $server;
return $this;
}
public function getAccessToken(): AccessTokenInterface|RefreshableAccessTokenInterface
{
if (! $this->accessToken) {
$this->accessToken = new AccessToken(
appId: $this->getAccount()->getAppId(),
secret: $this->getAccount()->getSecret(),
cache: $this->getCache(),
httpClient: $this->getHttpClient(),
stable: $this->config->get('use_stable_access_token', false),
);
}
return $this->accessToken;
}
public function setAccessToken(AccessTokenInterface|RefreshableAccessTokenInterface $accessToken): static
{
$this->accessToken = $accessToken;
return $this;
}
public function setOAuthFactory(callable $factory): static
{
$this->oauthFactory = fn (Application $app): WeChat => $factory($app);
return $this;
}
/**
* @throws InvalidArgumentException
*/
public function getOAuth(): SocialiteProviderInterface
{
if (! $this->oauthFactory) {
$this->oauthFactory = fn (self $app): SocialiteProviderInterface => (new WeChat(
[
'client_id' => $this->getAccount()->getAppId(),
'client_secret' => $this->getAccount()->getSecret(),
'redirect_url' => $this->config->get('oauth.redirect_url'),
]
))->scopes((array) $this->config->get('oauth.scopes', ['snsapi_userinfo']));
}
$provider = call_user_func($this->oauthFactory, $this);
if (! $provider instanceof SocialiteProviderInterface) {
throw new InvalidArgumentException(sprintf(
'The factory must return a %s instance.',
SocialiteProviderInterface::class
));
}
return $provider;
}
public function getTicket(): JsApiTicketInterface|RefreshableJsApiTicketInterface
{
if (! $this->ticket) {
$this->ticket = new JsApiTicket(
appId: $this->getAccount()->getAppId(),
secret: $this->getAccount()->getSecret(),
cache: $this->getCache(),
httpClient: $this->getClient(),
stable: $this->config->get('use_stable_access_token', false),
);
}
return $this->ticket;
}
public function setTicket(JsApiTicketInterface|RefreshableJsApiTicketInterface $ticket): static
{
$this->ticket = $ticket;
return $this;
}
#[\JetBrains\PhpStorm\Pure]
public function getUtils(): Utils
{
return new Utils($this);
}
public function createClient(): AccessTokenAwareClient
{
$httpClient = $this->getHttpClient();
if ((bool) $this->config->get('http.retry', false)) {
$httpClient = new RetryableHttpClient(
$httpClient,
$this->getRetryStrategy(),
(int) $this->config->get('http.max_retries', 2) // @phpstan-ignore-line
);
}
return (new AccessTokenAwareClient(
client: $httpClient,
accessToken: $this->getAccessToken(),
failureJudge: fn (Response $response) => (bool) ($response->toArray()['errcode'] ?? 0),
throw: (bool) $this->config->get('http.throw', true),
))->setPresets($this->config->all());
}
public function getRetryStrategy(): AccessTokenExpiredRetryStrategy
{
$retryConfig = RequestUtil::mergeDefaultRetryOptions((array) $this->config->get('http.retry', []));
return (new AccessTokenExpiredRetryStrategy($retryConfig))
->decideUsing(function (AsyncContext $context, ?string $responseContent): bool {
return ! empty($responseContent)
&& str_contains($responseContent, '42001')
&& str_contains($responseContent, 'access_token expired');
});
}
/**
* @return array
*/
protected function getHttpClientDefaultOptions(): array
{
return array_merge(
['base_uri' => 'https://api.weixin.qq.com/'],
(array) $this->config->get('http', [])
);
}
}
================================================
FILE: src/OfficialAccount/Config.php
================================================
*/
protected array $requiredKeys = [
'app_id',
];
}
================================================
FILE: src/OfficialAccount/Contracts/Account.php
================================================
getKey();
$ticket = $this->cache->get($key);
if ($ticket && \is_string($ticket)) {
return $ticket;
}
return $this->refreshTicket();
}
/**
* @throws HttpException
*/
public function refreshTicket(): string
{
$response = $this->httpClient->request('GET', '/cgi-bin/ticket/getticket', ['query' => ['type' => 'jsapi']])
->toArray(false);
if (empty($response['ticket'])) {
throw new HttpException('Failed to get jssdk ticket: '.\json_encode($response, JSON_UNESCAPED_UNICODE));
}
$this->cache->set($this->getKey(), $response['ticket'], \intval($response['expires_in']));
return $response['ticket'];
}
/**
* @return array
*/
#[\JetBrains\PhpStorm\ArrayShape([
'url' => 'string',
'nonceStr' => 'string',
'timestamp' => 'int',
'appId' => 'string',
'signature' => 'string',
])]
public function configSignature(string $url, string $nonce, int $timestamp): array
{
return [
'url' => $url,
'nonceStr' => $nonce,
'timestamp' => $timestamp,
'appId' => $this->appId,
'signature' => sha1(sprintf(
'jsapi_ticket=%s&noncestr=%s×tamp=%s&url=%s',
$this->getTicket(),
$nonce,
$timestamp,
$url
)),
];
}
public function getKey(): string
{
return $this->key ?? $this->key = sprintf('official_account.jsapi_ticket.%s', $this->appId);
}
}
================================================
FILE: src/OfficialAccount/Message.php
================================================
request = $request;
}
public function serve(): ResponseInterface
{
if ($str = $this->getRequest()->getQueryParams()['echostr'] ?? '') {
return new Response(200, [], $str);
}
$message = $this->getRequestMessage($this->getRequest());
$query = $this->getRequest()->getQueryParams();
if ($this->encryptor && ! empty($query['msg_signature'])) {
$this->prepend($this->decryptRequestMessage($query));
}
$response = $this->handle(new Response(200, [], 'success'), $message);
if (! ($response instanceof ResponseInterface)) {
$response = $this->transformToReply($response, $message, $this->encryptor);
}
return ServerResponse::make($response);
}
/**
* @throws Throwable
*/
public function addMessageListener(string $type, callable|string $handler): static
{
$handler = $this->makeClosure($handler);
$this->withHandler(
function (Message $message, Closure $next) use ($type, $handler): mixed {
return $message->MsgType === $type ? $handler($message, $next) : $next($message);
}
);
return $this;
}
public function addEventListener(string $event, callable|string $handler): static
{
$handler = $this->makeClosure($handler);
$this->withHandler(
function (Message $message, Closure $next) use ($event, $handler): mixed {
return $message->Event === $event ? $handler($message, $next) : $next($message);
}
);
return $this;
}
/**
* @param array $query
*
* @psalm-suppress PossiblyNullArgument
*/
protected function decryptRequestMessage(array $query): Closure
{
return function (Message $message, Closure $next) use ($query): mixed {
if (! $this->encryptor) {
return null;
}
$this->decryptIncomingMessage($message, $query);
return $next($message);
};
}
public function getRequestMessage(?ServerRequestInterface $request = null): \EasyWeChat\Kernel\Message
{
return Message::createFromRequest($request ?? $this->getRequest());
}
public function getDecryptedMessage(?ServerRequestInterface $request = null): \EasyWeChat\Kernel\Message
{
$request = $request ?? $this->getRequest();
$message = $this->getRequestMessage($request);
$query = $request->getQueryParams();
if (! $this->encryptor || empty($query['msg_signature'])) {
return $message;
}
return $this->decryptIncomingMessage($message, $query);
}
/**
* @param array $query
*/
protected function decryptIncomingMessage(\EasyWeChat\Kernel\Message $message, array $query): \EasyWeChat\Kernel\Message
{
if (! $this->encryptor) {
return $message;
}
$signature = $query['msg_signature'] ?? '';
$timestamp = $query['timestamp'] ?? '';
$nonce = $query['nonce'] ?? '';
return $this->decryptMessage(
message: $message,
encryptor: $this->encryptor,
signature: $signature,
timestamp: $timestamp,
nonce: $nonce
);
}
}
================================================
FILE: src/OfficialAccount/Utils.php
================================================
$jsApiList
* @param array $openTagList
* @return array
*/
public function buildJsSdkConfig(
string $url,
array $jsApiList = [],
array $openTagList = [],
bool $debug = false
): array {
return array_merge(
compact('jsApiList', 'openTagList', 'debug'),
$this->app->getTicket()->configSignature($url, Str::random(), time())
);
}
}
================================================
FILE: src/OpenPlatform/Account.php
================================================
appId;
}
public function getSecret(): string
{
return $this->secret;
}
public function getToken(): string
{
return $this->token;
}
public function getAesKey(): string
{
return $this->aesKey;
}
}
================================================
FILE: src/OpenPlatform/Application.php
================================================
account) {
$this->account = new Account(
appId: (string) $this->config->get('app_id'), /** @phpstan-ignore-line */
secret: (string) $this->config->get('secret'), /** @phpstan-ignore-line */
token: (string) $this->config->get('token'), /** @phpstan-ignore-line */
aesKey: (string) $this->config->get('aes_key'),/** @phpstan-ignore-line */
);
}
return $this->account;
}
public function setAccount(AccountInterface $account): static
{
$this->account = $account;
return $this;
}
public function getVerifyTicket(): VerifyTicketInterface
{
if (! $this->verifyTicket) {
$this->verifyTicket = new VerifyTicket(
appId: $this->getAccount()->getAppId(),
cache: $this->getCache(),
);
}
return $this->verifyTicket;
}
public function setVerifyTicket(VerifyTicketInterface $verifyTicket): static
{
$this->verifyTicket = $verifyTicket;
return $this;
}
public function getEncryptor(): Encryptor
{
if (! $this->encryptor) {
$this->encryptor = new Encryptor(
appId: $this->getAccount()->getAppId(),
token: $this->getAccount()->getToken(),
aesKey: $this->getAccount()->getAesKey(),
receiveId: $this->getAccount()->getAppId(),
);
}
return $this->encryptor;
}
public function setEncryptor(Encryptor $encryptor): static
{
$this->encryptor = $encryptor;
return $this;
}
public function getServer(): Server|ServerInterface
{
if (! $this->server) {
$this->server = new Server(
encryptor: $this->getEncryptor(),
request: $this->getRequest()
);
}
if ($this->server instanceof Server) {
$this->server->withDefaultVerifyTicketHandler(
function (Message $message, Closure $next): mixed {
$ticket = $this->getVerifyTicket();
$ticket->setTicket($message->ComponentVerifyTicket);
return $next($message);
}
);
}
return $this->server;
}
public function setServer(ServerInterface $server): static
{
$this->server = $server;
return $this;
}
public function getAccessToken(): AccessTokenInterface
{
return $this->getComponentAccessToken();
}
public function getComponentAccessToken(): AccessTokenInterface
{
if (! $this->componentAccessToken) {
$this->componentAccessToken = new ComponentAccessToken(
appId: $this->getAccount()->getAppId(),
secret: $this->getAccount()->getSecret(),
verifyTicket: $this->getVerifyTicket(),
cache: $this->getCache(),
httpClient: $this->getHttpClient(),
);
}
return $this->componentAccessToken;
}
public function setComponentAccessToken(AccessTokenInterface $componentAccessToken): static
{
$this->componentAccessToken = $componentAccessToken;
return $this;
}
/**
* @throws HttpException
*/
public function getAuthorization(string $authorizationCode): Authorization
{
$response = $this->getClient()->request(
'POST',
'cgi-bin/component/api_query_auth',
[
'json' => [
'component_appid' => $this->getAccount()->getAppId(),
'authorization_code' => $authorizationCode,
],
]
)->toArray(false);
if (empty($response['authorization_info'])) {
throw new HttpException('Failed to get authorization_info: '.json_encode(
$response,
JSON_UNESCAPED_UNICODE
));
}
return new Authorization($response);
}
/**
* @throws HttpException
*/
public function refreshAuthorizerToken(string $authorizerAppId, string $authorizerRefreshToken): array
{
$response = $this->getClient()->request(
'POST',
'cgi-bin/component/api_authorizer_token',
[
'json' => [
'component_appid' => $this->getAccount()->getAppId(),
'authorizer_appid' => $authorizerAppId,
'authorizer_refresh_token' => $authorizerRefreshToken,
],
]
)->toArray(false);
if (empty($response['authorizer_access_token'])) {
throw new HttpException('Failed to get authorizer_access_token: '.json_encode(
$response,
JSON_UNESCAPED_UNICODE
));
}
return $response;
}
/**
* @throws HttpException
*/
public function createPreAuthorizationCode(): array
{
$response = $this->getClient()->request(
'POST',
'cgi-bin/component/api_create_preauthcode',
[
'json' => [
'component_appid' => $this->getAccount()->getAppId(),
],
]
)->toArray(false);
if (empty($response['pre_auth_code'])) {
throw new HttpException('Failed to get authorizer_access_token: '.json_encode(
$response,
JSON_UNESCAPED_UNICODE
));
}
return $response;
}
public function createPreAuthorizationUrl(string $callbackUrl, array|string $optional = []): string
{
// 兼容旧版 API 设计
if (is_string($optional)) {
$optional = [
'pre_auth_code' => $optional,
];
} else {
$optional['pre_auth_code'] = Arr::get($this->createPreAuthorizationCode(), 'pre_auth_code');
}
$queries = array_merge(
$optional,
[
'component_appid' => $this->getAccount()->getAppId(),
'redirect_uri' => $callbackUrl,
]
);
return 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?'.http_build_query($queries);
}
public function getOAuth(): SocialiteProviderInterface
{
return (new WeChat(
[
'client_id' => $this->getAccount()->getAppId(),
'client_secret' => $this->getAccount()->getSecret(),
'redirect_url' => $this->config->get('oauth.redirect_url'),
]
))->scopes((array) $this->config->get('oauth.scopes', ['snsapi_userinfo']));
}
public function getOfficialAccountWithRefreshToken(
string $appId,
string $refreshToken,
array $config = []
): OfficialAccountApplication {
return $this->getOfficialAccountWithAccessToken(
$appId,
$this->getAuthorizerAccessToken($appId, $refreshToken),
$config
);
}
public function getOfficialAccountWithAccessToken(
string $appId,
string $accessToken,
array $config = []
): OfficialAccountApplication {
return $this->getOfficialAccount(new AuthorizerAccessToken($appId, $accessToken), $config);
}
public function getOfficialAccount(
AuthorizerAccessToken $authorizerAccessToken,
array $config = []
): OfficialAccountApplication {
$config = new OfficialAccountConfig(
array_merge(
[
'app_id' => $authorizerAccessToken->getAppId(),
'token' => $this->config->get('token'),
'aes_key' => $this->config->get('aes_key'),
'logging' => $this->config->get('logging'),
'http' => $this->config->get('http', []),
],
$config
)
);
$app = new OfficialAccountApplication($config);
$app->setAccessToken($authorizerAccessToken);
$app->setEncryptor($this->getEncryptor());
$app->setOAuthFactory($this->createAuthorizerOAuthFactory($authorizerAccessToken->getAppId(), $config));
return $app;
}
public function getMiniAppWithRefreshToken(
string $appId,
string $refreshToken,
array $config = []
): MiniAppApplication {
return $this->getMiniAppWithAccessToken(
$appId,
$this->getAuthorizerAccessToken($appId, $refreshToken),
$config
);
}
public function getMiniAppWithAccessToken(
string $appId,
string $accessToken,
array $config = []
): MiniAppApplication {
return $this->getMiniApp(new AuthorizerAccessToken($appId, $accessToken), $config);
}
public function getMiniApp(AuthorizerAccessToken $authorizerAccessToken, array $config = []): MiniAppApplication
{
$app = new MiniAppApplication(
array_merge(
[
'app_id' => $authorizerAccessToken->getAppId(),
'token' => $this->config->get('token'),
'aes_key' => $this->config->get('aes_key'),
'logging' => $this->config->get('logging'),
'http' => $this->config->get('http'),
],
$config
)
);
$app->setAccessToken($authorizerAccessToken);
$app->setEncryptor($this->getEncryptor());
return $app;
}
protected function createAuthorizerOAuthFactory(string $authorizerAppId, OfficialAccountConfig $config): Closure
{
return fn () => (new WeChat(
[
'client_id' => $authorizerAppId,
'component' => [
'component_app_id' => $this->getAccount()->getAppId(),
'component_access_token' => fn () => $this->getComponentAccessToken()->getToken(),
],
'redirect_url' => $this->config->get('oauth.redirect_url'),
]
))->scopes((array) $config->get('oauth.scopes', ['snsapi_userinfo']));
}
public function createClient(): AccessTokenAwareClient
{
return (new AccessTokenAwareClient(
client: $this->getHttpClient(),
accessToken: $this->getComponentAccessToken(),
failureJudge: fn (Response $response) => (bool) ($response->toArray()['errcode'] ?? 0),
throw: (bool) $this->config->get('http.throw', true),
))->setPresets($this->config->all());
}
public function getAuthorizerAccessToken(string $appId, string $refreshToken): string
{
$cacheKey = sprintf('open-platform.authorizer_access_token.%s.%s', $appId, md5($refreshToken));
/** @phpstan-ignore-next-line */
$authorizerAccessToken = (string) $this->getCache()->get($cacheKey);
if (! $authorizerAccessToken) {
$response = $this->refreshAuthorizerToken($appId, $refreshToken);
$authorizerAccessToken = (string) $response['authorizer_access_token'];
$this->getCache()->set($cacheKey, $authorizerAccessToken, intval($response['expires_in'] ?? 7200) - 500);
}
return $authorizerAccessToken;
}
/**
* @return array
*/
protected function getHttpClientDefaultOptions(): array
{
return array_merge(
['base_uri' => 'https://api.weixin.qq.com/'],
(array) $this->config->get('http', [])
);
}
}
================================================
FILE: src/OpenPlatform/Authorization.php
================================================
*/
class Authorization implements Arrayable, ArrayAccess, Jsonable
{
use HasAttributes;
public function getAppId(): string
{
/** @phpstan-ignore-next-line */
return (string) $this->attributes['authorization_info']['authorizer_appid'] ?? '';
}
#[\JetBrains\PhpStorm\Pure]
public function getAccessToken(): AuthorizerAccessToken
{
return new AuthorizerAccessToken(
/** @phpstan-ignore-next-line */
$this->attributes['authorization_info']['authorizer_appid'] ?? '',
/** @phpstan-ignore-next-line */
$this->attributes['authorization_info']['authorizer_access_token'] ?? ''
);
}
public function getRefreshToken(): string
{
/** @phpstan-ignore-next-line */
return $this->attributes['authorization_info']['authorizer_refresh_token'] ?? '';
}
}
================================================
FILE: src/OpenPlatform/AuthorizerAccessToken.php
================================================
appId;
}
public function getToken(): string
{
return $this->accessToken;
}
public function __toString()
{
return $this->accessToken;
}
/**
* @return array
*/
#[\JetBrains\PhpStorm\Pure]
#[\JetBrains\PhpStorm\ArrayShape(['access_token' => 'string'])]
public function toQuery(): array
{
return ['access_token' => $this->getToken()];
}
}
================================================
FILE: src/OpenPlatform/ComponentAccessToken.php
================================================
httpClient = $httpClient ?? HttpClient::create(['base_uri' => 'https://api.weixin.qq.com/']);
$this->cache = $cache ?? new Psr16Cache(new FilesystemAdapter(namespace: 'easywechat', defaultLifetime: 1500));
}
public function getKey(): string
{
return $this->key ?? $this->key = \sprintf('open_platform.component_access_token.%s', $this->appId);
}
public function setKey(string $key): static
{
$this->key = $key;
return $this;
}
public function getToken(): string
{
$token = $this->cache->get($this->getKey());
if ($token && \is_string($token)) {
return $token;
}
return $this->refresh();
}
#[\JetBrains\PhpStorm\ArrayShape(['component_access_token' => 'string'])]
public function toQuery(): array
{
return ['component_access_token' => $this->getToken()];
}
/**
* @throws HttpException
*/
public function refresh(): string
{
$response = $this->httpClient->request(
'POST',
'cgi-bin/component/api_component_token',
[
'json' => [
'component_appid' => $this->appId,
'component_appsecret' => $this->secret,
'component_verify_ticket' => $this->verifyTicket->getTicket(),
],
]
)->toArray(false);
if (empty($response['component_access_token'])) {
throw new HttpException('Failed to get component_access_token: '.json_encode(
$response,
JSON_UNESCAPED_UNICODE
));
}
$this->cache->set(
$this->getKey(),
$response['component_access_token'],
abs(intval($response['expires_in']) - 100)
);
return $response['component_access_token'];
}
}
================================================
FILE: src/OpenPlatform/Config.php
================================================
*/
protected array $requiredKeys = [
'app_id',
'secret',
'aes_key',
];
}
================================================
FILE: src/OpenPlatform/Contracts/Account.php
================================================
$config
*/
public function getMiniApp(AuthorizerAccessToken $authorizerAccessToken, array $config): MiniAppApplication;
/**
* @param array $config
*/
public function getOfficialAccount(
AuthorizerAccessToken $authorizerAccessToken,
array $config
): OfficialAccountApplication;
}
================================================
FILE: src/OpenPlatform/Contracts/VerifyTicket.php
================================================
request = $request;
}
public function serve(): ResponseInterface
{
if ($str = $this->getRequest()->getQueryParams()['echostr'] ?? '') {
return new Response(200, [], $str);
}
$message = $this->getRequestMessage($this->getRequest());
$this->prepend($this->decryptRequestMessage());
$response = $this->handle(new Response(200, [], 'success'), $message);
if (! ($response instanceof ResponseInterface)) {
$response = $this->transformToReply($response, $message, $this->encryptor);
}
return ServerResponse::make($response);
}
public function handleAuthorized(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->InfoType === 'authorized' ? $handler($message, $next) : $next($message);
});
return $this;
}
public function handleUnauthorized(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->InfoType === 'unauthorized' ? $handler($message, $next) : $next($message);
});
return $this;
}
public function handleAuthorizeUpdated(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->InfoType === 'updateauthorized' ? $handler($message, $next) : $next($message);
});
return $this;
}
public function withDefaultVerifyTicketHandler(callable $handler): void
{
$this->defaultVerifyTicketHandler = fn (): mixed => $handler(...func_get_args());
$this->handleVerifyTicketRefreshed($this->defaultVerifyTicketHandler);
}
public function handleVerifyTicketRefreshed(callable $handler): static
{
if ($this->defaultVerifyTicketHandler) {
$this->withoutHandler($this->defaultVerifyTicketHandler);
}
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->InfoType === 'component_verify_ticket' ? $handler($message, $next) : $next($message);
});
return $this;
}
protected function decryptRequestMessage(): Closure
{
$query = $this->getRequest()->getQueryParams();
return function (Message $message, Closure $next) use ($query): mixed {
$message = $this->decryptMessage(
message: $message,
encryptor: $this->encryptor,
signature: $query['msg_signature'] ?? '',
timestamp: $query['timestamp'] ?? '',
nonce: $query['nonce'] ?? ''
);
return $next($message);
};
}
public function getRequestMessage(?ServerRequestInterface $request = null): \EasyWeChat\Kernel\Message
{
return Message::createFromRequest($request ?? $this->getRequest());
}
public function getDecryptedMessage(?ServerRequestInterface $request = null): \EasyWeChat\Kernel\Message
{
$request = $request ?? $this->getRequest();
$message = $this->getRequestMessage($request);
$query = $request->getQueryParams();
return $this->decryptMessage(
message: $message,
encryptor: $this->encryptor,
signature: $query['msg_signature'] ?? '',
timestamp: $query['timestamp'] ?? '',
nonce: $query['nonce'] ?? ''
);
}
}
================================================
FILE: src/OpenPlatform/VerifyTicket.php
================================================
cache = $cache ?? new Psr16Cache(new FilesystemAdapter(namespace: 'easywechat', defaultLifetime: 1500));
}
public function getKey(): string
{
return $this->key ?? $this->key = sprintf('open_platform.verify_ticket.%s', $this->appId);
}
public function setKey(string $key): static
{
$this->key = $key;
return $this;
}
public function setTicket(string $ticket): static
{
$this->cache->set($this->getKey(), $ticket, 6000);
return $this;
}
/**
* @throws RuntimeException
*/
public function getTicket(): string
{
$ticket = $this->cache->get($this->getKey());
if (! $ticket || ! is_string($ticket)) {
throw new RuntimeException('No component_verify_ticket found.');
}
return $ticket;
}
}
================================================
FILE: src/OpenWork/Account.php
================================================
corpId;
}
public function getProviderSecret(): string
{
return $this->providerSecret;
}
public function getSuiteId(): string
{
return $this->suiteId;
}
public function getSuiteSecret(): string
{
return $this->suiteSecret;
}
public function getToken(): string
{
return $this->token;
}
public function getAesKey(): string
{
return $this->aesKey;
}
}
================================================
FILE: src/OpenWork/Application.php
================================================
account) {
$this->account = new Account(
corpId: (string) $this->config->get('corp_id'), /** @phpstan-ignore-line */
providerSecret: (string) $this->config->get('provider_secret'), /** @phpstan-ignore-line */
suiteId: (string) $this->config->get('suite_id'), /** @phpstan-ignore-line */
suiteSecret: (string) $this->config->get('suite_secret'), /** @phpstan-ignore-line */
token: (string) $this->config->get('token'), /** @phpstan-ignore-line */
aesKey: (string) $this->config->get('aes_key'),/** @phpstan-ignore-line */
);
}
return $this->account;
}
public function setAccount(AccountInterface $account): static
{
$this->account = $account;
return $this;
}
public function getEncryptor(): Encryptor
{
if (! $this->encryptor) {
$this->encryptor = new Encryptor(
corpId: $this->getAccount()->getCorpId(),
token: $this->getAccount()->getToken(),
aesKey: $this->getAccount()->getAesKey(),
);
}
return $this->encryptor;
}
public function setEncryptor(Encryptor $encryptor): static
{
$this->encryptor = $encryptor;
return $this;
}
public function getSuiteEncryptor(): SuiteEncryptor
{
if (! $this->suiteEncryptor) {
$this->suiteEncryptor = new SuiteEncryptor(
suiteId: $this->getAccount()->getSuiteId(),
token: $this->getAccount()->getToken(),
aesKey: $this->getAccount()->getAesKey(),
);
}
return $this->suiteEncryptor;
}
public function setSuiteEncryptor(SuiteEncryptor $encryptor): static
{
$this->suiteEncryptor = $encryptor;
return $this;
}
public function getServer(): Server|ServerInterface
{
if (! $this->server) {
$this->server = new Server(
encryptor: $this->getSuiteEncryptor(),
providerEncryptor: $this->getEncryptor(),
request: $this->getRequest(),
);
$this->server->withDefaultSuiteTicketHandler(function (Message $message, \Closure $next): mixed {
if ($message->SuiteId === $this->getAccount()->getSuiteId()) {
$this->getSuiteTicket()->setTicket($message->SuiteTicket);
}
return $next($message);
});
}
return $this->server;
}
public function setServer(ServerInterface $server): static
{
$this->server = $server;
return $this;
}
public function getProviderAccessToken(): AccessTokenInterface
{
if (! $this->accessToken) {
$this->accessToken = new ProviderAccessToken(
corpId: $this->getAccount()->getCorpId(),
providerSecret: $this->getAccount()->getProviderSecret(),
cache: $this->getCache(),
httpClient: $this->getHttpClient(),
);
}
return $this->accessToken;
}
public function setProviderAccessToken(AccessTokenInterface $accessToken): static
{
$this->accessToken = $accessToken;
return $this;
}
public function getSuiteAccessToken(): AccessTokenInterface
{
if (! $this->suiteAccessToken) {
$this->suiteAccessToken = new SuiteAccessToken(
suiteId: $this->getAccount()->getSuiteId(),
suiteSecret: $this->getAccount()->getSuiteSecret(),
suiteTicket: $this->getSuiteTicket(),
cache: $this->getCache(),
httpClient: $this->getHttpClient(),
);
}
return $this->suiteAccessToken;
}
public function setSuiteAccessToken(AccessTokenInterface $accessToken): static
{
$this->suiteAccessToken = $accessToken;
return $this;
}
public function getSuiteTicket(): SuiteTicketInterface
{
if (! $this->suiteTicket) {
$this->suiteTicket = new SuiteTicket(
suiteId: $this->getAccount()->getSuiteId(),
cache: $this->getCache(),
);
}
return $this->suiteTicket;
}
public function setSuiteTicket(SuiteTicketInterface $suiteTicket): SuiteTicketInterface
{
$this->suiteTicket = $suiteTicket;
return $this->suiteTicket;
}
/**
* @throws HttpException
*/
public function getAuthorization(
string $corpId,
string $permanentCode,
?AccessTokenInterface $suiteAccessToken = null
): Authorization {
$suiteAccessToken = $suiteAccessToken ?? $this->getSuiteAccessToken();
$response = $this->getHttpClient()->request('POST', 'cgi-bin/service/get_auth_info', [
'query' => [
'suite_access_token' => $suiteAccessToken->getToken(),
],
'json' => [
'auth_corpid' => $corpId,
'permanent_code' => $permanentCode,
],
])->toArray(false);
if (empty($response['auth_corp_info'])) {
throw new HttpException('Failed to get auth_corp_info: '.json_encode($response, JSON_UNESCAPED_UNICODE));
}
return new Authorization($response);
}
public function getAuthorizerAccessToken(
string $corpId,
string $permanentCode,
?AccessTokenInterface $suiteAccessToken = null
): AuthorizerAccessToken {
$suiteAccessToken = $suiteAccessToken ?? $this->getSuiteAccessToken();
return new AuthorizerAccessToken(
corpId: $corpId,
permanentCodeOrAccessToken: $permanentCode,
suiteAccessToken: $suiteAccessToken,
cache: $this->getCache(),
httpClient: $this->getHttpClient(),
);
}
public function createClient(): AccessTokenAwareClient
{
return (new AccessTokenAwareClient(
client: $this->getHttpClient(),
accessToken: $this->getProviderAccessToken(),
failureJudge: fn (Response $response) => (bool) ($response->toArray()['errcode'] ?? 0),
throw: (bool) $this->config->get('http.throw', true),
))->setPresets($this->config->all());
}
public function getAuthorizerClient(string $corpId, string $permanentCode, ?AccessTokenInterface $suiteAccessToken = null): AccessTokenAwareClient
{
return (new AccessTokenAwareClient(
client: $this->getHttpClient(),
accessToken: $this->getAuthorizerAccessToken($corpId, $permanentCode, $suiteAccessToken),
failureJudge: fn (Response $response) => (bool) ($response->toArray()['errcode'] ?? 0),
throw: (bool) $this->config->get('http.throw', true),
))->setPresets($this->config->all());
}
public function getJsApiTicket(string $corpId, string $permanentCode, ?AccessTokenInterface $suiteAccessToken = null): JsApiTicket
{
return new JsApiTicket(
corpId: $corpId,
cache: $this->getCache(),
httpClient: $this->getAuthorizerClient($corpId, $permanentCode, $suiteAccessToken),
);
}
public function getOAuth(
string $suiteId,
?AccessTokenInterface $suiteAccessToken = null
): SocialiteProviderInterface {
$suiteAccessToken = $suiteAccessToken ?? $this->getSuiteAccessToken();
return (new OpenWeWork(array_filter([
'client_id' => $suiteId,
'redirect_url' => $this->config->get('oauth.redirect_url'),
'base_url' => $this->config->get('http.base_uri'),
])))->withSuiteTicket($this->getSuiteTicket()->getTicket())
->withSuiteAccessToken($suiteAccessToken->getToken())
->scopes((array) $this->config->get('oauth.scopes', ['snsapi_base']));
}
public function getCorpOAuth(
string $corpId,
?AccessTokenInterface $suiteAccessToken = null
): SocialiteProviderInterface {
$suiteAccessToken = $suiteAccessToken ?? $this->getSuiteAccessToken();
return (new OpenWeWork(array_filter([
'client_id' => $corpId,
'redirect_url' => $this->config->get('oauth.redirect_url'),
'base_url' => $this->config->get('http.base_uri'),
])))->withSuiteTicket($this->getSuiteTicket()->getTicket())
->withSuiteAccessToken($suiteAccessToken->getToken())
->scopes((array) $this->config->get('oauth.scopes', ['snsapi_base']));
}
/**
* @return array
*/
protected function getHttpClientDefaultOptions(): array
{
return array_merge(
['base_uri' => 'https://qyapi.weixin.qq.com/'],
(array) $this->config->get('http', [])
);
}
}
================================================
FILE: src/OpenWork/Authorization.php
================================================
*/
class Authorization implements Arrayable, ArrayAccess, Jsonable
{
use HasAttributes;
public function getAppId(): string
{
/** @phpstan-ignore-next-line */
return (string) $this->attributes['auth_corp_info']['corpid'];
}
}
================================================
FILE: src/OpenWork/AuthorizerAccessToken.php
================================================
httpClient = $httpClient ?? HttpClient::create(['base_uri' => 'https://qyapi.weixin.qq.com/']);
$this->cache = $cache ?? new Psr16Cache(new FilesystemAdapter(namespace: 'easywechat', defaultLifetime: 1500));
}
public function getCorpId(): string
{
return $this->corpId;
}
public function getToken(): string
{
if (! isset($this->suiteAccessToken)) {
return $this->permanentCodeOrAccessToken;
}
$token = $this->cache->get($this->getKey());
if ($token && is_string($token)) {
return $token;
}
return $this->refresh();
}
public function __toString()
{
return $this->getToken();
}
#[\JetBrains\PhpStorm\ArrayShape(['access_token' => 'string'])]
public function toQuery(): array
{
return ['access_token' => $this->getToken()];
}
public function getKey(): string
{
return $this->key ?? $this->key = sprintf('open_work.authorizer.access_token.%s.%s', $this->corpId, $this->permanentCodeOrAccessToken);
}
public function setKey(string $key): static
{
$this->key = $key;
return $this;
}
/**
* @throws HttpException
*/
public function refresh(): string
{
if (! isset($this->suiteAccessToken)) {
return '';
}
$response = $this->httpClient->request('POST', 'cgi-bin/service/get_corp_token', [
'query' => [
'suite_access_token' => $this->suiteAccessToken->getToken(),
],
'json' => [
'auth_corpid' => $this->corpId,
'permanent_code' => $this->permanentCodeOrAccessToken,
],
])->toArray(false);
if (empty($response['access_token'])) {
throw new HttpException('Failed to get access_token: '.json_encode($response, JSON_UNESCAPED_UNICODE));
}
$this->cache->set($this->getKey(), $response['access_token'], intval($response['expires_in']));
return $response['access_token'];
}
}
================================================
FILE: src/OpenWork/Config.php
================================================
*/
protected array $requiredKeys = [
'corp_id',
'suite_id',
'provider_secret',
'suite_secret',
'token',
'aes_key',
];
}
================================================
FILE: src/OpenWork/Contracts/Account.php
================================================
httpClient = $httpClient ?? HttpClient::create(['base_uri' => 'https://qyapi.weixin.qq.com/']);
$this->cache = $cache ?? new Psr16Cache(new FilesystemAdapter(namespace: 'easywechat', defaultLifetime: 1500));
}
/**
* @return array
*/
public function createConfigSignature(string $nonce, int $timestamp, string $url, array $jsApiList = [], bool $debug = false, bool $beta = true): array
{
return [
'appId' => $this->corpId,
'nonceStr' => $nonce,
'timestamp' => $timestamp,
'url' => $url,
'signature' => $this->getTicketSignature($this->getTicket(), $nonce, $timestamp, $url),
'jsApiList' => $jsApiList,
'debug' => $debug,
'beta' => $beta,
];
}
public function getTicketSignature(string $ticket, string $nonce, int $timestamp, string $url): string
{
return sha1(sprintf('jsapi_ticket=%s&noncestr=%s×tamp=%s&url=%s', $ticket, $nonce, $timestamp, $url));
}
/**
* @throws HttpException
*/
public function getTicket(): string
{
$key = $this->getKey();
$ticket = $this->cache->get($key);
if ($ticket && is_string($ticket)) {
return $ticket;
}
$response = $this->httpClient->request('GET', '/cgi-bin/get_jsapi_ticket')->toArray(false);
if (empty($response['ticket'])) {
throw new HttpException('Failed to get jssdk ticket: '.json_encode($response, JSON_UNESCAPED_UNICODE));
}
$this->cache->set($key, $response['ticket'], intval($response['expires_in']));
return $response['ticket'];
}
public function setKey(string $key): static
{
$this->key = $key;
return $this;
}
public function getKey(): string
{
return $this->key ?? $this->key = sprintf('open_work.jsapi_ticket.%s', $this->corpId);
}
public function createAgentConfigSignature(int $agentId, string $nonce, int $timestamp, string $url, array $jsApiList = []): array
{
return [
'corpid' => $this->corpId,
'agentid' => $agentId,
'nonceStr' => $nonce,
'timestamp' => $timestamp,
'signature' => $this->getTicketSignature($this->getAgentTicket($agentId), $nonce, $timestamp, $url),
'jsApiList' => $jsApiList,
];
}
/**
* @throws HttpException
*/
public function getAgentTicket(int $agentId): string
{
$key = $this->getAgentKey($agentId);
$ticket = $this->cache->get($key);
if ($ticket && is_string($ticket)) {
return $ticket;
}
$response = $this->httpClient->request('GET', '/cgi-bin/ticket/get', ['query' => ['type' => 'agent_config']])->toArray(false);
if (empty($response['ticket'])) {
throw new HttpException('Failed to get jssdk agentTicket: '.json_encode($response, JSON_UNESCAPED_UNICODE));
}
$this->cache->set($key, $response['ticket'], intval($response['expires_in']));
return $response['ticket'];
}
public function getAgentKey(int $agentId): string
{
return sprintf('%s.%s', $this->getKey(), $agentId);
}
}
================================================
FILE: src/OpenWork/Message.php
================================================
httpClient = $httpClient ?? HttpClient::create(['base_uri' => 'https://qyapi.weixin.qq.com/']);
$this->cache = $cache ?? new Psr16Cache(new FilesystemAdapter(namespace: 'easywechat', defaultLifetime: 1500));
}
public function getKey(): string
{
return $this->key ?? $this->key = \sprintf('open_work.access_token.%s.%s', $this->corpId, $this->providerSecret);
}
public function setKey(string $key): static
{
$this->key = $key;
return $this;
}
public function getToken(): string
{
$token = $this->cache->get($this->getKey());
if ($token && \is_string($token)) {
return $token;
}
return $this->refresh();
}
/**
* @return array
*/
#[\JetBrains\PhpStorm\ArrayShape(['provider_access_token' => 'string'])]
public function toQuery(): array
{
return ['provider_access_token' => $this->getToken()];
}
/**
* @throws HttpException
*/
public function refresh(): string
{
$response = $this->httpClient->request('POST', 'cgi-bin/service/get_provider_token', [
'json' => [
'corpid' => $this->corpId,
'provider_secret' => $this->providerSecret,
],
])->toArray(false);
if (empty($response['provider_access_token'])) {
throw new HttpException('Failed to get provider_access_token: '.\json_encode(
$response,
JSON_UNESCAPED_UNICODE
));
}
$this->cache->set($this->getKey(), $response['provider_access_token'], intval($response['expires_in']));
return $response['provider_access_token'];
}
}
================================================
FILE: src/OpenWork/Server.php
================================================
request = $request;
}
/**
* @throws InvalidArgumentException
* @throws BadRequestException
* @throws RuntimeException
*/
public function serve(): ResponseInterface
{
$query = $this->getRequest()->getQueryParams();
if ($str = $query['echostr'] ?? '') {
$response = $this->providerEncryptor->decrypt(
$str,
$query['msg_signature'] ?? '',
$query['nonce'] ?? '',
$query['timestamp'] ?? ''
);
return new Response(200, [], $response);
}
$message = $this->getRequestMessage($this->getRequest());
$this->prepend($this->decryptRequestMessage());
$response = $this->handle(new Response(200, [], 'success'), $message);
if (! ($response instanceof ResponseInterface)) {
$response = $this->transformToReply($response, $message, $this->encryptor);
}
return ServerResponse::make($response);
}
public function withDefaultSuiteTicketHandler(callable $handler): void
{
$this->defaultSuiteTicketHandler = fn (): mixed => $handler(...func_get_args());
$this->handleSuiteTicketRefreshed($this->defaultSuiteTicketHandler);
}
public function handleSuiteTicketRefreshed(callable $handler): static
{
if ($this->defaultSuiteTicketHandler) {
$this->withoutHandler($this->defaultSuiteTicketHandler);
}
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->InfoType === 'suite_ticket' ? $handler($message, $next) : $next($message);
});
return $this;
}
public function handleAuthCreated(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->InfoType === 'create_auth' ? $handler($message, $next) : $next($message);
});
return $this;
}
public function handleAuthChanged(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->InfoType === 'change_auth' ? $handler($message, $next) : $next($message);
});
return $this;
}
public function handleAuthCancelled(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->InfoType === 'cancel_auth' ? $handler($message, $next) : $next($message);
});
return $this;
}
public function handleUserCreated(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->InfoType === 'change_contact' && $message->ChangeType === 'create_user' ? $handler(
$message,
$next
) : $next($message);
});
return $this;
}
public function handleUserUpdated(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->InfoType === 'change_contact' && $message->ChangeType === 'update_user' ? $handler(
$message,
$next
) : $next($message);
});
return $this;
}
public function handleUserDeleted(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->InfoType === 'change_contact' && $message->ChangeType === 'delete_user' ? $handler(
$message,
$next
) : $next($message);
});
return $this;
}
public function handlePartyCreated(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->InfoType === 'change_contact' && $message->ChangeType === 'create_party' ? $handler(
$message,
$next
) : $next($message);
});
return $this;
}
public function handlePartyUpdated(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->InfoType === 'change_contact' && $message->ChangeType === 'update_party' ? $handler(
$message,
$next
) : $next($message);
});
return $this;
}
public function handlePartyDeleted(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->InfoType === 'change_contact' && $message->ChangeType === 'delete_party' ? $handler(
$message,
$next
) : $next($message);
});
return $this;
}
public function handleUserTagUpdated(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->InfoType === 'change_contact' && $message->ChangeType === 'update_tag' ? $handler(
$message,
$next
) : $next($message);
});
return $this;
}
public function handleShareAgentChanged(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->InfoType === 'share_agent_change' ? $handler($message, $next) : $next($message);
});
return $this;
}
public function handleResetPermanentCode(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->InfoType === 'reset_permanent_code' ? $handler($message, $next) : $next($message);
});
return $this;
}
public function handleChangeAppAdmin(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->MsgType === 'event' && $message->Event === 'change_app_admin' ? $handler(
$message,
$next
) : $next($message);
});
return $this;
}
protected function decryptRequestMessage(): Closure
{
$query = $this->getRequest()->getQueryParams();
return function (Message $message, Closure $next) use ($query): mixed {
$this->decryptMessage(
$message,
$this->encryptor,
$query['msg_signature'],
$query['timestamp'],
$query['nonce']
);
return $next($message);
};
}
/**
* @throws BadRequestException
*/
public function getRequestMessage(?ServerRequestInterface $request = null): \EasyWeChat\Kernel\Message
{
return Message::createFromRequest($request ?? $this->getRequest());
}
/**
* @throws BadRequestException
* @throws RuntimeException
*/
public function getDecryptedMessage(?ServerRequestInterface $request = null): \EasyWeChat\Kernel\Message
{
$request = $request ?? $this->getRequest();
$message = $this->getRequestMessage($request);
$query = $request->getQueryParams();
return $this->decryptMessage(
message: $message,
encryptor: $this->encryptor,
signature: $query['msg_signature'] ?? '',
timestamp: $query['timestamp'] ?? '',
nonce: $query['nonce'] ?? ''
);
}
}
================================================
FILE: src/OpenWork/SuiteAccessToken.php
================================================
httpClient = $httpClient ?? HttpClient::create(['base_uri' => 'https://qyapi.weixin.qq.com/']);
$this->cache = $cache ?? new Psr16Cache(new FilesystemAdapter(namespace: 'easywechat', defaultLifetime: 1500));
$this->suiteTicket ??= new SuiteTicket($this->suiteId, $this->cache);
}
public function getKey(): string
{
return $this->key ?? $this->key = \sprintf('open_work.suite_access_token.%s.%s', $this->suiteId, $this->suiteSecret);
}
public function setKey(string $key): static
{
$this->key = $key;
return $this;
}
public function getToken(): string
{
$token = $this->cache->get($this->getKey());
if ($token && \is_string($token)) {
return $token;
}
return $this->refresh();
}
/**
* @return array
*/
#[\JetBrains\PhpStorm\ArrayShape(['suite_access_token' => 'string'])]
public function toQuery(): array
{
return ['suite_access_token' => $this->getToken()];
}
/**
* @throws HttpException
*/
public function refresh(): string
{
$response = $this->httpClient->request('POST', 'cgi-bin/service/get_suite_token', [
'json' => [
'suite_id' => $this->suiteId,
'suite_secret' => $this->suiteSecret,
'suite_ticket' => $this->suiteTicket?->getTicket(),
],
])->toArray(false);
if (empty($response['suite_access_token'])) {
throw new HttpException('Failed to get suite_access_token: '.json_encode(
$response,
JSON_UNESCAPED_UNICODE
));
}
$this->cache->set(
$this->getKey(),
$response['suite_access_token'],
abs(intval($response['expires_in']) - 100)
);
return $response['suite_access_token'];
}
}
================================================
FILE: src/OpenWork/SuiteEncryptor.php
================================================
cache = $cache ?? new Psr16Cache(new FilesystemAdapter(namespace: 'easywechat', defaultLifetime: 1500));
}
public function getKey(): string
{
return $this->key ?? $this->key = sprintf('open_work.suite_ticket.%s', $this->suiteId);
}
public function setKey(string $key): static
{
$this->key = $key;
return $this;
}
public function setTicket(string $ticket): static
{
$this->cache->set($this->getKey(), $ticket, 6000);
return $this;
}
/**
* @throws RuntimeException
*/
public function getTicket(): string
{
$ticket = $this->cache->get($this->getKey());
if (! $ticket || ! is_string($ticket)) {
throw new RuntimeException('No suite_ticket found.');
}
return $ticket;
}
}
================================================
FILE: src/Pay/Application.php
================================================
getMerchant());
}
public function getMerchant(): Merchant
{
if (! $this->merchant) {
$this->merchant = new Merchant(
mchId: $this->config['mch_id'], /** @phpstan-ignore-line */
privateKey: new PrivateKey((string) $this->config['private_key']), /** @phpstan-ignore-line */
certificate: new PublicKey((string) $this->config['certificate']), /** @phpstan-ignore-line */
secretKey: (string) $this->config['secret_key'], /** @phpstan-ignore-line */
v2SecretKey: (string) $this->config['v2_secret_key'], /** @phpstan-ignore-line */
platformCerts: $this->config->has('platform_certs') ? (array) $this->config['platform_certs'] : [],/** @phpstan-ignore-line */
);
}
return $this->merchant;
}
public function getValidator(): ValidatorInterface
{
if (! $this->validator) {
$this->validator = new Validator($this->getMerchant());
}
return $this->validator;
}
public function setValidator(ValidatorInterface $validator): static
{
$this->validator = $validator;
return $this;
}
public function getServer(): Server|ServerInterface
{
if (! $this->server) {
$this->server = new Server(
merchant: $this->getMerchant(),
request: $this->getRequest(),
);
}
return $this->server;
}
public function setServer(ServerInterface $server): static
{
$this->server = $server;
return $this;
}
public function setConfig(ConfigInterface $config): static
{
$this->config = $config;
return $this;
}
public function getConfig(): ConfigInterface
{
return $this->config;
}
public function getClient(): Client|HttpClientInterface
{
return $this->client ?? $this->client = (new Client(
$this->getMerchant(),
$this->getHttpClient(),
(array) $this->config->get('http', [])
))->setPresets($this->config->all());
}
public function setClient(HttpClientInterface $client): static
{
$this->client = $client;
return $this;
}
}
================================================
FILE: src/Pay/Client.php
================================================
'https://api.mch.weixin.qq.com/',
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
],
];
protected const V3_URI_PREFIXES = [
'/v3/',
'/hk/v3/',
'/global/v3/',
];
/**
* Special absolute path string over `GET` method
*/
protected const V2_URI_OVER_GETS = [
'/appauth/getaccesstoken', // secret API which's respond `JSON`, must keep in the first
'/papay/entrustweb',
'/papay/h5entrustweb',
'/papay/partner/entrustweb',
'/papay/partner/h5entrustweb',
];
protected bool $throw = true;
/**
* @param array $defaultOptions
*/
public function __construct(
protected Merchant $merchant,
?HttpClientInterface $client = null,
array $defaultOptions = []
) {
$this->throw = (bool) ($defaultOptions['throw'] ?? true);
$this->defaultOptions = array_merge(self::OPTIONS_DEFAULTS, $this->defaultOptions);
if (! empty($defaultOptions)) {
$defaultOptions = RequestUtil::formatDefaultOptions($defaultOptions);
[, $this->defaultOptions] = self::prepareRequest(null, null, $defaultOptions, $this->defaultOptions);
}
$this->client = ($client ?? SymfonyHttpClient::create())->withOptions($this->defaultOptions);
}
/**
* @param array $options
*
* @throws InvalidArgumentException
*/
public function request(string $method, string $url, array $options = []): ResponseInterface
{
if (empty($options['headers'])) {
$options['headers'] = [];
}
$options = $this->mergeThenResetPrepends($options);
$options['headers']['User-Agent'] = UserAgent::create();
if ($this->isV3Request($url)) {
[, $_options] = $this->prepareRequest($method, $url, $options, $this->defaultOptions, true);
// 部分签名算法需要使用到 body 中额外的部分,所以交由前置逻辑自行完成
if (empty($options['headers']['Authorization'])) {
$options['headers']['Authorization'] = $this->createSignature($method, $url, $_options);
}
} else {
if (! strcasecmp($method, 'POST') && ! empty($options['xml'])) {
if (is_array($options['xml'])) {
$options['xml'] = Xml::build($this->attachLegacySignature($options['xml']));
}
$options['body'] = $options['xml'];
unset($options['xml']);
}
if (! empty($options['body']) && is_array($options['body'])) {
$options['body'] = Xml::build($this->attachLegacySignature($options['body']));
}
if (! strcasecmp($method, 'GET') && in_array($url, self::V2_URI_OVER_GETS) && is_array($options['query'] ?? null)) {
$options['query'] = $this->attachLegacySignature($options['query']);
}
if (! isset($options['headers']['Content-Type']) && ! isset($options['headers']['content-type'])) {
$options['headers']['Content-Type'] = 'text/xml';
}
}
// 合并通过 withHeader 和 withHeaders 设置的信息
if (! empty($this->prependHeaders)) {
$options['headers'] = array_merge($this->prependHeaders, $options['headers']);
}
return new Response(
$this->client->request($method, $url, $options),
failureJudge: $this->isV3Request($url) ? null : function (Response $response) use ($url): bool {
$arr = $response->toArray();
if ($url === self::V2_URI_OVER_GETS[0]) {
return ! (array_key_exists('retcode', $arr) && $arr['retcode'] === 0);
}
return ! (
// protocol code, most similar to the HTTP status code in APIv3
array_key_exists('return_code', $arr) && $arr['return_code'] === 'SUCCESS'
) || (
// business code, most similar to the Response.JSON.code in APIv3
array_key_exists('result_code', $arr) && $arr['result_code'] !== 'SUCCESS'
);
},
throw: $this->throw
);
}
protected function isV3Request(string $url): bool
{
$uri = '/'.ltrim((new Uri($url))->getPath(), '/');
foreach (self::V3_URI_PREFIXES as $prefix) {
if (str_starts_with($uri, $prefix)) {
return true;
}
}
return false;
}
/**
* @throws InvalidArgumentException
*/
public function withSerialHeader(?string $serial = null): static
{
$platformCerts = $this->merchant->getPlatformCerts();
if (empty($platformCerts)) {
throw new InvalidConfigException('Missing platform certificate.');
}
$serial ??= array_key_first($platformCerts);
$this->withHeader('Wechatpay-Serial', $serial);
return $this;
}
/**
* @param array $arguments
*/
public function __call(string $name, array $arguments): mixed
{
if (\str_starts_with($name, 'with')) {
return $this->handleMagicWithCall($name, $arguments[0] ?? null);
}
return $this->client->$name(...$arguments);
}
public function uploadMedia(string $uri, string $pathOrContents, ?array $meta = null, ?string $filename = null): ResponseInterface
{
$isFile = is_file($pathOrContents);
$meta = self::jsonEncode($meta ?? [
'filename' => $isFile ? basename($pathOrContents) : $filename ?? 'file',
'sha256' => $isFile ? hash_file('sha256', $pathOrContents) : hash('sha256', $pathOrContents),
]);
$form = Form::create([
'file' => File::from($pathOrContents),
'meta' => new DataPart($meta, null, 'application/json'),
]);
$options = $signatureOptions = $form->toOptions();
$signatureOptions['body'] = $meta;
$options['headers']['Authorization'] = $this->createSignature('POST', $uri, $signatureOptions);
return $this->request('POST', $uri, $options);
}
/**
* @param array $options
*
* @throws Exception
*/
protected function createSignature(string $method, string $url, array $options): string
{
return (new Signature($this->merchant))->createHeader($method, $url, $options);
}
/**
* @param array $body
* @return array
*
* @throws Exception
*/
protected function attachLegacySignature(array $body): array
{
return (new LegacySignature($this->merchant))->sign($body);
}
public static function createMockClient(MockHttpClient $mockHttpClient): HttpClientInterface|Mock
{
$mockMerchant = new Merchant(
'mch_id',
/** @phpstan-ignore-next-line */
Mockery::mock(PrivateKey::class),
/** @phpstan-ignore-next-line */
Mockery::mock(PublicKey::class),
'mock-v3-key',
'mock-v2-key',
[
'PUB_KEY_ID_MOCK' => '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlReZ1YnfAohRIfUqIeyP
aO0PlkMw1RLPdZbEZmldbGrIrOh/0XqSzNZ+mtB6H0eB7TSaoGFtdp/AWy3tb67m
1T62OrEhz6bnSKMcZkYVmODyxZvcwsCZ3zqCaFo7FrGmh1o9M0/Xfa5SOX4jVGni
3iM7r7YD/NiW2RCYDtjMoLTmVgrzv45Mzu2XpJqtNbUJIRRhVSnjsAZRC6spWH+b
QpYIkVd4qmYE0qdpIQBMYOV1w7v1pYn6Z5QdKG4keemADTn4QaZZHrryTcHNYVsZ
2OZ3aybrevSV3wDGnYGk2nt2xtkdfaNfFn4dGW+p4an5M4fRK+CnYpeTgI6POABk
pwIDAQAB
-----END PUBLIC KEY-----',
]
);
return Mockery::mock(static::class, [$mockMerchant, $mockHttpClient])
->shouldAllowMockingProtectedMethods()
->makePartial();
}
}
================================================
FILE: src/Pay/Config.php
================================================
*/
protected array $requiredKeys = [
'mch_id',
'secret_key',
'private_key',
'certificate',
];
}
================================================
FILE: src/Pay/Contracts/Application.php
================================================
*/
public function getPlatformCerts(): array;
}
================================================
FILE: src/Pay/Contracts/ResponseValidator.php
================================================
$params
* @return array
*
* @throws InvalidConfigException
* @throws RuntimeException
*/
public function sign(array $params): array
{
$nonce = Str::random();
$params = $attributes = array_filter(
\array_merge(
[
'nonce_str' => $nonce,
'sub_mch_id' => $params['sub_mch_id'] ?? null,
'sub_appid' => $params['sub_appid'] ?? null,
],
$params
),
static fn ($value, $key) => ! ($key === 'sign' || $value === '' || is_null($value)),
ARRAY_FILTER_USE_BOTH
);
ksort($attributes);
$attributes['key'] = $this->merchant->getV2SecretKey();
if (empty($attributes['key'])) {
throw new InvalidConfigException('Missing V2 API key.');
}
if (! empty($params['sign_type']) && $params['sign_type'] === 'HMAC-SHA256') {
$signType = fn (string $message): string => hash_hmac('sha256', $message, $attributes['key']);
} else {
$signType = 'md5';
}
$sign = call_user_func_array($signType, [urldecode(http_build_query($attributes))]);
if (! is_string($sign)) {
throw new RuntimeException('Failed to sign the request.');
}
$params['sign'] = strtoupper($sign);
return $params;
}
}
================================================
FILE: src/Pay/Merchant.php
================================================
*/
protected array $platformCerts = [];
/**
* @param array $platformCerts
*/
public function __construct(
protected int|string $mchId,
protected PrivateKey $privateKey,
protected PublicKey $certificate,
protected string $secretKey,
protected ?string $v2SecretKey = null,
array $platformCerts = [],
) {
$this->platformCerts = $this->normalizePlatformCerts($platformCerts);
}
public function getMerchantId(): int
{
return intval($this->mchId);
}
public function getPrivateKey(): PrivateKey
{
return $this->privateKey;
}
public function getCertificate(): PublicKey
{
return $this->certificate;
}
public function getSecretKey(): string
{
return $this->secretKey;
}
public function getV2SecretKey(): ?string
{
return $this->v2SecretKey;
}
public function getPlatformCert(string $serial): ?PublicKey
{
return $this->platformCerts[$serial] ?? null;
}
public function getPlatformCerts(): array
{
return $this->platformCerts;
}
/**
* @param array $platformCerts
* @return array
*
* @throws InvalidArgumentException
*/
protected function normalizePlatformCerts(array $platformCerts): array
{
$certs = [];
$isList = array_is_list($platformCerts);
foreach ($platformCerts as $index => $publicKey) {
if (is_string($publicKey)) {
$publicKey = new PublicKey($publicKey);
}
if (! $publicKey instanceof PublicKey) {
throw new InvalidArgumentException('Invalid platform certficate.');
}
$certs[$isList ? $publicKey->getSerialNo() : $index] = $publicKey;
}
return $certs;
}
}
================================================
FILE: src/Pay/Message.php
================================================
*/
public function getOriginalAttributes(): array
{
$attributes = json_decode($this->getOriginalContents(), true);
return is_array($attributes) ? $attributes : [];
}
/**
* @throws RuntimeException
*/
public function getEventType(): ?string
{
$eventType = $this->getOriginalAttributes()['event_type'];
if (! is_string($eventType)) {
throw new RuntimeException('Invalid event type.');
}
return $eventType;
}
}
================================================
FILE: src/Pay/ResponseValidator.php
================================================
toPsrResponse();
}
if ($response->getStatusCode() !== 200) {
throw new BadResponseException('Request Failed');
}
(new Validator($this->merchant))->validate($response);
}
}
================================================
FILE: src/Pay/Server.php
================================================
request = $request;
}
public function serve(): ResponseInterface
{
$message = $this->getRequestMessage();
try {
$defaultResponse = new Response(
200,
[],
strval(json_encode(['code' => 'SUCCESS', 'message' => '成功'], JSON_UNESCAPED_UNICODE))
);
$response = $this->handle($defaultResponse, $message);
if (! ($response instanceof ResponseInterface)) {
$response = $defaultResponse;
}
return ServerResponse::make($response);
} catch (Exception $e) {
return new Response(
500,
[],
strval(json_encode(['code' => 'ERROR', 'message' => $e->getMessage()], JSON_UNESCAPED_UNICODE))
);
}
}
/**
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012791861
* @link https://pay.weixin.qq.com/doc/v3/merchant/4013070368
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012791836
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012791882
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012791902
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012158598
* @link https://pay.weixin.qq.com/doc/v3/merchant/4013421143
* @link https://pay.weixin.qq.com/doc/v3/merchant/4013421231
* @link https://pay.weixin.qq.com/doc/v3/merchant/4013421336
* @link https://pay.weixin.qq.com/doc/v3/merchant/4013421407
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012587960
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012647435
* @link https://pay.weixin.qq.com/doc/v3/partner/4012085146
* @link https://pay.weixin.qq.com/doc/v3/partner/4013080237
* @link https://pay.weixin.qq.com/doc/v3/partner/4012085680
* @link https://pay.weixin.qq.com/doc/v3/partner/4012085875
* @link https://pay.weixin.qq.com/doc/v3/partner/4012085801
* @link https://pay.weixin.qq.com/doc/v3/partner/4012231898
* @link https://pay.weixin.qq.com/doc/v3/partner/4013462105
* @link https://pay.weixin.qq.com/doc/v3/partner/4013462175
* @link https://pay.weixin.qq.com/doc/v3/partner/4013462250
* @link https://pay.weixin.qq.com/doc/v3/partner/4013462574
* @link https://pay.weixin.qq.com/doc/v3/partner/4012155283
* @link https://pay.weixin.qq.com/doc/v3/partner/4012586136
* @link https://pay.weixin.qq.com/doc/v3/partner/4012085573
* @link https://pay.weixin.qq.com/doc/v3/partner/4013194298
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012284311
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012285856
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012286313
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012595808
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012289459
* @link https://pay.weixin.qq.com/doc/v3/merchant/4013392770
* @link https://pay.weixin.qq.com/doc/v3/partner/4012086059
* @link https://pay.weixin.qq.com/doc/v3/partner/4012090195
* @link https://pay.weixin.qq.com/doc/v3/partner/4012076414
* @link https://pay.weixin.qq.com/doc/v3/partner/4012159706
* @link https://pay.weixin.qq.com/doc/v2/merchant/4011935221
* @link https://pay.weixin.qq.com/doc/v2/merchant/4011937152
* @link https://pay.weixin.qq.com/doc/v2/merchant/4011937248
* @link https://pay.weixin.qq.com/doc/v2/merchant/4011938508
* @link https://pay.weixin.qq.com/doc/v2/merchant/4011941607
* @link https://pay.weixin.qq.com/doc/v2/merchant/4011985057
* @link https://pay.weixin.qq.com/doc/v2/merchant/4011985480
* @link https://pay.weixin.qq.com/doc/v2/partner/4011936650
* @link https://pay.weixin.qq.com/doc/v2/partner/4011989262
* @link https://pay.weixin.qq.com/doc/v2/partner/4011941679
* @link https://pay.weixin.qq.com/doc/v2/partner/4011941306
* @link https://pay.weixin.qq.com/doc/v2/partner/4011984334
* @link https://pay.weixin.qq.com/doc/v2/partner/4011989906
* @link https://pay.weixin.qq.com/doc/v2/partner/4011988207
* @link https://pay.weixin.qq.com/doc/v2/partner/4011984263
*/
public function handlePaid(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->getEventType() === 'TRANSACTION.SUCCESS' && $message->trade_state === 'SUCCESS'
? $handler($message, $next) : $next($message);
});
return $this;
}
/**
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012791865
* @link https://pay.weixin.qq.com/doc/v3/merchant/4013070388
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012810605
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012791886
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012791906
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012085921
* @link https://pay.weixin.qq.com/doc/v3/merchant/4013421172
* @link https://pay.weixin.qq.com/doc/v3/merchant/4013421273
* @link https://pay.weixin.qq.com/doc/v3/merchant/4013421356
* @link https://pay.weixin.qq.com/doc/v3/merchant/4013421448
* @link https://pay.weixin.qq.com/doc/v3/merchant/4013071196
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012268885
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012082022
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012587976
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012647469
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012083103
* @link https://pay.weixin.qq.com/doc/v3/merchant/4012285869
* @link https://pay.weixin.qq.com/doc/v3/partner/4012085298
* @link https://pay.weixin.qq.com/doc/v3/partner/4013080241
* @link https://pay.weixin.qq.com/doc/v3/partner/4012085681
* @link https://pay.weixin.qq.com/doc/v3/partner/4012085876
* @link https://pay.weixin.qq.com/doc/v3/partner/4012085802
* @link https://pay.weixin.qq.com/doc/v3/partner/4012231901
* @link https://pay.weixin.qq.com/doc/v3/partner/4013462126
* @link https://pay.weixin.qq.com/doc/v3/partner/4013462195
* @link https://pay.weixin.qq.com/doc/v3/partner/4013462327
* @link https://pay.weixin.qq.com/doc/v3/partner/4013462586
* @link https://pay.weixin.qq.com/doc/v3/partner/4013080628
* @link https://pay.weixin.qq.com/doc/v3/partner/4012167494
* @link https://pay.weixin.qq.com/doc/v3/partner/4012650317
* @link https://pay.weixin.qq.com/doc/v3/partner/4012166857
* @link https://pay.weixin.qq.com/doc/v3/partner/4012886275
* @link https://pay.weixin.qq.com/doc/v3/partner/4012086319
* @link https://pay.weixin.qq.com/doc/v3/partner/4012124635
* @link https://pay.weixin.qq.com/doc/v3/partner/4012076419
* @link https://pay.weixin.qq.com/doc/v3/partner/4013163616
* @link https://pay.weixin.qq.com/doc/v3/partner/4012586138
* @link https://pay.weixin.qq.com/doc/v2/merchant/4011940955
* @link https://pay.weixin.qq.com/doc/v2/merchant/4011935223
* @link https://pay.weixin.qq.com/doc/v2/merchant/4011937201
* @link https://pay.weixin.qq.com/doc/v2/merchant/4011939959
* @link https://pay.weixin.qq.com/doc/v2/merchant/4011939475
* @link https://pay.weixin.qq.com/doc/v2/merchant/4011941681
* @link https://pay.weixin.qq.com/doc/v2/merchant/4011985425
* @link https://pay.weixin.qq.com/doc/v2/merchant/4011987569
* @link https://pay.weixin.qq.com/doc/v2/partner/4011941745
* @link https://pay.weixin.qq.com/doc/v2/partner/4011936652
* @link https://pay.weixin.qq.com/doc/v2/partner/4011989265
* @link https://pay.weixin.qq.com/doc/v2/partner/4011984153
* @link https://pay.weixin.qq.com/doc/v2/partner/4012297550
* @link https://pay.weixin.qq.com/doc/v2/partner/4011984440
* @link https://pay.weixin.qq.com/doc/v2/partner/4011989912
* @link https://pay.weixin.qq.com/doc/v2/partner/4011988218
*/
public function handleRefunded(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return in_array($message->getEventType(), [
'REFUND.SUCCESS',
'REFUND.ABNORMAL',
'REFUND.CLOSED',
]) ? $handler($message, $next) : $next($message);
});
return $this;
}
public function getRequestMessage(?ServerRequestInterface $request = null): \EasyWeChat\Kernel\Message|Message
{
$originContent = (string) ($request ?? $this->getRequest())->getBody();
// 微信支付的回调数据回调,偶尔是 XML https://github.com/w7corp/easywechat/issues/2737
$contentType = ($request ?? $this->getRequest())->getHeaderLine('content-type');
$isXml = (str_contains($contentType, 'text/xml') || str_contains($contentType, 'application/xml')) && str_starts_with($originContent, 'decodeXmlMessage($originContent) : $this->decodeJsonMessage($originContent);
return new Message($attributes, $originContent);
}
/**
* @throws InvalidArgumentException
* @throws RuntimeException
*/
protected function decodeXmlMessage(string $contents): array
{
$attributes = Xml::parse($contents);
if (! is_array($attributes)) {
throw new RuntimeException('Invalid request body.');
}
if (! empty($attributes['req_info'])) {
$key = $this->merchant->getV2SecretKey();
if (empty($key)) {
throw new InvalidArgumentException('V2 secret key is required.');
}
$attributes = Xml::parse(AesEcb::decrypt($attributes['req_info'], md5($key), iv: ''));
}
if (
is_array($attributes)
&& array_key_exists('event_ciphertext', $attributes) && is_string($attributes['event_ciphertext'])
&& array_key_exists('event_nonce', $attributes) && is_string($attributes['event_nonce'])
&& array_key_exists('event_associated_data', $attributes) && is_string($attributes['event_associated_data'])
) {
$attributes += Xml::parse(AesGcm::decrypt(
$attributes['event_ciphertext'],
$this->merchant->getSecretKey(),
$attributes['event_nonce'],
$attributes['event_associated_data'] // maybe empty string
));
}
if (! is_array($attributes)) {
throw new RuntimeException('Failed to decrypt request message.');
}
return $attributes;
}
/**
* @throws RuntimeException
*/
protected function decodeJsonMessage(string $contents): array
{
$attributes = json_decode($contents, true);
if (! (is_array($attributes) && is_array($attributes['resource']))) {
throw new RuntimeException('Invalid request body.');
}
if (empty($attributes['resource']['ciphertext'] ?? null)) {
throw new RuntimeException('Invalid request.');
}
$attributes = json_decode(
AesGcm::decrypt(
$attributes['resource']['ciphertext'],
$this->merchant->getSecretKey(),
$attributes['resource']['nonce'],
$attributes['resource']['associated_data'],
),
true
);
if (! is_array($attributes)) {
throw new RuntimeException('Failed to decrypt request message.');
}
return $attributes;
}
public function getDecryptedMessage(?ServerRequestInterface $request = null): \EasyWeChat\Kernel\Message|Message
{
return $this->getRequestMessage($request);
}
}
================================================
FILE: src/Pay/Signature.php
================================================
$options
*/
public function createHeader(string $method, string $url, array $options): string
{
$uri = new Uri($url);
parse_str($uri->getQuery(), $query);
$uri = $uri->withQuery(http_build_query(array_merge($query, (array) ($options['query'] ?? []))));
$body = '';
$query = $uri->getQuery();
$timestamp = time();
$nonce = Str::random();
$path = '/'.ltrim($uri->getPath().(empty($query) ? '' : '?'.$query), '/');
if (! empty($options['body']) && (is_scalar($options['body']) || $options['body'] instanceof Stringable)) {
$body = strval($options['body']);
}
$message = strtoupper($method)."\n".
$path."\n".
$timestamp."\n".
$nonce."\n".
$body."\n";
openssl_sign($message, $signature, $this->merchant->getPrivateKey()->getKey(), 'sha256WithRSAEncryption');
return sprintf(
'WECHATPAY2-SHA256-RSA2048 %s',
sprintf(
'mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
$this->merchant->getMerchantId(),
$nonce,
$timestamp,
$this->merchant->getCertificate()->getSerialNo(),
base64_encode($signature)
)
);
}
}
================================================
FILE: src/Pay/URLSchemeBuilder.php
================================================
$appId,
'mch_id' => $this->merchant->getMerchantId(),
'time_stamp' => time(),
'nonce_str' => Str::random(),
'product_id' => $productId,
];
$params['sign'] = (new LegacySignature($this->merchant))->sign($params);
return 'weixin://wxpay/bizpayurl?'.http_build_query($params);
}
public function forCodeUrl(string $codeUrl): string
{
return sprintf('weixin://wxpay/bizpayurl?sr=%s', $codeUrl);
}
}
================================================
FILE: src/Pay/Utils.php
================================================
*/
#[\JetBrains\PhpStorm\ArrayShape([
'appId' => 'string',
'timeStamp' => 'string',
'nonceStr' => 'string',
'package' => 'string',
'signType' => 'string',
'paySign' => 'string',
])]
public function buildBridgeConfig(string $prepayId, string $appId, string $signType = 'RSA'): array
{
$params = [
'appId' => $appId,
'timeStamp' => strval(time()),
'nonceStr' => Str::random(),
'package' => "prepay_id=$prepayId",
'signType' => $signType,
];
$message = $params['appId']."\n".
$params['timeStamp']."\n".
$params['nonceStr']."\n".
$params['package']."\n";
// v2
if ($signType != 'RSA') {
$params['paySign'] = $this->createV2Signature($params);
} else {
// v3
$params['paySign'] = $this->createSignature($message);
}
return $params;
}
/**
* @see https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#58
*
* @return array
*/
#[\JetBrains\PhpStorm\ArrayShape([
'appId' => 'string',
'nonceStr' => 'string',
'package' => 'string',
'signType' => 'string',
'paySign' => 'string',
'timestamp' => 'string',
])]
public function buildSdkConfig(string $prepayId, string $appId, string $signType = 'RSA'): array
{
$params = $this->buildBridgeConfig($prepayId, $appId, $signType);
$params['timestamp'] = $params['timeStamp'];
unset($params['timeStamp']);
return $params;
}
/**
* @see https://developers.weixin.qq.com/miniprogram/dev/api/payment/wx.requestPayment.html
*
* @return array
*/
#[\JetBrains\PhpStorm\ArrayShape([
'appId' => 'string',
'timeStamp' => 'string',
'nonceStr' => 'string',
'package' => 'string',
'signType' => 'string',
'paySign' => 'string',
])]
public function buildMiniAppConfig(string $prepayId, string $appId, string $signType = 'RSA'): array
{
return $this->buildBridgeConfig($prepayId, $appId, $signType);
}
/**
* @return array
*/
#[\JetBrains\PhpStorm\ArrayShape([
'appid' => 'string',
'partnerid' => 'int',
'prepayid' => 'string',
'noncestr' => 'string',
'timestamp' => 'int',
'package' => 'string',
'sign' => 'string',
])]
public function buildAppConfig(string $prepayId, string $appId): array
{
$params = [
'appid' => $appId,
'partnerid' => $this->merchant->getMerchantId(),
'prepayid' => $prepayId,
'noncestr' => Str::random(),
'timestamp' => time(),
'package' => 'Sign=WXPay',
];
$message = $params['appid']."\n".
$params['timestamp']."\n".
$params['noncestr']."\n".
$params['prepayid']."\n";
$params['sign'] = $this->createSignature($message);
return $params;
}
protected function createSignature(string $message): string
{
openssl_sign($message, $signature, $this->merchant->getPrivateKey(), 'sha256WithRSAEncryption');
return base64_encode($signature);
}
/**
* @link https://pay.weixin.qq.com/doc/v3/merchant/4013053257
* @link https://pay.weixin.qq.com/doc/v3/partner/4013059044
*
* @param string $plaintext The text to be encrypted.
* @param string|null $serial The serial number of the platform certificate to use for encryption. If null, the first available certificate will be used.
* @return string The base64-encoded encrypted text.
*
* @throws InvalidConfigException If no platform certificate is found.
* @throws EncryptionFailureException If the encryption process fails.
*/
public function encryptWithRsaPublicKey(string $plaintext, ?string $serial = null): string
{
$platformCerts = $this->merchant->getPlatformCerts();
/** @var string $identifier - One of the serial number of the platform certificates OR the weixin pay's public key identifier. */
$identifier = $serial ?? array_key_first($platformCerts);
$platformCert = $this->merchant->getPlatformCert($identifier);
if (empty($platformCert)) {
throw new InvalidConfigException('Missing platform certificate.');
}
if (! openssl_public_encrypt($plaintext, $encrypted, $platformCert, OPENSSL_PKCS1_OAEP_PADDING)) {
throw new EncryptionFailureException('Encrypt failed.');
}
return base64_encode($encrypted);
}
/**
* @throws InvalidConfigException
*/
public function createV2Signature(array $params): string
{
$method = 'md5';
$secretKey = $this->merchant->getV2SecretKey();
if (empty($secretKey)) {
throw new InvalidConfigException('Missing v2 secret key.');
}
if ($params['signType'] === 'HMAC-SHA256') {
$method = function ($str) use ($secretKey) {
return hash_hmac('sha256', $str, $secretKey);
};
}
ksort($params);
$params['key'] = $secretKey;
// @phpstan-ignore-next-line
return strtoupper((string) call_user_func_array($method, [urldecode(http_build_query($params))]));
}
}
================================================
FILE: src/Pay/Validator.php
================================================
hasHeader($header)) {
throw new InvalidSignatureException("Missing Header: {$header}");
}
}
[$timestamp] = $message->getHeader(self::HEADER_TIMESTAMP);
[$nonce] = $message->getHeader(self::HEADER_NONCE);
[$serial] = $message->getHeader(self::HEADER_SERIAL);
[$signature] = $message->getHeader(self::HEADER_SIGNATURE);
$body = (string) $message->getBody();
$message = "{$timestamp}\n{$nonce}\n{$body}\n";
if (\time() - \intval($timestamp) > self::MAX_ALLOWED_CLOCK_OFFSET) {
throw new InvalidSignatureException('Clock Offset Exceeded');
}
$publicKey = $this->merchant->getPlatformCert($serial);
if (! $publicKey) {
throw new InvalidConfigException(
"No platform certs found for serial: {$serial},
please download from wechat pay and set it in merchant config with key `certs`."
);
}
if (\openssl_verify(
$message,
base64_decode($signature),
strval($publicKey),
OPENSSL_ALGO_SHA256
) !== 1) {
throw new InvalidSignatureException('Invalid Signature');
}
}
}
================================================
FILE: src/Work/AccessToken.php
================================================
httpClient = $httpClient ?? HttpClient::create(['base_uri' => 'https://qyapi.weixin.qq.com/']);
$this->cache = $cache ?? new Psr16Cache(new FilesystemAdapter(namespace: 'easywechat', defaultLifetime: 1500));
}
public function getKey(): string
{
return $this->key ?? $this->key = sprintf('work.access_token.%s.%s', $this->corpId, $this->secret);
}
public function setKey(string $key): static
{
$this->key = $key;
return $this;
}
public function getToken(): string
{
$token = $this->cache->get($this->getKey());
if ($token && is_string($token)) {
return $token;
}
return $this->refresh();
}
/**
* @return array
*/
#[\JetBrains\PhpStorm\ArrayShape(['access_token' => 'string'])]
public function toQuery(): array
{
return ['access_token' => $this->getToken()];
}
/**
* @throws HttpException
*/
public function refresh(): string
{
$response = $this->httpClient->request('GET', '/cgi-bin/gettoken', [
'query' => [
'corpid' => $this->corpId,
'corpsecret' => $this->secret,
],
])->toArray(false);
if (empty($response['access_token'])) {
throw new HttpException('Failed to get access_token: '.json_encode($response, JSON_UNESCAPED_UNICODE));
}
$this->cache->set($this->getKey(), $response['access_token'], intval($response['expires_in']));
return $response['access_token'];
}
}
================================================
FILE: src/Work/Account.php
================================================
corpId;
}
public function getSecret(): string
{
return $this->secret;
}
public function getToken(): string
{
return $this->token;
}
public function getAesKey(): string
{
return $this->aesKey;
}
}
================================================
FILE: src/Work/Application.php
================================================
account) {
$this->account = new Account(
corpId: (string) $this->config->get('corp_id'), /** @phpstan-ignore-line */
secret: (string) $this->config->get('secret'), /** @phpstan-ignore-line */
token: (string) $this->config->get('token'), /** @phpstan-ignore-line */
aesKey: (string) $this->config->get('aes_key'),/** @phpstan-ignore-line */
);
}
return $this->account;
}
public function setAccount(AccountInterface $account): static
{
$this->account = $account;
return $this;
}
public function getEncryptor(): Encryptor
{
if (! $this->encryptor) {
$this->encryptor = new Encryptor(
corpId: $this->getAccount()->getCorpId(),
token: $this->getAccount()->getToken(),
aesKey: $this->getAccount()->getAesKey(),
);
}
return $this->encryptor;
}
public function setEncryptor(Encryptor $encryptor): static
{
$this->encryptor = $encryptor;
return $this;
}
public function getServer(string $messageType = 'xml'): Server|ServerInterface
{
if (! $this->server) {
$this->server = new Server(
encryptor: $this->getEncryptor(),
request: $this->getRequest(),
messageType: $messageType,
);
}
return $this->server;
}
public function setServer(ServerInterface $server): static
{
$this->server = $server;
return $this;
}
public function getAccessToken(): AccessTokenInterface
{
if (! $this->accessToken) {
$this->accessToken = new AccessToken(
corpId: $this->getAccount()->getCorpId(),
secret: $this->getAccount()->getSecret(),
cache: $this->getCache(),
httpClient: $this->getHttpClient(),
);
}
return $this->accessToken;
}
public function setAccessToken(AccessTokenInterface $accessToken): static
{
$this->accessToken = $accessToken;
return $this;
}
public function getUtils(): Utils
{
return new Utils($this);
}
public function createClient(): AccessTokenAwareClient
{
return (new AccessTokenAwareClient(
client: $this->getHttpClient(),
accessToken: $this->getAccessToken(),
failureJudge: fn (Response $response) => (bool) ($response->toArray()['errcode'] ?? 0),
throw: (bool) $this->config->get('http.throw', true),
))->setPresets($this->config->all());
}
public function getOAuth(): SocialiteProviderInterface
{
$provider = new WeWork(
[
'client_id' => $this->getAccount()->getCorpId(),
'client_secret' => $this->getAccount()->getSecret(),
'redirect_url' => $this->config->get('oauth.redirect_url'),
]
);
$provider->withApiAccessToken($this->getAccessToken()->getToken());
$provider->scopes((array) $this->config->get('oauth.scopes', ['snsapi_base']));
if ($this->config->has('agent_id') && \is_numeric($this->config->get('agent_id'))) {
$provider->withAgentId((int) $this->config->get('agent_id'));
}
return $provider;
}
public function getTicket(): JsApiTicket
{
if (! $this->ticket) {
$this->ticket = new JsApiTicket(
corpId: $this->getAccount()->getCorpId(),
cache: $this->getCache(),
httpClient: $this->getClient(),
);
}
return $this->ticket;
}
public function setTicket(JsApiTicket $ticket): static
{
$this->ticket = $ticket;
return $this;
}
/**
* @return array
*/
protected function getHttpClientDefaultOptions(): array
{
return array_merge(
['base_uri' => 'https://qyapi.weixin.qq.com/'],
(array) $this->config->get('http', [])
);
}
}
================================================
FILE: src/Work/Config.php
================================================
*/
protected array $requiredKeys = [
'corp_id',
'secret',
'token',
'aes_key',
];
}
================================================
FILE: src/Work/Contracts/Account.php
================================================
httpClient = $httpClient ?? HttpClient::create(['base_uri' => 'https://qyapi.weixin.qq.com/']);
$this->cache = $cache ?? new Psr16Cache(new FilesystemAdapter(namespace: 'easywechat', defaultLifetime: 1500));
}
/**
* @return array
*/
#[\JetBrains\PhpStorm\ArrayShape([
'url' => 'string',
'nonceStr' => 'string',
'timestamp' => 'int',
'appId' => 'string',
'signature' => 'string',
])]
public function createConfigSignature(string $url, string $nonce, int $timestamp): array
{
return [
'appId' => $this->corpId,
'nonceStr' => $nonce,
'timestamp' => $timestamp,
'url' => $url,
'signature' => $this->getTicketSignature($this->getTicket(), $nonce, $timestamp, $url),
];
}
public function getTicketSignature(string $ticket, string $nonce, int $timestamp, string $url): string
{
return sha1(sprintf('jsapi_ticket=%s&noncestr=%s×tamp=%s&url=%s', $ticket, $nonce, $timestamp, $url));
}
/**
* @throws HttpException
*/
public function getTicket(): string
{
$key = $this->getKey();
$ticket = $this->cache->get($key);
if ($ticket && is_string($ticket)) {
return $ticket;
}
$response = $this->httpClient->request('GET', '/cgi-bin/get_jsapi_ticket')->toArray(false);
if (empty($response['ticket'])) {
throw new HttpException('Failed to get jssdk ticket: '.json_encode($response, JSON_UNESCAPED_UNICODE));
}
$this->cache->set($key, $response['ticket'], intval($response['expires_in']));
return $response['ticket'];
}
public function setKey(string $key): static
{
$this->key = $key;
return $this;
}
public function getKey(): string
{
return $this->key ?? $this->key = sprintf('work.jsapi_ticket.%s', $this->corpId);
}
/**
* @return array
*/
#[\JetBrains\PhpStorm\ArrayShape([
'corpid' => 'string',
'agentid' => 'int',
'nonceStr' => 'string',
'timestamp' => 'int',
'url' => 'string',
'signature' => 'string',
])]
public function createAgentConfigSignature(int $agentId, string $url, string $nonce, int $timestamp): array
{
return [
'corpid' => $this->corpId,
'agentid' => $agentId,
'nonceStr' => $nonce,
'timestamp' => $timestamp,
'url' => $url,
'signature' => $this->getTicketSignature($this->getAgentTicket($agentId), $nonce, $timestamp, $url),
];
}
/**
* @throws HttpException
*/
public function getAgentTicket(int $agentId): string
{
$key = $this->getAgentKey($agentId);
$ticket = $this->cache->get($key);
if ($ticket && is_string($ticket)) {
return $ticket;
}
$response = $this->httpClient->request('GET', '/cgi-bin/ticket/get', ['query' => ['type' => 'agent_config']])
->toArray(false);
if (empty($response['ticket'])) {
throw new HttpException('Failed to get jssdk agentTicket: '.json_encode($response, JSON_UNESCAPED_UNICODE));
}
$this->cache->set($key, $response['ticket'], intval($response['expires_in']));
return $response['ticket'];
}
public function getAgentKey(int $agentId): string
{
return sprintf('%s.%s', $this->getKey(), $agentId);
}
}
================================================
FILE: src/Work/Message.php
================================================
request = $request;
}
public function serve(): ResponseInterface
{
$query = $this->getRequest()->getQueryParams();
if (! empty($query['echostr'])) {
$response = $this->encryptor->decrypt(
$query['echostr'],
$query['msg_signature'] ?? '',
$query['nonce'] ?? '',
$query['timestamp'] ?? ''
);
return new Response(200, [], $response);
}
$message = $this->getRequestMessage($this->getRequest());
$this->prepend($this->decryptRequestMessage());
$response = $this->handle(new Response(200, [], 'SUCCESS'), $message);
if (! ($response instanceof ResponseInterface)) {
$response = $this->messageType === 'xml' ?
$this->transformToReply($response, $message, $this->encryptor) :
$this->transformJsonToReply($response, $message, $this->encryptor);
}
return ServerResponse::make($response);
}
public function handleContactChanged(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->Event === 'change_contact' ? $handler($message, $next) : $next($message);
});
return $this;
}
public function handleUserTagUpdated(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->Event === 'change_contact' && $message->ChangeType === 'update_tag' ? $handler(
$message,
$next
) : $next($message);
});
return $this;
}
public function handleUserCreated(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->Event === 'change_contact' && $message->ChangeType === 'create_user' ? $handler(
$message,
$next
) : $next($message);
});
return $this;
}
public function handleUserUpdated(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->Event === 'change_contact' && $message->ChangeType === 'update_user' ? $handler(
$message,
$next
) : $next($message);
});
return $this;
}
public function handleUserDeleted(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->Event === 'change_contact' && $message->ChangeType === 'delete_user' ? $handler(
$message,
$next
) : $next($message);
});
return $this;
}
public function handlePartyCreated(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->Event === 'change_contact' && $message->ChangeType === 'create_party' ? $handler(
$message,
$next
) : $next($message);
});
return $this;
}
public function handlePartyUpdated(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->Event === 'change_contact' && $message->ChangeType === 'update_party' ? $handler(
$message,
$next
) : $next($message);
});
return $this;
}
public function handlePartyDeleted(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->Event === 'change_contact' && $message->ChangeType === 'delete_party' ? $handler(
$message,
$next
) : $next($message);
});
return $this;
}
public function handleBatchJobsFinished(callable $handler): static
{
$this->with(function (Message $message, Closure $next) use ($handler): mixed {
return $message->Event === 'batch_job_result' ? $handler($message, $next) : $next($message);
});
return $this;
}
public function addMessageListener(string $type, callable $handler): static
{
$this->withHandler(
function (Message $message, Closure $next) use ($type, $handler): mixed {
return $message->MsgType === $type ? $handler($message, $next) : $next($message);
}
);
return $this;
}
public function addEventListener(string $event, callable $handler): static
{
$this->withHandler(
function (Message $message, Closure $next) use ($event, $handler): mixed {
return $message->Event === $event ? $handler($message, $next) : $next($message);
}
);
return $this;
}
protected function validateUrl(): Closure
{
return function (Message $message, Closure $next): Response {
$query = $this->getRequest()->getQueryParams();
$response = $this->encryptor->decrypt(
$query['echostr'],
$query['msg_signature'] ?? '',
$query['nonce'] ?? '',
$query['timestamp'] ?? ''
);
return new Response(200, [], $response);
};
}
protected function decryptRequestMessage(): Closure
{
return function (Message $message, Closure $next): mixed {
$query = $this->getRequest()->getQueryParams();
$params = [
$query['msg_signature'] ?? '',
$query['timestamp'] ?? '',
$query['nonce'] ?? '',
];
$this->decryptMessage($message, $this->encryptor, ...$params);
return $next($message);
};
}
public function getRequestMessage(?ServerRequestInterface $request = null): \EasyWeChat\Kernel\Message
{
return Message::createFromRequest($request ?? $this->getRequest());
}
public function getDecryptedMessage(?ServerRequestInterface $request = null): \EasyWeChat\Kernel\Message
{
$request = $request ?? $this->getRequest();
$message = $this->getRequestMessage($request);
$query = $request->getQueryParams();
$params = [
$query['msg_signature'] ?? '',
$query['timestamp'] ?? '',
$query['nonce'] ?? '',
];
return $this->decryptMessage(
$message,
$this->encryptor,
...$params
);
}
}
================================================
FILE: src/Work/Utils.php
================================================
$jsApiList
* @param array $openTagList
* @return array
*/
public function buildJsSdkConfig(
string $url,
array $jsApiList,
array $openTagList = [],
bool $debug = false,
bool $beta = true,
): array {
return array_merge(
compact('jsApiList', 'openTagList', 'debug', 'beta'),
$this->app->getTicket()->createConfigSignature($url, Str::random(), time())
);
}
/**
* @param array $jsApiList
* @param array $openTagList
* @return array
*/
public function buildJsSdkAgentConfig(
int $agentId,
string $url,
array $jsApiList,
array $openTagList = [],
bool $debug = false
): array {
return array_merge(
compact('jsApiList', 'openTagList', 'debug'),
$this->app->getTicket()->createAgentConfigSignature($agentId, $url, Str::random(), time())
);
}
}
================================================
FILE: tests/Kernel/EncryptorTest.php
================================================
\n \n \n\n";
$encrypt = Xml::parse($encrypted);
$decrypted = Xml::parse($this->getEncryptor()->decrypt($encrypt['Encrypt'], '4f3ad57b6989f09f4eb392acce4f9e93942ed890', '260774613', '1458300676'));
$this->assertSame('asdasdasd', $decrypted['ToUserName']);
$this->assertSame('asdasdasdsadasd', $decrypted['FromUserName']);
$this->assertSame('1234567898', $decrypted['CreateTime']);
$this->assertSame('hello', $decrypted['Content']);
}
public function test_decrypt_with_error_signature()
{
$this->expectExceptionMessage('Invalid Signature.');
$encrypted = "\n \n \n\n";
$encrypt = Xml::parse($encrypted);
$this->getEncryptor()->decrypt($encrypt['Encrypt'], 'invalid-signature', '260774613', '1458300676');
}
public function test_decrypt_with_error_received_id()
{
$this->expectExceptionMessage('Invalid appId.');
$encrypted = "\n \n \n\n";
$encryptor = new Encryptor('invalid appid', 'pamtest', 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG', 'invalid appid');
$encrypt = Xml::parse($encrypted);
$encryptor->decrypt($encrypt['Encrypt'], '4f3ad57b6989f09f4eb392acce4f9e93942ed890', '260774613', '1458300676');
}
public function test_encrypt_and_decrypt()
{
$raw = [
'ToUserName' => '测试中文',
'FromUserName' => 'gh_7f083739789a',
'CreateTime' => '1407743423',
'MsgType' => 'video',
'Video' => [
'MediaId' => 'eYJ1MbwPRJtOvIEabaxHs7TX2D-HV71s79GUxqdUkjm6Gs2Ed1KF3ulAOA9H1xG0',
'Title' => 'testCallBackReplyVideo',
'Description' => 'testCallBackReplyVideo',
],
];
$xml = Xml::build($raw);
$encrypted = $this->getEncryptor()->encrypt($xml, 'xxxxxx', '1407743423');
$array = Xml::parse($encrypted);
$this->assertSame('1407743423', $array['TimeStamp']);
$this->assertSame('xxxxxx', $array['Nonce']);
$this->assertNotEmpty($array['Encrypt']);
$this->assertNotEmpty($array['MsgSignature']);
$this->assertSame($raw, Xml::parse($this->getEncryptor()->decrypt($array['Encrypt'], $array['MsgSignature'], $array['Nonce'], $array['TimeStamp'])));
}
public function test_get_token()
{
$this->assertSame('pamtest', $this->getEncryptor()->getToken());
}
}
================================================
FILE: tests/Kernel/HttpClient/AccessTokenAwareClientTest.php
================================================
[
'accept' => 'application/json',
],
];
$client->request('GET', 'https://api2.mch.weixin.qq.com/v3/certificates', $options);
$this->assertSame('GET', $client->getRequestMethod());
$this->assertSame('https://api2.mch.weixin.qq.com/v3/certificates', $client->getRequestUrl());
$this->assertSame(['accept: application/json'], $client->getRequestOptions()['headers']);
}
public function test_shortcuts_call()
{
$client = AccessTokenAwareClient::mock();
$client->get('v3/certificates', [
'headers' => [
'accept' => 'application/json',
],
]);
$this->assertSame('GET', $client->getRequestMethod());
$this->assertSame('https://example.com/v3/certificates', $client->getRequestUrl());
$this->assertSame(['accept: application/json'], $client->getRequestOptions()['headers']);
}
public function test_it_will_auto_wrap_body()
{
$client = AccessTokenAwareClient::mock();
$client->post('v3/certificates', [
'body' => [
'foo' => 'bar',
],
]);
$this->assertSame('POST', $client->getRequestMethod());
$this->assertSame('https://example.com/v3/certificates', $client->getRequestUrl());
$this->assertSame('foo=bar', $client->getRequestOptions()['body']);
// post without body key
$client = AccessTokenAwareClient::mock();
$client->post('v3/certificates', [
'foo' => 'bar',
]);
$this->assertSame('POST', $client->getRequestMethod());
$this->assertSame('https://example.com/v3/certificates', $client->getRequestUrl());
$this->assertSame('foo=bar', $client->getRequestOptions()['body']);
// patch without body key
$client = AccessTokenAwareClient::mock();
$client->patch('v3/certificates', [
'foo' => 'bar',
]);
$this->assertSame('PATCH', $client->getRequestMethod());
$this->assertSame('https://example.com/v3/certificates', $client->getRequestUrl());
$this->assertSame('foo=bar', $client->getRequestOptions()['body']);
// put without body key
$client = AccessTokenAwareClient::mock();
$client->put('v3/certificates', [
'foo' => 'bar',
]);
$this->assertSame('PUT', $client->getRequestMethod());
$this->assertSame('https://example.com/v3/certificates', $client->getRequestUrl());
$this->assertSame('foo=bar', $client->getRequestOptions()['body']);
}
public function test_it_will_apply_access_token_to_query()
{
$client = AccessTokenAwareClient::mock();
$client->withAccessToken(new class implements AccessToken
{
public function getToken(): string
{
return 'mock-access-token';
}
public function toQuery(): array
{
return ['access_token' => 'mock-access-token'];
}
});
$client->get('v3/certificates', ['foo' => 'bar']);
$this->assertSame('https://example.com/v3/certificates?foo=bar&access_token=mock-access-token', $client->getRequestUrl());
}
public function test_it_will_merge_presets()
{
$client = AccessTokenAwareClient::mock();
$client->setPresets([
'mch_id' => 'mock-mch-id',
]);
// raw name
$client->withMchId()->get('v3/certificates');
$this->assertSame('https://example.com/v3/certificates?mch_id=mock-mch-id', $client->getRequestUrl());
$client = AccessTokenAwareClient::mock();
$client->setPresets([
'mch_id' => 'mock-mch-id',
]);
// alias
$client->withMchIdAs('mchid')->get('v3/certificates');
$this->assertSame('https://example.com/v3/certificates?mchid=mock-mch-id', $client->getRequestUrl());
}
}
================================================
FILE: tests/Kernel/HttpClient/AccessTokenExpiredRetryStrategyTest.php
================================================
getContext(2, 'GET', 'http://easywechat.com', 200);
$this->assertFalse($strategy->shouldRetry($context, 'mock-response', null));
// no decider: 429 should be retried (default)
$context = $this->getContext(2, 'GET', 'http://easywechat.com', 429);
$this->assertTrue($strategy->shouldRetry($context, 'mock-response', null));
}
public function test_it_will_refresh_access_token_when_token_is_refreshable()
{
$strategy = new AccessTokenExpiredRetryStrategy;
$notRefreshAbleAccessToken = \Mockery::mock(AccessToken::class, function ($mock) {
$mock->shouldReceive('refresh')->never();
});
// no decider: 200 should not be retried
$context = $this->getContext(2, 'GET', 'http://easywechat.com', 200);
$this->assertFalse($strategy->shouldRetry($context, 'mock-response', null));
// with not refreshable access token: 200 should not be retried
$strategy->withAccessToken($notRefreshAbleAccessToken)
->decideUsing(function () {
return true;
});
$context = $this->getContext(2, 'GET', 'http://easywechat.com', 200);
$this->assertFalse($strategy->shouldRetry($context, 'mock-response', null));
$this->assertFalse($strategy->shouldRetry($context, 'mock-response', null));
// with refreshable access token and token expired: should be retried first time
$refreshAbleAccessToken = \Mockery::mock(RefreshableAccessToken::class, function ($mock) {
$mock->shouldReceive('refresh')->twice()->andReturns('mock-access-token', false);
});
$strategy->withAccessToken($refreshAbleAccessToken)
->decideUsing(function () {
return true;
});
$context = $this->getContext(2, 'GET', 'http://easywechat.com', 200);
// first time should be retried
$this->assertTrue($strategy->shouldRetry($context, 'mock-response', null));
// refresh failed(no refresh result string returned): should not be retried
$this->assertFalse($strategy->shouldRetry($context, 'mock-response', null));
}
private function getContext($retryCount, $method, $url, $statusCode): AsyncContext
{
$passthru = null;
$info = [
'retry_count' => $retryCount,
'http_method' => $method,
'url' => $url,
'http_code' => $statusCode,
];
$response = new MockResponse('', $info);
return new AsyncContext($passthru, new MockHttpClient, $response, $info, null, 0);
}
}
================================================
FILE: tests/Kernel/HttpClient/HttpClientMethodsTest.php
================================================
get('http://easywechat.com');
$this->assertInstanceOf(ResponseInterface::class, $response);
$this->assertSame('GET', $response->getRequestMethod());
$this->assertSame('http://easywechat.com', $response->getRequestUrl());
}
public function test_post()
{
$client = new DummyHttpClient;
$response = $client->post('http://easywechat.com', ['foo' => 'bar']);
$this->assertSame('POST', $response->getRequestMethod());
$this->assertSame('http://easywechat.com', $response->getRequestUrl());
$this->assertSame(['foo' => 'bar'], $response->getRequestOptions()['body']);
$response = $client->post('http://easywechat.com', ['json' => ['foo' => 'bar']]);
$this->assertSame('POST', $response->getRequestMethod());
$this->assertSame('http://easywechat.com', $response->getRequestUrl());
$this->assertSame(['json' => ['foo' => 'bar']], $response->getRequestOptions());
$response = $client->post('http://easywechat.com', ['xml' => ['foo' => 'bar']]);
$this->assertSame('POST', $response->getRequestMethod());
$this->assertSame('http://easywechat.com', $response->getRequestUrl());
$this->assertSame(['xml' => ['foo' => 'bar']], $response->getRequestOptions());
}
public function test_post_json()
{
$client = new DummyHttpClient;
$response = $client->postJson('http://easywechat.com', ['foo' => 'bar']);
$this->assertSame('POST', $response->getRequestMethod());
$this->assertSame('http://easywechat.com', $response->getRequestUrl());
$this->assertSame(['foo' => 'bar'], $response->getRequestOptions()['json']);
$this->assertSame('application/json', $response->getRequestOptions()['headers']['Content-Type']);
// with options keywords
$response = $client->postJson('http://easywechat.com', ['foo' => 'bar', 'query' => 'k1=v1&k2=v2']);
$this->assertSame(['foo' => 'bar', 'query' => 'k1=v1&k2=v2'], $response->getRequestOptions()['json']);
}
public function test_post_xml()
{
$client = new DummyHttpClient;
// no type
$response = $client->postXml('http://easywechat.com', ['foo' => 'bar'], [
'headers' => ['Accept' => 'application/xml'],
]);
$this->assertSame('POST', $response->getRequestMethod());
$this->assertSame('http://easywechat.com', $response->getRequestUrl());
$this->assertSame(['foo' => 'bar'], $response->getRequestOptions()['xml']);
$this->assertSame('text/xml', $response->getRequestOptions()['headers']['Content-Type']);
$this->assertSame('application/xml', $response->getRequestOptions()['headers']['Accept']);
// with type
$response = $client->postXml('http://easywechat.com', ['xml' => ['foo' => 'bar']]);
$this->assertSame('POST', $response->getRequestMethod());
$this->assertSame('http://easywechat.com', $response->getRequestUrl());
$this->assertSame(['foo' => 'bar'], $response->getRequestOptions()['xml']);
$this->assertSame('text/xml', $response->getRequestOptions()['headers']['Content-Type']);
// with string
$response = $client->postXml('http://easywechat.com', ['xml' => Xml::build(['foo' => 'bar'])]);
$this->assertSame('POST', $response->getRequestMethod());
$this->assertSame('http://easywechat.com', $response->getRequestUrl());
$this->assertSame(Xml::build(['foo' => 'bar']), $response->getRequestOptions()['xml']);
$this->assertSame('text/xml', $response->getRequestOptions()['headers']['Content-Type']);
// with options keywords
$response = $client->postXml('http://easywechat.com', ['xml' => ['foo' => 'bar', 'query' => 'k1=v1&k2=v2']]);
$this->assertSame(['foo' => 'bar', 'query' => 'k1=v1&k2=v2'], $response->getRequestOptions()['xml']);
}
public function test_put()
{
$client = new DummyHttpClient;
$response = $client->put('http://easywechat.com', ['foo' => 'bar']);
$this->assertSame('PUT', $response->getRequestMethod());
$this->assertSame('http://easywechat.com', $response->getRequestUrl());
$this->assertSame(['foo' => 'bar'], $response->getRequestOptions()['body']);
}
public function test_patch()
{
$client = new DummyHttpClient;
$response = $client->patch('http://easywechat.com', ['foo' => 'bar']);
$this->assertSame('PATCH', $response->getRequestMethod());
$this->assertSame('http://easywechat.com', $response->getRequestUrl());
$this->assertSame(['foo' => 'bar'], $response->getRequestOptions()['body']);
}
public function test_patch_json()
{
$client = new DummyHttpClient;
$response = $client->patchJson('http://easywechat.com', ['foo' => 'bar']);
$this->assertSame('PATCH', $response->getRequestMethod());
$this->assertSame('http://easywechat.com', $response->getRequestUrl());
$this->assertSame(['foo' => 'bar'], $response->getRequestOptions()['json']);
$this->assertSame('application/json', $response->getRequestOptions()['headers']['Content-Type']);
}
public function test_delete()
{
$client = new DummyHttpClient;
$response = $client->delete('http://easywechat.com');
$this->assertSame('DELETE', $response->getRequestMethod());
$this->assertSame('http://easywechat.com', $response->getRequestUrl());
}
}
class DummyHttpClient
{
use HttpClientMethods;
public function request($method, $url, $options = []): ResponseInterface
{
$response = new MockResponse('');
$response->fromRequest($method, $url, $options, $response);
return $response;
}
}
================================================
FILE: tests/Kernel/HttpClient/RequestUtilTest.php
================================================
GenericRetryStrategy::DEFAULT_RETRY_STATUS_CODES,
'delay' => 1000,
'max_delay' => 0,
'max_retries' => 3,
'multiplier' => 2.0,
'jitter' => 0.1,
];
$this->assertSame($defaultRetryOptions, RequestUtil::mergeDefaultRetryOptions([]));
$this->assertSame(
\array_merge($defaultRetryOptions, ['max_retries' => 3, 'jitter' => 2]),
RequestUtil::mergeDefaultRetryOptions(['max_retries' => 3, 'jitter' => 2])
);
}
public function test_format_default_options()
{
$options = ['foo' => 'bar', 'headers' => ['User-Agent' => 'EasyWeChat']];
$formatted = RequestUtil::formatDefaultOptions($options);
$this->assertArrayNotHasKey('foo', $formatted);
$this->assertArrayHasKey('User-Agent', $formatted['headers']);
$this->assertSame('EasyWeChat', $formatted['headers']['User-Agent']);
// test default User-Agent
$options = ['foo' => 'bar', 'headers' => ['foo' => 'bar']];
$formatted = RequestUtil::formatDefaultOptions($options);
$this->assertArrayNotHasKey('foo', $formatted);
$this->assertArrayHasKey('User-Agent', $formatted['headers']);
$this->assertSame(UserAgent::create(), $formatted['headers']['User-Agent']);
}
public function test_format_options()
{
// GET
$options = ['overtrue' => 'true', 'hello' => 'world', 'headers' => ['User-Agent' => 'EasyWeChat']];
$formatted = RequestUtil::formatOptions($options, 'GET');
$this->assertArrayNotHasKey('overtrue', $formatted);
$this->assertArrayNotHasKey('hello', $formatted);
$this->assertArrayHasKey('query', $formatted);
$this->assertSame('true', $formatted['query']['overtrue']);
$this->assertSame('world', $formatted['query']['hello']);
// DELETE
$options = ['overtrue' => 'true', 'hello' => 'world', 'headers' => ['User-Agent' => 'EasyWeChat']];
$formatted = RequestUtil::formatOptions($options, 'DELETE');
$this->assertArrayNotHasKey('overtrue', $formatted);
$this->assertArrayNotHasKey('hello', $formatted);
$this->assertArrayHasKey('query', $formatted);
$this->assertSame('true', $formatted['query']['overtrue']);
$this->assertSame('world', $formatted['query']['hello']);
// POST
$options = ['overtrue' => 'true', 'hello' => 'world', 'headers' => ['User-Agent' => 'EasyWeChat']];
$formatted = RequestUtil::formatOptions($options, 'POST');
$this->assertArrayNotHasKey('overtrue', $formatted);
$this->assertArrayNotHasKey('hello', $formatted);
$this->assertArrayHasKey('body', $formatted);
$this->assertSame('true', $formatted['body']['overtrue']);
$this->assertSame('world', $formatted['body']['hello']);
// POST with json
$options = ['overtrue' => 'true', 'hello' => 'world', 'headers' => ['User-Agent' => 'EasyWeChat', 'content-type' => 'application/json']];
$formatted = RequestUtil::formatOptions($options, 'POST');
$this->assertArrayNotHasKey('overtrue', $formatted);
$this->assertArrayNotHasKey('hello', $formatted);
$this->assertArrayHasKey('json', $formatted);
$this->assertSame(['overtrue' => 'true', 'hello' => 'world'], $formatted['json']);
// POST with xml
$options = ['overtrue' => 'true', 'hello' => 'world', 'headers' => ['User-Agent' => 'EasyWeChat', 'content-type' => 'text/xml']];
$formatted = RequestUtil::formatOptions($options, 'POST');
$this->assertArrayNotHasKey('overtrue', $formatted);
$this->assertArrayNotHasKey('hello', $formatted);
$this->assertArrayHasKey('xml', $formatted);
$this->assertSame(['overtrue' => 'true', 'hello' => 'world'], $formatted['xml']);
// PATCH
$options = ['overtrue' => 'true', 'hello' => 'world', 'headers' => ['User-Agent' => 'EasyWeChat']];
$formatted = RequestUtil::formatOptions($options, 'PATCH');
$this->assertArrayNotHasKey('overtrue', $formatted);
$this->assertArrayNotHasKey('hello', $formatted);
$this->assertArrayHasKey('body', $formatted);
$this->assertSame('true', $formatted['body']['overtrue']);
$this->assertSame('world', $formatted['body']['hello']);
// POST with `query`
$options = ['overtrue' => 'true', 'hello' => 'world', '"query"' => 'id=1'];
$formatted = RequestUtil::formatOptions($options, 'POST');
$this->assertArrayNotHasKey('overtrue', $formatted);
$this->assertArrayNotHasKey('hello', $formatted);
$this->assertArrayHasKey('body', $formatted);
$this->assertArrayNotHasKey('query', $formatted);
$this->assertArrayHasKey('query', $formatted['body']);
$this->assertSame('id=1', $formatted['body']['query']);
$this->assertSame('true', $formatted['body']['overtrue']);
$this->assertSame('world', $formatted['body']['hello']);
}
public function test_format_xml_body()
{
// xml string
$options = RequestUtil::formatBody(['xml' => 'bar']);
$this->assertArrayNotHasKey('xml', $options);
$this->assertArrayHasKey('body', $options);
$this->assertSame('bar', $options['body']);
$this->assertSame('text/xml', $options['headers']['Content-Type']);
// xml array
$options = RequestUtil::formatBody(['xml' => ['foo' => 'bar']]);
$this->assertArrayNotHasKey('xml', $options);
$this->assertArrayHasKey('body', $options);
$this->assertSame('bar', $options['body']);
$this->assertSame('text/xml', $options['headers']['Content-Type']);
// invalid xml
$this->expectExceptionMessage('The type of `xml` must be string or array.');
RequestUtil::formatBody(['xml' => true]);
}
public function test_format_json_body()
{
// json string
$options = RequestUtil::formatBody(['json' => '{"foo":"bar"}']);
$this->assertArrayNotHasKey('json', $options);
$this->assertArrayHasKey('body', $options);
$this->assertSame('{"foo":"bar"}', $options['body']);
$this->assertSame('application/json', $options['headers']['Content-Type']);
// json array
$options = RequestUtil::formatBody(['json' => ['foo' => 'bar', 'chinese' => '中文']]);
$this->assertArrayNotHasKey('json', $options);
$this->assertArrayHasKey('body', $options);
$this->assertSame('{"foo":"bar","chinese":"中文"}', $options['body']);
// json empty array
$options = RequestUtil::formatBody(['json' => []]);
$this->assertArrayNotHasKey('json', $options);
$this->assertArrayHasKey('body', $options);
$this->assertSame('{}', $options['body']);
// invalid json
$this->expectExceptionMessage('The type of `json` must be string or array.');
RequestUtil::formatBody(['json' => true]);
}
}
================================================
FILE: tests/Kernel/HttpClient/RequestWithPresetsTest.php
================================================
with('foo', 'bar')
->with('bar')
->with(['appid' => 'wx123456', 'secret'])
->with([
'age' => 12,
'name' => 'overtrue',
])
->with('items', ['foo', 'bar']);
$this->assertSame([
'foo' => 'bar',
'bar' => null,
'appid' => 'wx123456',
'secret' => null,
'age' => 12,
'name' => 'overtrue',
'items' => ['foo', 'bar'],
], $client->getPrependsParts());
// update
$client->with('foo', 'baz');
$this->assertSame([
'foo' => 'baz',
'bar' => null,
'appid' => 'wx123456',
'secret' => null,
'age' => 12,
'name' => 'overtrue',
'items' => ['foo', 'bar'],
], $client->getPrependsParts());
}
public function test_it_can_with_key_of_presets()
{
$client = new DummyClassForRequestWithPresetsTest;
$client->setPresets([
'appid' => 'wx123456',
'secret' => 'helloworld',
'bar' => 'baz',
]);
$client->with('foo', 'bar')
->with('bar')
->with(['appid', 'secret']);
$this->assertSame([
'foo' => 'bar',
'bar' => 'baz',
'appid' => 'wx123456',
'secret' => 'helloworld',
], $client->getPrependsParts());
}
public function test_it_can_with_use_magic_call()
{
$client = new DummyClassForRequestWithPresetsTest;
$client->setPresets([
'appid' => 'wx123456',
'secret' => 'helloworld',
'bar' => 'balabala',
'name' => 'w7corp',
]);
$client->with('foo', 'bar')
->with('bar')
->withAppid()
->withSecret()
->withBarAs('baz')
->withName('overtrue');
$this->assertSame([
'foo' => 'bar',
'bar' => 'balabala',
'appid' => 'wx123456',
'secret' => 'helloworld',
'baz' => 'balabala',
'name' => 'overtrue',
], $client->getPrependsParts());
}
public function test_it_can_merge_to_options()
{
$client = new DummyClassForRequestWithPresetsTest;
$client->setPresets([
'appid' => 'wx123456',
'secret' => 'helloworld',
'bar' => 'balabala',
'name' => 'w7corp',
]);
// empty
$this->assertSame([], $client->mergeThenResetPrepends([]));
// GET/HEAD/DELETE
$client->withAppid()->withSecret();
$this->assertSame(['query' => ['appid' => 'wx123456', 'secret' => 'helloworld']], $client->mergeThenResetPrepends([]));
$client->withAppid()->withSecret();
$this->assertSame(['query' => ['appid' => 'wx123456', 'secret' => 'helloworld']], $client->mergeThenResetPrepends([], 'HEAD'));
$client->withAppid()->withSecret();
$this->assertSame(['query' => ['appid' => 'wx123456', 'secret' => 'helloworld']], $client->mergeThenResetPrepends([], 'DELETE'));
// POST/PUT/PATCH
$client->withAppid()->withSecret();
$this->assertSame(['body' => ['appid' => 'wx123456', 'secret' => 'helloworld']], $client->mergeThenResetPrepends([], 'POST'));
$client->withAppid()->withSecret();
$this->assertSame(['body' => ['appid' => 'wx123456', 'secret' => 'helloworld']], $client->mergeThenResetPrepends([], 'PUT'));
$client->withAppid()->withSecret();
$this->assertSame(['body' => ['appid' => 'wx123456', 'secret' => 'helloworld']], $client->mergeThenResetPrepends([], 'PATCH'));
// merge
$client->withAppid();
$this->assertSame(
['query' => ['appid' => 'wx123456', 'name' => '1234']],
$client->mergeThenResetPrepends(['query' => ['name' => '1234']])
);
$client->withAppid();
$this->assertSame(
['body' => ['appid' => 'wx123456', 'name' => '1234']],
$client->mergeThenResetPrepends(['body' => ['name' => '1234']], 'POST')
);
// XML
// 1. !empty xml
$client->withAppid();
$this->assertSame(
['xml' => ['appid' => 'wx123456', 'name' => '1234']],
$client->mergeThenResetPrepends(['xml' => ['name' => '1234']], 'POST')
);
// 2. content-type is xml
$client->withAppid();
$this->assertSame(
['headers' => ['content-type' => 'text/xml'], 'xml' => ['appid' => 'wx123456']],
$client->mergeThenResetPrepends(['headers' => ['content-type' => 'text/xml']], 'POST')
);
// JSON
// 1. !empty json
$client->withAppid();
$this->assertSame(
['json' => ['appid' => 'wx123456', 'name' => '1234']],
$client->mergeThenResetPrepends(['json' => ['name' => '1234']], 'POST')
);
// 2. content-type is json
$client->withAppid();
$this->assertSame(
['headers' => ['content-type' => 'application/json'], 'json' => ['appid' => 'wx123456']],
$client->mergeThenResetPrepends(['headers' => ['content-type' => 'application/json']], 'POST')
);
// HEADERS
$client->withAppid()->withHeader('X-foo', 'bar');
$this->assertSame(
['headers' => ['X-foo' => 'bar', 'content-type' => 'application/json'], 'json' => ['appid' => 'wx123456']],
$client->mergeThenResetPrepends(['headers' => ['content-type' => 'application/json']], 'POST')
);
// 带下划线
$client->setPresets([
'app_id' => 'wx123456',
'secret' => 'helloworld',
'bar' => 'balabala',
'name' => 'w7corp',
]);
// GET/HEAD/DELETE
$client->withAppId()->withSecret();
$this->assertSame(['query' => ['app_id' => 'wx123456', 'secret' => 'helloworld']], $client->mergeThenResetPrepends([]));
$client->withAppId()->withSecret();
$this->assertSame(['query' => ['app_id' => 'wx123456', 'secret' => 'helloworld']], $client->mergeThenResetPrepends([], 'HEAD'));
$client->withAppId()->withSecret();
$this->assertSame(['query' => ['app_id' => 'wx123456', 'secret' => 'helloworld']], $client->mergeThenResetPrepends([], 'DELETE'));
// POST/PUT/PATCH
$client->withAppId()->withSecret();
$this->assertSame(['body' => ['app_id' => 'wx123456', 'secret' => 'helloworld']], $client->mergeThenResetPrepends([], 'POST'));
$client->withAppId()->withSecret();
$this->assertSame(['body' => ['app_id' => 'wx123456', 'secret' => 'helloworld']], $client->mergeThenResetPrepends([], 'PUT'));
$client->withAppId()->withSecret();
$this->assertSame(['body' => ['app_id' => 'wx123456', 'secret' => 'helloworld']], $client->mergeThenResetPrepends([], 'PATCH'));
// test As
$client->withAppIdAs('test')->withSecret();
$this->assertSame(['query' => ['test' => 'wx123456', 'secret' => 'helloworld']], $client->mergeThenResetPrepends([]));
// test key/value
$client->withAppId('test')->withSecret();
$this->assertSame(['query' => ['app_id' => 'test', 'secret' => 'helloworld']], $client->mergeThenResetPrepends([]));
}
public function test_it_can_with_headers()
{
$client = new DummyClassForRequestWithPresetsTest;
$client->withHeaders(['content-type' => 'application/xml'])->withHeader('accept', 'application/json');
$this->assertSame(
['content-type' => 'application/xml', 'accept' => 'application/json'],
$client->getPrependsHeaders()
);
// update
$client->withHeaders(['content-type' => 'text/xml']);
$this->assertSame(
['content-type' => 'text/xml', 'accept' => 'application/json'],
$client->getPrependsHeaders()
);
}
}
class DummyClassForRequestWithPresetsTest
{
use RequestWithPresets;
public function getPrependsParts(): array
{
return $this->prependParts;
}
public function getPrependsHeaders(): array
{
return $this->prependHeaders;
}
public function __call(string $name, array $arguments)
{
if (\str_starts_with($name, 'with')) {
return $this->handleMagicWithCall($name, $arguments[0] ?? null);
}
throw new \BadMethodCallException('Call to undefined method '.__CLASS__.'::'.$name.'()');
}
}
================================================
FILE: tests/Kernel/HttpClient/ResponseTest.php
================================================
shouldReceive('getContent')->andReturns('');
});
$this->expectException(BadResponseException::class);
(new Response($response))->toArray();
}
public function test_it_can_decode_xml()
{
$response = \Mockery::mock(ResponseInterface::class, function ($mock) {
$mock->shouldReceive('getHeaders')->andReturns([], ['content-type' => ['text/xml']], ['content-type' => ['text/xml']]);
$mock->shouldReceive('getContent')->andReturns('bar', 'bar', '');
});
$this->assertSame(['foo' => 'bar'], (new Response($response))->toArray());
$this->assertSame(['foo' => 'bar'], (new Response($response))->toArray());
$response = (new Response($response))->toArray();
$this->assertIsArray($response);
$this->assertEmpty($response);
}
public function test_it_support_array_access()
{
$response = \Mockery::mock(ResponseInterface::class, function ($mock) {
$mock->shouldReceive('getHeaders')->andReturns([]);
$mock->shouldReceive('getContent')->andReturns('{"foo":"bar"}');
$mock->shouldReceive('toArray')->andReturns(['foo' => 'bar']);
});
$response = (new Response($response));
$this->assertSame('bar', $response['foo']);
$this->assertNull($response['not-exist']);
$this->assertTrue(isset($response['foo']));
$this->assertFalse(isset($response['not-exist']));
}
public function test_it_support_to_json()
{
$response = \Mockery::mock(ResponseInterface::class, function ($mock) {
$mock->shouldReceive('getHeaders')->andReturns([]);
$mock->shouldReceive('getContent')->andReturns('{"foo":"bar"}');
$mock->shouldReceive('toArray')->andReturns(['foo' => 'bar']);
});
$response = (new Response($response));
$this->assertSame('{"foo":"bar"}', $response->toJson());
}
public function test_it_can_get_headers()
{
$response = \Mockery::mock(ResponseInterface::class, function ($mock) {
$mock->shouldReceive('getHeaders')->andReturns([
'content-type' => ['text/xml; encoding=utf-8'],
'cache-control' => ['max-age=3600', 'public'],
]);
});
$response = (new Response($response));
$this->assertTrue($response->hasHeader('content-type'));
$this->assertSame(['text/xml; encoding=utf-8'], $response->getHeader('content-type'));
$this->assertSame('max-age=3600,public', $response->getHeaderLine('cache-control'));
}
public function test_it_can_save_content_to_files()
{
$response = \Mockery::mock(ResponseInterface::class, function ($mock) {
$mock->shouldReceive('getHeaders')->andReturns([]);
$mock->shouldReceive('getContent')->andReturns('{"foo":"bar"}');
$mock->shouldReceive('toArray')->andReturns(['foo' => 'bar']);
});
$response = (new Response($response));
$tmpFile = \sys_get_temp_dir().'/'.\uniqid('', true);
$response->saveAs($tmpFile);
$this->assertSame('{"foo":"bar"}', \file_get_contents($tmpFile));
@\unlink($tmpFile);
// throw when response get content failed
$response = \Mockery::mock(ResponseInterface::class, function ($mock) {
$mock->shouldReceive('getContent')->with(true)->andThrow(new \Exception('mock-exception'))->once();
$mock->shouldReceive('getContent')->with(false)->andReturns('{"errcode":40029, "errmsg":"invalid code"}')->once();
});
$response = (new Response($response));
$this->expectException(BadResponseException::class);
$this->expectExceptionMessageMatches('/Cannot save response to .*?: {"errcode":40029, "errmsg":"invalid code"}/');
$response->saveAs($tmpFile);
}
public function test_it_can_transform_to_data_url()
{
$response = \Mockery::mock(ResponseInterface::class, function ($mock) {
$mock->shouldReceive('getHeaders')->andReturns(['content-type' => ['application/json;encoding=utf-8']]);
$mock->shouldReceive('getContent')->andReturns('{"foo":"bar"}');
$mock->shouldReceive('toArray')->andReturns(['foo' => 'bar']);
});
$response = (new Response($response));
$this->assertSame('data:application/json;encoding=utf-8;base64,eyJmb28iOiJiYXIifQ==', $response->toDataUrl());
}
public function test_it_can_judge_failure_with_custom_callback()
{
// from http code 200
$response = \Mockery::mock(ResponseInterface::class, function ($mock) {
$mock->shouldReceive('getStatusCode')->andReturns(200)->times(2);
$mock->shouldReceive('getHeaders')->andReturns(['content-type' => ['application/json;encoding=utf-8']]);
});
$response = (new Response($response));
$this->assertFalse($response->isFailed()); // 200
$this->assertTrue($response->isSuccessful());
// from http code 400
$response = \Mockery::mock(ResponseInterface::class, function ($mock) {
$mock->shouldReceive('getHeaders')->andReturns(['content-type' => ['application/json;encoding=utf-8']]);
$mock->shouldReceive('getStatusCode')->andReturns(400)->times(2);
});
$response = (new Response($response));
$this->assertTrue($response->isFailed()); // 400
$this->assertFalse($response->isSuccessful());
// custom callback
$response = \Mockery::mock(ResponseInterface::class, function ($mock) {
$mock->shouldReceive('getStatusCode')->never();
$mock->shouldReceive('getHeaders')->andReturns(['content-type' => ['application/json;encoding=utf-8']]);
$mock->shouldReceive('getContent')->andReturns(\json_encode(['errcode' => 40029, 'errmsg' => 'invalid code']));
$mock->shouldReceive('toArray')->andReturns(['errcode' => 40029, 'errmsg' => 'invalid code']);
});
$response = (new Response($response));
$response->judgeFailureUsing(function ($response) {
return ! empty($response->toArray()['errcode'] ?? null);
});
$this->assertTrue($response->isFailed());
$this->assertFalse($response->isSuccessful());
}
public function test_it_can_has_global_throw_settings()
{
$httpClient = new MockHttpClient(new MockResponse('{"foo":"bar"}', ['http_code' => 403]));
$response = (new Response($httpClient->request('GET', '/foo'), throw: false));
// global throw setting is false
try {
$this->assertSame(['foo' => 'bar'], $response->toArray());
$this->assertSame('{"foo":"bar"}', $response->getContent());
} catch (\Exception $e) {
$this->fail('should not throw exception');
}
// global throw setting is ignored
try {
$response->toArray(true);
$this->fail('should throw exception');
} catch (\Exception $e) {
$this->assertSame('HTTP 403 returned for "https://example.com/foo".', $e->getMessage());
}
try {
$response->getContent(true);
$this->fail('should throw exception');
} catch (\Exception $e) {
$this->assertSame('HTTP 403 returned for "https://example.com/foo".', $e->getMessage());
}
}
}
================================================
FILE: tests/Kernel/HttpClient/RetryableClientTest.php
================================================
500]),
new MockResponse('', ['http_code' => 500]),
new MockResponse('', ['http_code' => 500]),
new MockResponse('', ['http_code' => 200]),
]);
$this->assertInstanceOf(HttpClientInterface::class, $client->getClient());
$this->assertNotInstanceOf(RetryableHttpClient::class, $client->getClient());
// No retry
$response = $client->request('GET', 'http://foo.com');
$this->assertSame(500, $response->getStatusCode());
// Retry
$client->retry(['delay' => 10]);
$this->assertInstanceOf(RetryableHttpClient::class, $client->getClient());
// default retry 3 times
$response = $client->request('GET', 'http://foo.com');
$this->assertSame(200, $response->getStatusCode());
}
public function test_it_can_retry_with_custom_strategy()
{
$client = new DummyClientForRetryableClientTest([
new MockResponse('', ['http_code' => 500]),
new MockResponse('', ['http_code' => 500]),
new MockResponse('', ['http_code' => 500]),
new MockResponse('', ['http_code' => 200]),
]);
$response = $client->request('GET', 'https://easywechat.com');
$this->assertNull($response->getInfo('ret'));
$client->retryUsing(new class extends GenericRetryStrategy
{
public function __construct(
array $statusCodes = self::DEFAULT_RETRY_STATUS_CODES,
int $delayMs = 1000,
float $multiplier = 2.0,
int $maxDelayMs = 0,
float $jitter = 0.1
) {
parent::__construct($statusCodes, 10, $multiplier, $maxDelayMs, $jitter);
}
}, maxRetries: 2);
$this->expectException(ServerException::class);
$client->request('GET', 'http://foo.com');
}
}
class DummyClientForRetryableClientTest implements HttpClientInterface
{
use DecoratorTrait;
use RetryableClient;
public function __construct($response = null)
{
$this->client = new MockHttpClient($response);
}
public function getClient(): HttpClientInterface
{
return $this->client;
}
public function __call(string $name, array $arguments)
{
return $this->client->{$name}(...$arguments);
}
}
================================================
FILE: tests/Kernel/MessageTest.php
================================================
1]);
$this->assertSame($message->one, 1);
$this->assertSame($message['one'], 1);
}
public function test_message_can_be_encode_as_json()
{
$message = new Message(['one' => 1]);
$this->assertSame(json_encode($message), '{"one":1}');
}
}
================================================
FILE: tests/Kernel/ServerResponseTest.php
================================================
'bar'], 'foo'));
$responseLines = explode("\r\n", $response);
$this->assertEquals('HTTP/1.1 200 OK', $responseLines[0]);
$this->assertEquals('X-Foo: bar', $responseLines[1]);
$this->assertEquals('foo', $responseLines[3]);
}
public function test_to_string_without_headers()
{
$response = ServerResponse::make(new Response(200, [], 'foo'));
$responseLines = explode("\r\n", $response);
$this->assertEquals('HTTP/1.1 200 OK', $responseLines[0]);
$this->assertEquals('foo', $responseLines[2]);
}
public function test_it_can_send_response()
{
\ob_start();
$response = ServerResponse::make(new Response(200, ['X-Foo' => 'bar'], 'foo'));
$response->sendContent();
$contents = \ob_get_contents();
\ob_end_clean();
$this->assertSame('foo', $contents);
}
}
================================================
FILE: tests/Kernel/Support/AesCbcTest.php
================================================
assertSame($ciphertext, AesCbc::encrypt($plaintext, $key, $iv));
// decrypt
$json = \json_decode(AesCbc::decrypt($ciphertext, $key, $iv), true);
$this->assertSame('oGZUI0egBJY1zhBYw2KhdUfwVJJE', $json['openId']);
}
}
================================================
FILE: tests/Kernel/Support/AesEcbTest.php
================================================
';
$ciphertext = 'm+cqC5OWNek/jGSeSFjMwxqoQmt9x/XQEPRosjYHR2a6kosdkuS2hFlt1QP/ykVOCm6PXnC0tOc7gsPzP3aG4Hhn7wJwJAvMhSUJhOAOlnXtHupbyiwb9vNgqAwcSr04U1yoI8UemDCz+TnIsbldurZh6UKtDqSutp/KiutgJ/9crss+fh9hy9UcBKO60JkJgka79q6lkQoOKZh3kIHrFEZGFKcvCOJzx/heVtz8AHGoB/IuNV4Mh280FZM1TTe8V54eXgqHNAOdJCoYQuKu34tepA+a4sjCcPOmNU5wLCjEFQ/+w7Ad8U2i3bfaA713DPk5qV8IVSB1cMGZj+zZBGPT4OWBg0vZD4ZJCydf93e95CbxV7FuSPiFnZwjvsHBCA7DNGoAfSx72p5ZBcyCTFV9y4O9xTukHUmJNI8XK+JhR5Imz9u5422lfN5FcM6g4WdLDTVO/DiN4chaTUk9uqEiMqD2Bn3+ZWe/R91YDW8koG3qd7m/9y7sckptNQWU9fi+zk/AbCLHETiUIj4dtFxsZRTBUFIEmSl2ebcPEdowOLzjUe2uW/Qr8dDwFuWGsSYawYnsbsxliNc5DthzhcdB9MDkOab6hckUIC7639s6DKFP44Olgjc+tt5EfDpNxK0rHh4rhlCz9h5ZhzI7CVqJRx5pCLEBaJKntPeF9IWfj92VYMY7o8TesmqhiDWnGVGSK8vXDsQMAWIhHi2STvdVAZkaOTzF+cxVJsUgy2zVlGhNzlqjQZmLoXZ/Kiid7cfUQvg/Bqw4We6KRrAfTHplwjbghjVzqWsgJv8KI3cYjFJEtTy19a0z3yBrcthtjszmBEUyUG/d4O0DzGEG+JNB4VsMz/jWUJ2d2uJmpyvngyt5RkafRH4mCHWkNTPz5UCBZtJbvFzQ/VB/X077Apwgk7lfgULu1uVF9N108kRKQcrqoGEH/oZ6lo0wIXbITx+7lr91eMvu4JgGPSQW4MKbluSa28iwkE5YcnQbYd0=';
// encrypt
$this->assertSame($ciphertext, AesEcb::encrypt($plaintext, $key));
// decrypt
$xml = Xml::parse(AesEcb::decrypt($ciphertext, $key));
$this->assertSame('123', $xml['out_refund_no']);
}
}
================================================
FILE: tests/Kernel/Support/AesGcmTest.php
================================================
assertSame($ciphertext, AesGcm::encrypt($plaintext, $key, $nonce, $aad));
// decrypt
$json = \json_decode(AesGcm::decrypt($ciphertext, $key, $nonce, $aad), true);
$this->assertSame('1217752501201407033233368018', $json['transaction_id']);
}
}
================================================
FILE: tests/Kernel/Support/MessageParserTest.php
================================================
assertIsArray($result);
$this->assertSame('value', $result['key']);
$this->assertSame(123, $result['number']);
}
public function test_it_can_parse_json_with_whitespace()
{
$content = " \n\t {\"key\":\"value\"} \n ";
$result = MessageParser::parse($content);
$this->assertIsArray($result);
$this->assertSame('value', $result['key']);
}
public function test_it_falls_back_to_xml_when_json_decode_fails()
{
$content = 'value123';
$result = MessageParser::parse($content);
$this->assertIsArray($result);
$this->assertSame('value', $result['key']);
$this->assertSame('123', $result['number']);
}
public function test_it_falls_back_to_xml_when_json_is_not_array()
{
// JSON string (not an array) should fall back to XML
// Since it's not valid XML either, it should throw exception
$this->expectException(BadRequestException::class);
MessageParser::parse('"just a string"');
}
public function test_it_falls_back_to_xml_when_json_is_empty_array()
{
// Empty JSON array should fall back to XML
// Since empty array is not valid XML, it should throw exception
$this->expectException(BadRequestException::class);
MessageParser::parse('[]');
}
public function test_it_falls_back_to_xml_when_json_is_not_array_but_xml_is_valid()
{
// JSON that parses to a string (not array) should fall back to XML
// If the content is also valid XML, it should parse as XML
$content = 'value';
$result = MessageParser::parse($content);
$this->assertIsArray($result);
$this->assertSame('value', $result['key']);
}
public function test_it_throws_exception_when_both_json_and_xml_fail()
{
$this->expectException(BadRequestException::class);
$this->expectExceptionMessage('Failed to decode content. Content must be valid XML or JSON.');
MessageParser::parse('invalid content');
}
public function test_it_prioritizes_json_over_xml()
{
// Content that could be both valid JSON and valid XML
// JSON should be parsed first
$content = '{"xml":"value"}';
$result = MessageParser::parse($content);
$this->assertIsArray($result);
$this->assertSame('value', $result['xml']);
}
public function test_it_can_parse_xml_with_whitespace()
{
$content = " \n value \n ";
$result = MessageParser::parse($content);
$this->assertIsArray($result);
$this->assertSame('value', $result['key']);
}
}
================================================
FILE: tests/Kernel/Support/PrivateKeyTest.php
================================================
assertSame($contents, $key->getKey());
$this->assertSame('overtrue', $key->getPassphrase());
}
public function test_create_from_path()
{
$path = __DIR__.'/../../fixtures/private.key';
$contents = file_get_contents($path) ?: '';
$key = new PrivateKey($path, 'overtrue');
$this->assertSame($contents, $key->getKey());
$this->assertSame('overtrue', $key->getPassphrase());
}
}
================================================
FILE: tests/Kernel/Support/PublicKeyTest.php
================================================
assertSame($contents, \strval($cert));
}
public function test_create_from_path()
{
$path = __DIR__.'/../../fixtures/cert.pem';
$contents = file_get_contents($path) ?: '';
$cert = new PublicKey($path);
$this->assertSame($contents, \strval($cert));
}
}
================================================
FILE: tests/Kernel/Support/UserAgentTest.php
================================================
assertSame(
\sprintf(
'easywechat-sdk/%s OS/%s curl/%s custom-part custom-part2',
InstalledVersions::getVersion('w7corp/easywechat'),
php_uname('s').'/'.php_uname('r'),
\curl_version()['version']
),
UserAgent::create(['custom-part', 'custom-part2'])
);
}
}
================================================
FILE: tests/Kernel/Traits/DecryptJsonMessageTest.php
================================================
'wx5823bf96d3bd56c7',
'FromUserName' => 'mycreate',
'CreateTime' => '1409659813',
'MsgType' => 'text',
'Content' => 'hello',
'MsgId' => '4561255354251345929',
], JSON_UNESCAPED_UNICODE);
$this->assertIsString($plaintext);
$encryptor = new Encryptor('wx5823bf96d3bd56c7', 'QDG6eK', 'jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C');
$encrypted = $encryptor->encryptAsArray(
plaintext: $plaintext,
nonce: '1372623149',
timestamp: '1409659813'
);
$body = json_encode([
'ToUserName' => 'wx5823bf96d3bd56c7',
'Encrypt' => $encrypted['ciphertext'],
'AgentID' => '218',
], JSON_UNESCAPED_UNICODE);
$this->assertIsString($body);
$message = JsonDummyMessage::createFromRequest(new ServerRequest('POST', 'http://easywechat.com/server', [], $body));
$message = $this->decryptMessage(
message: $message,
encryptor: $encryptor,
signature: $encrypted['signature'],
timestamp: $encrypted['timestamp'],
nonce: $encrypted['nonce']
);
$this->assertSame([
'ToUserName' => 'wx5823bf96d3bd56c7',
'Encrypt' => $encrypted['ciphertext'],
'AgentID' => '218',
'FromUserName' => 'mycreate',
'CreateTime' => '1409659813',
'MsgType' => 'text',
'Content' => 'hello',
'MsgId' => '4561255354251345929',
], $message->toArray());
}
}
class JsonDummyMessage extends Message
{
}
================================================
FILE: tests/Kernel/Traits/DecryptXmlMessageTest.php
================================================
';
$message = DummyMessage::createFromRequest(new ServerRequest('POST', 'http://easywechat.com/server', [], $body));
$encryptor = new Encryptor('wx5823bf96d3bd56c7', 'QDG6eK', 'jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C');
$message = $this->decryptMessage($message, $encryptor, '477715d11cdb4164915debcba66cb864d751f3e6', '1409659813', '1372623149');
$this->assertSame([
'ToUserName' => 'wx5823bf96d3bd56c7',
'Encrypt' => 'RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==',
'AgentID' => '218',
'FromUserName' => 'mycreate',
'CreateTime' => '1409659813',
'MsgType' => 'text',
'Content' => 'hello',
'MsgId' => '4561255354251345929',
], $message->toArray());
}
}
class DummyMessage extends Message
{
}
================================================
FILE: tests/Kernel/Traits/InteractWithCacheTest.php
================================================
assertInstanceOf(CacheInterface::class, $app->getCache());
$this->assertSame($app->getCache(), $app->getCache());
// set
$cache = \Mockery::mock(Psr16Cache::class);
$app->setCache($cache);
$this->assertSame($cache, $app->getCache());
}
}
class DummyClassForInteractWithCacheTest
{
use InteractWithCache;
}
================================================
FILE: tests/Kernel/Traits/InteractWithClientTest.php
================================================
assertInstanceOf(AccessTokenAwareClient::class, $app->getClient());
$this->assertSame($app->getClient(), $app->getClient());
// set
$client = new AccessTokenAwareClient;
$app->setClient($client);
$this->assertSame($client, $app->getClient());
}
}
class DummyClassForInteractWithClientTest
{
use InteractWithClient;
public function createClient(): AccessTokenAwareClient
{
return new AccessTokenAwareClient;
}
}
================================================
FILE: tests/Kernel/Traits/InteractWithConfigTest.php
================================================
assertInstanceOf(ConfigInterface::class, $app->getConfig());
$this->assertSame($app->getConfig(), $app->getConfig());
// set
$config = \Mockery::mock(ConfigInterface::class);
$app->setConfig($config);
$this->assertSame($config, $app->getConfig());
}
}
class DummyClassForInteractWithConfigTest
{
use InteractWithConfig;
}
================================================
FILE: tests/Kernel/Traits/InteractWithHandlersTest.php
================================================
with([$c, 'hello']);
$this->assertCount(1, $m->getHandlers());
$this->assertSame('hello', $m->handle('result'));
// remove
$m->withoutHandler([$c, 'hello']);
$ci = new class
{
public function __invoke()
{
return 'hello invoke';
}
};
$m->with($ci);
$this->assertCount(1, $m->getHandlers());
$this->assertSame('hello invoke', $m->handle('result'));
// remove
$m->withoutHandler($ci);
$this->assertCount(0, $m->getHandlers());
$this->assertSame('result', $m->handle('result'));
}
/**
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
*/
public function test_it_has_closure_handlers()
{
$m = \Mockery::mock(InteractWithHandlers::class);
$h = fn () => 'hello';
$m->with($h);
$this->assertCount(1, $m->getHandlers());
$this->assertSame('hello', $m->handle('result'));
// remove
$m->withoutHandler($h);
$this->assertCount(0, $m->getHandlers());
$this->assertSame('result', $m->handle('result'));
}
/**
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
*/
public function test_it_has_class_based_handlers()
{
$m = \Mockery::mock(InteractWithHandlers::class);
$m->with(DummyClassBasedHandler::class);
$this->assertCount(1, $m->getHandlers());
$this->assertSame('hello', $m->handle('result'));
// remove
$m->withoutHandler(DummyClassBasedHandler::class);
$this->assertCount(0, $m->getHandlers());
$this->assertSame('result', $m->handle('result'));
}
/**
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
*/
public function test_it_will_run_by_sort()
{
$m = \Mockery::mock(InteractWithHandlers::class);
$h1 = function ($payload, $next) {
return 'h1'.$next($payload);
};
$h2 = function ($payload, $next) {
return 'h2'.$next($payload);
};
$h3 = function ($payload, $next) {
return 'h3'.$next($payload);
};
$h4 = function ($payload, $next) {
return 'h4';
};
$m->with($h1);
$m->with($h2);
$m->with($h3);
$m->with($h4);
$this->assertSame('h1h2h3h4', $m->handle('success'));
}
/**
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
*/
public function test_it_can_push_with_conditions()
{
$m = \Mockery::mock(InteractWithHandlers::class);
$h1 = fn () => 'handler1';
$h2 = fn () => 'handler2';
$h3 = fn () => 'handler3';
$h4 = fn () => 'handler4';
$m->when(fn () => false, $h1);
$m->when(fn () => true, $h2);
$m->when('bool-value-true', $h3);
$m->when(fn () => 0, $h4);
$this->assertCount(2, $m->getHandlers());
$this->assertFalse($m->has($h1));
$this->assertTrue($m->has($h2));
$this->assertTrue($m->has($h3));
$this->assertFalse($m->has($h4));
}
/**
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
*/
public function test_it_can_handle_with_chain_handles()
{
$m = \Mockery::mock(InteractWithHandlers::class);
$h1 = function ($payload, $next) {
return $next($payload);
};
$h2 = function ($payload, $next) {
return $next($payload);
};
$h3 = function ($payload, $next) {
return 'final result';
};
$h4 = function ($payload, $next) {
return $next($payload);
};
// h4 will not run
$m->with($h1);
$m->with($h2);
$m->with($h3);
$m->with($h4);
$this->assertSame('final result', $m->handle('SUCCESS'));
$m->without($h3);
$this->assertSame('SUCCESS', $m->handle('SUCCESS'));
}
/**
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
*/
public function test_it_can_handle_with_default_value()
{
$m = \Mockery::mock(InteractWithHandlers::class);
$h1 = function ($payload, $next) {
return $next($payload);
};
$h2 = function ($payload, $next) {
return $next($payload);
};
$h3 = function ($payload, $next) {
return null;
};
$h4 = function ($payload, $next) {
return 'hello';
};
$m->with($h1);
$m->with($h2);
$m->with($h3);
$m->with($h4);
// null
$this->assertSame('default value', $m->handle('default value'));
// closure
$h5 = fn () => 'h5';
$this->assertSame('h5', $m->handle($h5));
// return $h4
$m->without($h3);
$this->assertSame('hello', $m->handle('default value'));
}
public function test_it_can_prepend_handlers()
{
$m = \Mockery::mock(InteractWithHandlers::class);
$h1 = function ($payload, $next) {
return 'h1'.$next($payload);
};
$h2 = function ($payload, $next) {
return 'h2'.$next($payload);
};
$h3 = function ($payload, $next) {
return 'h3'.$next($payload);
};
$h4 = function ($payload, $next) {
return 'h4';
};
$m->with($h1);
$m->with($h4);
$this->assertSame('h1h4', $m->handle('success'));
$m->prepend($h2);
$this->assertSame('h2h1h4', $m->handle('success'));
$m->prepend($h3);
$this->assertSame('h3h2h1h4', $m->handle('success'));
}
}
class DummyClassBasedHandler
{
public function __invoke($payload, \Closure $next)
{
return 'hello';
}
}
================================================
FILE: tests/Kernel/Traits/InteractWithHttpClientTest.php
================================================
assertInstanceOf(HttpClientInterface::class, $app->getHttpClient());
$this->assertSame($app->getHttpClient(), $app->getHttpClient());
// set
$client = new CurlHttpClient;
$app->setHttpClient($client);
$this->assertSame($client, $app->getHttpClient());
}
}
class DummyClassForInteractWithHttpClientTest
{
use InteractWithHttpClient;
}
================================================
FILE: tests/Kernel/Traits/InteractWithServerRequestTest.php
================================================
assertInstanceOf(ServerRequestInterface::class, $app->getRequest());
$this->assertSame($app->getRequest(), $app->getRequest());
// set
$request = \Mockery::mock(ServerRequestInterface::class);
$app->setRequest($request);
$this->assertSame($request, $app->getRequest());
}
public function test_it_can_set_request_from_symfony_request()
{
$app = new DummyClassForInteractWithServerRequestTest;
$request = \Symfony\Component\HttpFoundation\Request::create('/foo', 'GET');
$app->setRequestFromSymfonyRequest($request);
$this->assertInstanceOf(ServerRequestInterface::class, $app->getRequest());
$this->assertSame($request->getUri(), \strval($app->getRequest()->getUri()));
$this->assertSame($request->getMethod(), $app->getRequest()->getMethod());
}
}
class DummyClassForInteractWithServerRequestTest
{
use InteractWithServerRequest;
}
================================================
FILE: tests/Kernel/Traits/RespondXmlMessageTest.php
================================================
transformToReply('', \Mockery::mock(Message::class));
$this->assertSame(200, $response->getStatusCode());
$this->assertSame('success', \strval($response->getBody()));
}
public function test_it_will_handle_array_response()
{
$response = $this->transformToReply([
'MsgType' => 'text',
'Content' => 'Hello',
], \Mockery::mock(Message::class));
$this->assertSame(200, $response->getStatusCode());
$this->assertMatchesRegularExpression(
'~'
.'\d{10}'
.'text'
.'Hello'
.'~',
\strval($response->getBody())
);
}
public function test_it_will_handle_string_response()
{
$response = $this->transformToReply('Hello', \Mockery::mock(Message::class));
$this->assertSame(200, $response->getStatusCode());
$this->assertSame('application/xml', $response->getHeaderLine('content-type'));
$this->assertMatchesRegularExpression(
'~'
.'\d{10}'
.'text'
.'Hello'
.'~',
\strval($response->getBody())
);
}
public function test_it_will_throw_when_response_type_error()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid Response type "object".');
$this->transformToReply(new \stdClass, \Mockery::mock(Message::class));
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid Response type "boolean".');
$this->transformToReply(false, \Mockery::mock(Message::class));
}
}
================================================
FILE: tests/MiniApp/AccessTokenTest.php
================================================
assertStringStartsWith('mini_app.access_token', $accessToken->getKey());
}
}
================================================
FILE: tests/MiniApp/ApplicationTest.php
================================================
'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
]
);
$this->assertInstanceOf(ApplicationInterface::class, $app);
$this->assertInstanceOf(AccountInterface::class, $app->getAccount());
$this->assertSame($app->getAccount(), $app->getAccount());
// set
$account = new Account(appId: 'wx3cf0f39249000060', secret: 'mock-secret', token: 'mock-token');
$app->setAccount($account);
$this->assertSame($account, $app->getAccount());
}
public function test_get_and_set_encryptor()
{
$app = new Application(
[
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(Encryptor::class, $app->getEncryptor());
$this->assertSame($app->getEncryptor(), $app->getEncryptor());
// set
$encryptor = new Encryptor(appId: 'wx3cf0f39249000060', token: 'mock-token', aesKey: 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG');
$app->setEncryptor($encryptor);
$this->assertSame($encryptor, $app->getEncryptor());
}
public function test_get_and_set_server()
{
$app = new Application(
[
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(ServerInterface::class, $app->getServer());
$this->assertSame($app->getServer(), $app->getServer());
// set
$server = new Server(\Mockery::mock(ServerRequestInterface::class));
$app->setServer($server);
$this->assertSame($server, $app->getServer());
}
public function test_get_and_set_access_token()
{
$app = new Application(
[
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(AccessTokenInterface::class, $app->getAccessToken());
// set
$accessToken = new AccessToken('wx3cf0f39249000060', 'mock-secret');
$app->setAccessToken($accessToken);
$this->assertSame($accessToken, $app->getAccessToken());
}
public function test_get_utils()
{
$app = new Application(
[
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(Utils::class, $app->getUtils());
}
}
================================================
FILE: tests/MiniApp/DecryptorTest.php
================================================
assertSame([
'openId' => 'oGZUI0egBJY1zhBYw2KhdUfwVJJE',
'nickName' => 'Band',
'gender' => 1,
'language' => 'zh_CN',
'city' => 'Guangzhou',
'province' => 'Guangdong',
'country' => 'CN',
'avatarUrl' => 'http://wx.qlogo.cn/mmopen/vi_32/aSKcBBPpibyKNicHNTMM0qJVh8Kjgiak2AHWr8MHM4WgMEm7GFhsf8OYrySdbvAMvTsw3mo8ibKicsnfN5pRjl1p8HQ/0',
'unionId' => 'ocMvos6NjeKLIBqg5Mr9QjxrP1FA',
'watermark' => [
'timestamp' => 1477314187,
'appid' => 'wx4f4bc4dec97d474b',
],
], $decrypted);
}
public function test_it_will_throw_exception_when_payload_is_invalid()
{
$encryptedData = 'aaaaCiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZMQmRzooG2xrDcvSnxIMXFufNstNGTyaGS9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+3hVbJSRgv+4lGOETKUQz6OYStslQ142d
NCuabNPGBzlooOmB231qMM85d2/fV6ChevvXvQP8Hkue1poOFtnEtpyxVLW1zAo6/1Xx1COxFvrc2d7UL/lmHInNlxuacJXwu0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn
/Hz7saL8xz+W//FRAUid1OksQaQx4CMs8LOddcQhULW4ucetDf96JcR3g0gfRK4PC7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns
/8wR2SiRS7MNACwTyrGvt9ts8p12PKFdlqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYVoKlaRv85IfVunYzO0IKXsyl7JCUjCpoG20f0a04COwfneQAGGwd5oa+T8yO5hzuyDb/XcxxmK01EpqOyuxINew==';
try {
Decryptor::decrypt('tiihtNczf5v6AKRyjwEUhQ==', 'r7BXXKkLb8qrSNn05n0qiA==', $encryptedData);
} catch (\Throwable $e) {
$this->assertInstanceOf(DecryptException::class, $e);
$this->assertStringStartsWith('The given payload is invalid:', $e->getMessage());
}
}
}
================================================
FILE: tests/MiniApp/UtilsTest.php
================================================
'o6_bmjrPTlm6_2sgVt7hMZOPxxxx',
'session_key' => 'tiihtNczf5v6AKRyjwExxxx=',
'unionid' => 'o6_bmasdasdsad6_2sgVt7hMZOxxxx',
'errcode' => 0,
'errmsg' => 'ok',
];
$httpClient = new MockHttpClient(new MockResponse(json_encode($response)));
$app = new Application([
'app_id' => 'mock-appid',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes_key',
]);
$app->setHttpClient($httpClient);
$utils = new Utils($app);
$result = $utils->codeToSession('mock-js-code');
$this->assertSame($response, $result);
}
public function test_decrypt_session()
{
$sessionKey = 'tiihtNczf5v6AKRyjwEUhQ==';
$encryptedData = 'CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZM
QmRzooG2xrDcvSnxIMXFufNstNGTyaGS
9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+
3hVbJSRgv+4lGOETKUQz6OYStslQ142d
NCuabNPGBzlooOmB231qMM85d2/fV6Ch
evvXvQP8Hkue1poOFtnEtpyxVLW1zAo6
/1Xx1COxFvrc2d7UL/lmHInNlxuacJXw
u0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn
/Hz7saL8xz+W//FRAUid1OksQaQx4CMs
8LOddcQhULW4ucetDf96JcR3g0gfRK4P
C7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB
6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns
/8wR2SiRS7MNACwTyrGvt9ts8p12PKFd
lqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYV
oKlaRv85IfVunYzO0IKXsyl7JCUjCpoG
20f0a04COwfneQAGGwd5oa+T8yO5hzuy
Db/XcxxmK01EpqOyuxINew==';
$iv = 'r7BXXKkLb8qrSNn05n0qiA==';
$app = new Application([
'app_id' => 'mock-appid',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes_key',
]);
$utils = new Utils($app);
$this->assertSame([
'openId' => 'oGZUI0egBJY1zhBYw2KhdUfwVJJE',
'nickName' => 'Band',
'gender' => 1,
'language' => 'zh_CN',
'city' => 'Guangzhou',
'province' => 'Guangdong',
'country' => 'CN',
'avatarUrl' => 'http://wx.qlogo.cn/mmopen/vi_32/aSKcBBPpibyKNicHNTMM0qJVh8Kjgiak2AHWr8MHM4WgMEm7GFhsf8OYrySdbvAMvTsw3mo8ibKicsnfN5pRjl1p8HQ/0',
'unionId' => 'ocMvos6NjeKLIBqg5Mr9QjxrP1FA',
'watermark' => [
'timestamp' => 1477314187,
'appid' => 'wx4f4bc4dec97d474b',
],
], $utils->decryptSession($sessionKey, $iv, $encryptedData));
}
public function test_get_phone_number()
{
$response = [
'errcode' => 0,
'errmsg' => 'ok',
'phone_info' => [
'phoneNumber' => '13800138000',
'purePhoneNumber' => '13800138000',
'countryCode' => '86',
'watermark' => [
'timestamp' => 1637744274,
'appid' => 'xxxx',
],
],
];
$httpClient = new MockHttpClient([
new MockResponse(json_encode($response)),
]);
$cache = \Mockery::mock(CacheInterface::class);
$cache->allows()->get(\Mockery::any())->andReturn('mock-access-token');
$app = new Application([
'app_id' => 'mock-appid',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes_key',
]);
$app->setHttpClient($httpClient);
$app->setCache($cache);
$utils = new Utils($app);
$result = $utils->getPhoneNumber('mock-phone-code');
$this->assertSame($response, $result);
}
public function test_get_phone_number_with_error()
{
$this->expectException(\EasyWeChat\Kernel\Exceptions\HttpException::class);
$this->expectExceptionMessage('getPhoneNumber error:');
$errorResponse = [
'errcode' => 40029,
'errmsg' => 'invalid code',
];
$httpClient = new MockHttpClient([
new MockResponse(json_encode($errorResponse)),
]);
$cache = \Mockery::mock(CacheInterface::class);
$cache->allows()->get(\Mockery::any())->andReturn('mock-access-token');
$app = new Application([
'app_id' => 'mock-appid',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes_key',
]);
$app->setHttpClient($httpClient);
$app->setCache($cache);
$utils = new Utils($app);
$utils->getPhoneNumber('invalid-code');
}
}
================================================
FILE: tests/OfficialAccount/AccessTokenTest.php
================================================
'mock_access_token',
'expires_in' => '1500',
];
$response->allows()->toArray(false)->andReturn($result);
$config = [
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
];
$options = [
'query' => [
'grant_type' => 'client_credential',
'appid' => $config['app_id'],
'secret' => $config['secret'],
],
];
$httpClient->allows()->request('GET', 'cgi-bin/token', $options)->andReturn($response);
$accessToken = new AccessToken($config['app_id'], $config['secret'], null, null, $httpClient);
$this->assertSame($result['access_token'], $accessToken->getToken());
}
public function test_get_token_from_cache()
{
$cache = \Mockery::mock(CacheInterface::class);
$key = 'mock-cache-key';
$result = [
'access_token' => 'mock_access_token',
'expires_in' => '1500',
];
$cache->expects()->get($key)->andReturn($result['access_token']);
$config = [
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
];
$accessToken = new AccessToken($config['app_id'], $config['secret'], $key, $cache);
$this->assertSame($result['access_token'], $accessToken->getToken());
}
public function test_set_key()
{
$config = [
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
];
$key = 'mock-cache-key';
$accessToken = new AccessToken($config['app_id'], $config['secret'], $key);
$this->assertSame($key, $accessToken->getKey());
}
}
================================================
FILE: tests/OfficialAccount/AccountTest.php
================================================
'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
]
);
$this->assertInstanceOf(AccountInterface::class, $app->getAccount());
}
/**
* @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
*/
public function test_set_account_to_application()
{
$accountConfig = [
'app_id' => 'wx3cf0f39249111111',
'secret' => 'mock-account-secret',
'token' => 'mock-account-token',
'aes_key' => 'mock-account-aes-key',
];
$account = new Account(
appId: $accountConfig['app_id'],
secret: $accountConfig['secret'],
token: $accountConfig['token'],
aesKey: $accountConfig['aes_key']
);
$applicationConfig = [
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
];
$app = new Application(
[
'app_id' => $applicationConfig['app_id'],
'secret' => $applicationConfig['secret'],
'token' => $applicationConfig['token'],
]
);
$this->assertInstanceOf(AccountInterface::class, $app->getAccount());
$this->assertSame($applicationConfig['app_id'], $app->getAccount()->getAppId());
$app->setAccount($account);
$this->assertNotSame($applicationConfig['app_id'], $app->getAccount()->getAppId());
$this->assertSame($accountConfig['app_id'], $app->getAccount()->getAppId());
}
public function test_get_account_app_id()
{
$config = [
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes-key',
];
$account = new Account(
appId: $config['app_id'],
secret: $config['secret'],
token: $config['token'],
aesKey: $config['aes_key']
);
$this->assertSame($config['app_id'], $account->getAppId());
}
public function test_get_account_secret()
{
$config = [
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes-key',
];
$account = new Account(
appId: $config['app_id'],
secret: $config['secret'],
token: $config['token'],
aesKey: $config['aes_key']
);
$this->assertSame($config['secret'], $account->getSecret());
}
public function test_get_account_token()
{
$config = [
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes-key',
];
$account = new Account(
appId: $config['app_id'],
secret: $config['secret'],
token: $config['token'],
aesKey: $config['aes_key']
);
$this->assertSame($config['token'], $account->getToken());
}
public function test_get_account_aes_key()
{
$config = [
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes-key',
];
$account = new Account(
appId: $config['app_id'],
secret: $config['secret'],
token: $config['token'],
aesKey: $config['aes_key']
);
$this->assertSame($config['aes_key'], $account->getAesKey());
}
}
================================================
FILE: tests/OfficialAccount/ApplicationTest.php
================================================
'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
]
);
$this->assertInstanceOf(ApplicationInterface::class, $app);
$this->assertInstanceOf(AccountInterface::class, $app->getAccount());
$this->assertSame($app->getAccount(), $app->getAccount());
// set
$account = new Account(appId: 'wx3cf0f39249000060', secret: 'mock-secret', token: 'mock-token');
$app->setAccount($account);
$this->assertSame($account, $app->getAccount());
}
public function test_get_and_set_encryptor()
{
$app = new Application(
[
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(Encryptor::class, $app->getEncryptor());
$this->assertSame($app->getEncryptor(), $app->getEncryptor());
// set
$encryptor = new Encryptor(appId: 'wx3cf0f39249000060', token: 'mock-token', aesKey: 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG');
$app->setEncryptor($encryptor);
$this->assertSame($encryptor, $app->getEncryptor());
}
public function test_get_and_set_server()
{
$app = new Application(
[
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(ServerInterface::class, $app->getServer());
$this->assertSame($app->getServer(), $app->getServer());
// set
$server = new Server(\Mockery::mock(ServerRequestInterface::class));
$app->setServer($server);
$this->assertSame($server, $app->getServer());
}
public function test_get_and_set_access_token()
{
$app = new Application(
[
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(AccessTokenInterface::class, $app->getAccessToken());
// set
$accessToken = new AccessToken('wx3cf0f39249000060', 'mock-secret');
$app->setAccessToken($accessToken);
$this->assertSame($accessToken, $app->getAccessToken());
}
// https://github.com/w7corp/easywechat/issues/2743
public function test_get_client_without_http_config()
{
$app = new Application(
[
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(AccessTokenAwareClient::class, $app->getClient());
$app = new Application(
[
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
'http' => null,
]
);
// no exception
$this->assertInstanceOf(AccessTokenAwareClient::class, $app->getClient());
}
public function test_get_and_set_ticket()
{
$app = new Application(
[
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(JsApiTicket::class, $app->getTicket());
// set
$ticket = new JsApiTicket('wx3cf0f39249000060', 'mock-secret', 'mock-token', $app->getCache(), $app->getClient());
$app->setTicket($ticket);
$this->assertSame($ticket, $app->getTicket());
}
public function test_get_utils()
{
$app = new Application(
[
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(Utils::class, $app->getUtils());
}
}
================================================
FILE: tests/OfficialAccount/ConfigTest.php
================================================
'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
]
);
$this->assertInstanceOf(ConfigInterface::class, $app->getConfig());
}
/**
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
* @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
*/
public function test_set_config_to_application()
{
$config = [
'app_id' => 'wx3cf0f39249111111',
'secret' => 'mock-account-secret',
'token' => 'mock-account-token',
'aes_key' => 'mock-account-aes-key',
];
$config = new Config($config);
$applicationConfig = [
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
];
$app = new Application(
[
'app_id' => $applicationConfig['app_id'],
'secret' => $applicationConfig['secret'],
'token' => $applicationConfig['token'],
]
);
$this->assertInstanceOf(ConfigInterface::class, $app->getConfig());
$this->assertSame($applicationConfig['app_id'], $app->getConfig()->get('app_id'));
$this->assertSame(false, $app->getConfig()->has('aes_key'));
$app->setConfig($config);
$this->assertNotSame($applicationConfig['app_id'], $app->getConfig()->get('app_id'));
$this->assertSame($config['app_id'], $app->getConfig()->get('app_id'));
$this->assertSame(true, $app->getConfig()->has('aes_key'));
}
public function test_init_config_can_check_missing_keys()
{
$config = [
'secret' => 'mock-account-secret',
];
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(\sprintf('"%s" cannot be empty.', 'app_id'));
new Config($config);
}
}
================================================
FILE: tests/OfficialAccount/JsApiTicketTest.php
================================================
assertInstanceOf(AccessToken::class, $ticket);
$this->assertSame('official_account.jsapi_ticket.mock-appid', $ticket->getKey());
$ticket->setKey('mock-key');
$this->assertSame('mock-key', $ticket->getKey());
$ticket = new JsApiTicket('mock-appid', 'mock-secret', 'test-key');
$this->assertSame('test-key', $ticket->getKey());
}
public function test_get_ticket()
{
$cacheKey = 'official_account.jsapi_ticket.mock-appid';
$ticket = [
'ticket' => 'mock-ticket',
'expires_in' => 7200,
];
$response = \Mockery::mock(ResponseInterface::class);
$response->allows()->toArray(false)->andReturn($ticket);
$client = \Mockery::mock(HttpClientInterface::class);
$cache = \Mockery::mock(CacheInterface::class);
$cache->expects()->get($cacheKey)->andReturn($ticket['ticket']);
$jsApiTicket = new JsApiTicket('mock-appid', 'mock-secret', null, $cache, $client);
$this->assertSame($ticket['ticket'], $jsApiTicket->getTicket());
// 设为过期
$cache->expects()->get($cacheKey)->andReturn(false);
$cache->expects()->set($cacheKey, $ticket['ticket'], $ticket['expires_in'])->andReturn(true);
$client->allows()->request('GET', '/cgi-bin/ticket/getticket', ['query' => ['type' => 'jsapi']])
->andReturn($response);
$this->assertSame($ticket['ticket'], $jsApiTicket->getTicket());
}
public function test_config_signature()
{
$nonce = 'mock-nonce';
$timestamp = 1601234567;
$cacheKey = 'official_account.jsapi_ticket.mock-appid';
$cache = \Mockery::mock(CacheInterface::class);
$cache->expects()->get($cacheKey)->andReturn('mock-ticket');
$ticket = new JsApiTicket('mock-appid', 'mock-secret', null, $cache);
$result = $ticket->configSignature('https://www.easywechat.com/', $nonce, $timestamp);
$data = [
'url' => 'https://www.easywechat.com/',
'nonceStr' => 'mock-nonce',
'timestamp' => 1601234567,
'appId' => 'mock-appid',
'signature' => '22772d2fb393ab9f7f6a5a54168a566fbf1ab767',
];
$this->assertSame($data, $result);
}
}
================================================
FILE: tests/OfficialAccount/ServerTest.php
================================================
withQueryParams(['echostr' => 'abcdefghijklmn']);
$server = new Server($request);
$response = $server->serve();
$this->assertSame('abcdefghijklmn', \strval($response->getBody()));
}
public function test_it_will_response_success_without_handlers()
{
$body = '
1348831860
1234567890123456
';
$request = (new ServerRequest('POST', 'http://easywechat.com/server', [], $body));
$server = new Server($request);
$response = $server->serve();
$this->assertSame('success', \strval($response->getBody()));
}
public function test_it_will_respond_from_message_handlers()
{
$body = '
1348831860
1234567890123456
';
$request = (new ServerRequest('POST', 'http://easywechat.com/server', [], $body));
$server = new Server($request);
$response = $server
->addMessageListener(
'text',
function ($message) {
return 'hello';
}
)->addEventListener(
'subscribe',
function ($message) {
return 'world';
}
)->serve();
$response = Xml::parse(\strval($response->getBody()));
$this->assertSame('toUser', $response['FromUserName']);
$this->assertSame('fromUser', $response['ToUserName']);
$this->assertSame('text', $response['MsgType']);
$this->assertSame('hello', $response['Content']);
}
public function test_it_will_respond_from_event_handlers()
{
$body = '
123456789
';
$request = (new ServerRequest('POST', 'http://easywechat.com/server', [], $body));
$server = new Server($request);
$response = $server
->addMessageListener(
'text',
function ($message) {
return 'hello';
}
)->addEventListener(
'subscribe',
function ($message) {
return 'world';
}
)->serve();
$response = Xml::parse(\strval($response->getBody()));
$this->assertSame('toUser', $response['FromUserName']);
$this->assertSame('fromUser', $response['ToUserName']);
$this->assertSame('text', $response['MsgType']);
$this->assertSame('world', $response['Content']);
}
public function test_it_can_decrypt_json_mode_messages()
{
$plaintext = json_encode([
'ToUserName' => 'wx5823bf96d3bd56c7',
'FromUserName' => 'mycreate',
'CreateTime' => '1409659813',
'MsgType' => 'text',
'Content' => 'hello',
'MsgId' => '4561255354251345929',
], JSON_UNESCAPED_UNICODE);
$this->assertIsString($plaintext);
$encryptor = new Encryptor('wx5823bf96d3bd56c7', 'QDG6eK', 'jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C');
$encrypted = $encryptor->encryptAsArray(
plaintext: $plaintext,
nonce: '1372623149',
timestamp: '1409659813'
);
$body = json_encode([
'ToUserName' => 'wx5823bf96d3bd56c7',
'Encrypt' => $encrypted['ciphertext'],
], JSON_UNESCAPED_UNICODE);
$this->assertIsString($body);
$request = (new ServerRequest('POST', 'http://easywechat.com/server', [], $body))->withQueryParams([
'msg_signature' => $encrypted['signature'],
'timestamp' => $encrypted['timestamp'],
'nonce' => $encrypted['nonce'],
]);
$server = new Server($request, $encryptor);
$message = $server->getDecryptedMessage();
$this->assertSame('hello', $message->Content);
$this->assertSame('mycreate', $message->FromUserName);
}
}
================================================
FILE: tests/OfficialAccount/UtilsTest.php
================================================
['api1', 'api2'],
'openTagList' => ['openTag1', 'openTag2'],
'debug' => true,
'url' => 'https://www.easywechat.com/',
'nonceStr' => 'mock-nonce',
'timestamp' => 1601234567,
'appId' => 'mock-appid',
'signature' => '22772d2fb393ab9f7f6a5a54168a566fbf1ab767',
];
$signatue = [
'url' => 'https://www.easywechat.com/',
'nonceStr' => 'mock-nonce',
'timestamp' => 1601234567,
'appId' => 'mock-appid',
'signature' => '22772d2fb393ab9f7f6a5a54168a566fbf1ab767',
];
$ticket = \Mockery::mock(JsApiTicket::class);
$ticket->shouldReceive('configSignature')->andReturn($signatue);
$app = \Mockery::mock(Application::class);
$app->allows()->getTicket()->andReturn($ticket);
$utils = new Utils($app);
$result = $utils->buildJsSdkConfig('https://www.easywechat.com/', ['api1', 'api2'], ['openTag1', 'openTag2'], true);
$this->assertSame($data, $result);
}
}
================================================
FILE: tests/OpenPlatform/AccountTest.php
================================================
'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-account-aes-key',
]
);
$this->assertInstanceOf(AccountInterface::class, $app->getAccount());
}
/**
* @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
*/
public function test_set_account_to_application()
{
$accountConfig = [
'app_id' => 'wx3cf0f39249111111',
'secret' => 'mock-account-secret',
'token' => 'mock-account-token',
'aes_key' => 'mock-account-aes-key',
];
$account = new Account(
appId: $accountConfig['app_id'],
secret: $accountConfig['secret'],
token: $accountConfig['token'],
aesKey: $accountConfig['aes_key']
);
$config = [
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes_key',
];
$app = new Application($config);
$this->assertInstanceOf(AccountInterface::class, $app->getAccount());
$this->assertSame($config['app_id'], $app->getAccount()->getAppId());
$app->setAccount($account);
$this->assertNotSame($config['app_id'], $app->getAccount()->getAppId());
$this->assertSame($accountConfig['app_id'], $app->getAccount()->getAppId());
}
public function test_get_account_app_id()
{
$config = [
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes-key',
];
$account = new Account(
appId: $config['app_id'],
secret: $config['secret'],
token: $config['token'],
aesKey: $config['aes_key']
);
$this->assertSame($config['app_id'], $account->getAppId());
}
public function test_get_account_secret()
{
$config = [
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes-key',
];
$account = new Account(
appId: $config['app_id'],
secret: $config['secret'],
token: $config['token'],
aesKey: $config['aes_key']
);
$this->assertSame($config['secret'], $account->getSecret());
}
public function test_get_account_token()
{
$config = [
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes-key',
];
$account = new Account(
appId: $config['app_id'],
secret: $config['secret'],
token: $config['token'],
aesKey: $config['aes_key']
);
$this->assertSame($config['token'], $account->getToken());
}
public function test_get_account_aes_key()
{
$config = [
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes-key',
];
$account = new Account(
appId: $config['app_id'],
secret: $config['secret'],
token: $config['token'],
aesKey: $config['aes_key']
);
$this->assertSame($config['aes_key'], $account->getAesKey());
}
}
================================================
FILE: tests/OpenPlatform/ApplicationTest.php
================================================
'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes_key',
]);
$this->assertInstanceOf(ApplicationInterface::class, $app);
$this->assertInstanceOf(AccountInterface::class, $app->getAccount());
$this->assertSame($app->getAccount(), $app->getAccount());
// set
$account = new Account(appId: 'wx3cf0f39249000060', secret: 'mock-secret', token: 'mock-token', aesKey: 'mock-aes_key');
$app->setAccount($account);
$this->assertSame($account, $app->getAccount());
}
public function test_get_and_set_encryptor()
{
$app = new Application([
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]);
$this->assertInstanceOf(Encryptor::class, $app->getEncryptor());
$this->assertSame($app->getEncryptor(), $app->getEncryptor());
// set
$encryptor = new Encryptor(
appId: 'wx3cf0f39249000060',
token: 'mock-token',
aesKey: 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG'
);
$app->setEncryptor($encryptor);
$this->assertSame($encryptor, $app->getEncryptor());
}
public function test_get_and_set_server()
{
$app = new Application([
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]);
$this->assertInstanceOf(ServerInterface::class, $app->getServer());
$this->assertSame($app->getServer(), $app->getServer());
// set
$server = new Server(
encryptor: \Mockery::mock(Encryptor::class),
request: \Mockery::mock(ServerRequestInterface::class)
);
$app->setServer($server);
$this->assertSame($server, $app->getServer());
}
public function test_get_and_set_component_access_token()
{
$app = new Application([
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]);
$this->assertInstanceOf(AccessTokenInterface::class, $app->getAccessToken());
// set
$accessToken = new ComponentAccessToken('wx3cf0f39249000060', 'mock-secret', $app->getVerifyTicket());
$app->setComponentAccessToken($accessToken);
$this->assertSame($accessToken, $app->getAccessToken());
}
public function test_get_and_set_verify_ticket()
{
$app = new Application([
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]);
$this->assertInstanceOf(VerifyTicketInterface::class, $app->getVerifyTicket());
// set
$verifyTicket = new VerifyTicket('wx3cf0f39249000060');
$app->setVerifyTicket($verifyTicket);
$this->assertSame($verifyTicket, $app->getVerifyTicket());
}
public function test_get_authorization()
{
$app = new Application([
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]);
$verifyTicket = new VerifyTicket('wx3cf0f39249000060');
$verifyTicket->setTicket('mock-verify-ticket');
$app->setVerifyTicket($verifyTicket);
$tokenResponse = [
'component_access_token' => 'mock-access-token',
'expires_in' => 2700,
];
// token http client
$mockTokenResponse = new MockResponse(\json_encode($tokenResponse));
$tokenHttpClient = new MockHttpClient($mockTokenResponse, 'https://api.weixin.qq.com/');
$token = new ComponentAccessToken('wx3cf0f39249000060', 'mock-secret', $app->getVerifyTicket(), httpClient: $tokenHttpClient);
$app->setComponentAccessToken($token);
$mockResponse = new MockResponse(
\json_encode([
'authorization_info' => ['authorizer_appid' => 'mock-appid'],
]),
[
'http_code' => 201,
'response_headers' => ['Content-Type: application/json'],
]
);
$httpClient = new MockHttpClient($mockResponse, 'https://api.weixin.qq.com/');
$app->setHttpClient($httpClient);
$this->assertInstanceOf(Authorization::class, $app->getAuthorization('mock-auth-code'));
$this->assertSame('POST', $mockResponse->getRequestMethod());
$this->assertSame(
'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=mock-access-token',
$mockResponse->getRequestUrl()
);
$this->assertSame(
\json_encode([
'component_appid' => 'wx3cf0f39249000060',
'authorization_code' => 'mock-auth-code',
]),
$mockResponse->getRequestOptions()['body']
);
}
public function test_get_authorization_exception()
{
$app = new Application([
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]);
$verifyTicket = new VerifyTicket('wx3cf0f39249000060');
$verifyTicket->setTicket('mock-verify-ticket');
$app->setVerifyTicket($verifyTicket);
$tokenResponse = [
'component_access_token' => 'mock-access-token',
'expires_in' => 2700,
];
// token http client
$mockTokenResponse = new MockResponse(\json_encode($tokenResponse));
$tokenHttpClient = new MockHttpClient($mockTokenResponse, 'https://api.weixin.qq.com/');
$token = new ComponentAccessToken('wx3cf0f39249000060', 'mock-secret', $app->getVerifyTicket(), httpClient: $tokenHttpClient);
$app->setComponentAccessToken($token);
// exception
$mockResponse = new MockResponse(
\json_encode([
'error_code' => 100029,
]),
[
'http_code' => 201,
'response_headers' => ['Content-Type: application/json'],
]
);
$httpClient = new MockHttpClient($mockResponse, 'https://api.weixin.qq.com/');
$app->setHttpClient($httpClient);
$this->expectException(HttpException::class);
$this->expectExceptionMessage('Failed to get authorization_info: {"error_code":100029}');
$app->getAuthorization('mock-auth-code');
}
public function test_refresh_authorizer_token()
{
$app = new Application([
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]);
$verifyTicket = new VerifyTicket('wx3cf0f39249000060');
$verifyTicket->setTicket('mock-verify-ticket');
$app->setVerifyTicket($verifyTicket);
$tokenResponse = [
'component_access_token' => 'mock-access-token',
'expires_in' => 2700,
];
// token http client
$mockTokenResponse = new MockResponse(\json_encode($tokenResponse));
$tokenHttpClient = new MockHttpClient($mockTokenResponse, 'https://api.weixin.qq.com/');
$token = new ComponentAccessToken('wx3cf0f39249000060', 'mock-secret', $app->getVerifyTicket(), httpClient: $tokenHttpClient);
$app->setComponentAccessToken($token);
$mockResponse = new MockResponse(
\json_encode([
'authorizer_access_token' => 'mock-access-token',
]),
[
'http_code' => 201,
'response_headers' => ['Content-Type: application/json'],
]
);
$httpClient = new MockHttpClient($mockResponse, 'https://api.weixin.qq.com/');
$app->setHttpClient($httpClient);
$this->assertSame([
'authorizer_access_token' => 'mock-access-token',
], $app->refreshAuthorizerToken('mock-authorizer-appid', 'mock-refresh-token'));
$this->assertSame('POST', $mockResponse->getRequestMethod());
$this->assertSame(
'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=mock-access-token',
$mockResponse->getRequestUrl()
);
$this->assertSame(
\json_encode([
'component_appid' => 'wx3cf0f39249000060',
'authorizer_appid' => 'mock-authorizer-appid',
'authorizer_refresh_token' => 'mock-refresh-token',
]),
$mockResponse->getRequestOptions()['body']
);
}
public function test_refresh_authorizer_token_exception()
{
$app = new Application([
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]);
$verifyTicket = new VerifyTicket('wx3cf0f39249000060');
$verifyTicket->setTicket('mock-verify-ticket');
$app->setVerifyTicket($verifyTicket);
$tokenResponse = [
'component_access_token' => 'mock-access-token',
'expires_in' => 2700,
];
// token http client
$mockTokenResponse = new MockResponse(\json_encode($tokenResponse));
$tokenHttpClient = new MockHttpClient($mockTokenResponse, 'https://api.weixin.qq.com/');
$token = new ComponentAccessToken('wx3cf0f39249000060', 'mock-secret', $app->getVerifyTicket(), httpClient: $tokenHttpClient);
$app->setComponentAccessToken($token);
// exception
$mockResponse = new MockResponse(
\json_encode([
'error_code' => 100029,
]),
[
'http_code' => 201,
'response_headers' => ['Content-Type: application/json'],
]
);
$httpClient = new MockHttpClient($mockResponse, 'https://api.weixin.qq.com/');
$app->setHttpClient($httpClient);
$this->expectException(HttpException::class);
$this->expectExceptionMessage('Failed to get authorizer_access_token: {"error_code":100029}');
$app->refreshAuthorizerToken('mock-authorizer-appid', 'mock-refresh-token');
}
public function test_get_oauth()
{
$app = new Application([
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]);
$this->assertInstanceOf(WeChat::class, $app->getOAuth());
}
public function test_get_official_account()
{
$app = new Application([
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]);
$this->assertInstanceOf(
OfficialAccountApplication::class,
$app->getOfficialAccount(new AuthorizerAccessToken('mock-app-id', 'mock-access-token'), [
'secret' => 'mock-secret',
])
);
}
public function test_get_mini_app()
{
$app = new Application([
'app_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]);
$this->assertInstanceOf(
MiniAppApplication::class,
$app->getMiniApp(new AuthorizerAccessToken('mock-app-id', 'mock-access-token'), [
'secret' => 'mock-secret',
])
);
}
}
================================================
FILE: tests/OpenPlatform/AuthorizationTest.php
================================================
[
'authorizer_appid' => 'mock-app-id',
],
]);
$this->assertSame('mock-app-id', $authorization->getAppId());
}
public function test_get_access_token()
{
$authorization = new Authorization([
'authorization_info' => [
'authorizer_appid' => 'mock-app-id',
'authorizer_access_token' => 'mock-access-token',
],
]);
$this->assertInstanceOf(AuthorizerAccessToken::class, $authorization->getAccessToken());
$this->assertSame('mock-app-id', $authorization->getAccessToken()->getAppId());
$this->assertSame('mock-access-token', $authorization->getAccessToken()->getToken());
}
public function test_get_refresh_token()
{
$authorization = new Authorization([
'authorization_info' => [
'authorizer_appid' => 'mock-app-id',
'authorizer_refresh_token' => 'mock-refresh-token',
],
]);
$this->assertSame('mock-refresh-token', $authorization->getRefreshToken());
}
}
================================================
FILE: tests/OpenPlatform/AuthorizerAccessTokenTest.php
================================================
assertSame('mock-app-id', $token->getAppId());
$this->assertSame('mock-access-token', $token->getToken());
$this->assertSame('mock-access-token', \strval($token));
$this->assertSame([
'access_token' => 'mock-access-token',
], $token->toQuery());
}
}
================================================
FILE: tests/OpenPlatform/ComponentAccessTokenTest.php
================================================
assertSame('open_platform.component_access_token.mock-app-id', $token->getKey());
$token->setKey('custom-cache-key-for-app-id');
$this->assertSame('custom-cache-key-for-app-id', $token->getKey());
}
public function test_get_token_from_cache()
{
$cache = \Mockery::mock(CacheInterface::class);
$cache->expects()->get('open_platform.component_access_token.mock-app-id')->andReturns('mock-cached-access-token')->twice();
$token = new ComponentAccessToken('mock-app-id', 'mock-secret', \Mockery::mock(VerifyTicket::class), cache: $cache);
$this->assertSame('mock-cached-access-token', $token->getToken());
// to query
$this->assertSame([
'component_access_token' => 'mock-cached-access-token',
], $token->toQuery());
}
public function test_get_token_from_server()
{
$verifyTicket = \Mockery::mock(VerifyTicket::class);
$verifyTicket->expects()->getTicket()->andReturns('mock-verify-ticket');
$response = [
'component_access_token' => 'mock-access-token',
'expires_in' => 2700,
];
// cache client
$cache = \Mockery::mock(CacheInterface::class);
$cache->expects()->get('open_platform.component_access_token.mock-app-id')->andReturns(null)->once();
$cache->expects()->set('open_platform.component_access_token.mock-app-id', 'mock-access-token', 2700 - 100)->once();
// http client
$mockResponse = new MockResponse(\json_encode($response));
$httpClient = new MockHttpClient($mockResponse, 'https://api.weixin.qq.com/');
$token = new ComponentAccessToken('mock-app-id', 'mock-secret', $verifyTicket, httpClient: $httpClient, cache: $cache);
$this->assertSame('mock-access-token', $token->getToken());
$this->assertSame('POST', $mockResponse->getRequestMethod());
$this->assertSame('https://api.weixin.qq.com/cgi-bin/component/api_component_token', $mockResponse->getRequestUrl());
$this->assertSame(\json_encode([
'component_appid' => 'mock-app-id',
'component_appsecret' => 'mock-secret',
'component_verify_ticket' => 'mock-verify-ticket',
]), $mockResponse->getRequestOptions()['body']);
}
}
================================================
FILE: tests/OpenPlatform/ServerTest.php
================================================
第三方平台appid
1413192760
authorized
公众号appid
授权码
过期时间
预授权码
';
$encryptor = new Encryptor('wx5823bf96d3bd56c7', 'QDG6eK', 'jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C');
$request = $this->createEncryptedXmlMessageRequest($body, $encryptor);
$server = new Server(encryptor: $encryptor, request: $request);
$handleResult = null;
$response = $server->handleAuthorized(function ($message) use (&$handleResult) {
$handleResult = 'authorized-event-handled';
})->serve();
$this->assertSame('authorized-event-handled', $handleResult);
$this->assertSame('success', \strval($response->getBody()));
}
public function test_it_will_handle_unauthorized_event()
{
$body = '
第三方平台appid
1413192760
unauthorized
公众号appid
';
$encryptor = new Encryptor('wx5823bf96d3bd56c7', 'QDG6eK', 'jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C');
$request = $this->createEncryptedXmlMessageRequest($body, $encryptor);
$server = new Server(encryptor: $encryptor, request: $request);
$handleResult = null;
$response = $server->handleUnauthorized(function ($message) use (&$handleResult) {
$handleResult = 'unauthorized-event-handled';
})->serve();
$this->assertSame('unauthorized-event-handled', $handleResult);
$this->assertSame('success', \strval($response->getBody()));
}
public function test_it_will_handle_authorize_updated_event()
{
$body = '
第三方平台appid
1413192760
updateauthorized
公众号appid
授权码
过期时间
预授权码
';
$encryptor = new Encryptor('wx5823bf96d3bd56c7', 'QDG6eK', 'jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C');
$request = $this->createEncryptedXmlMessageRequest($body, $encryptor);
$server = new Server(encryptor: $encryptor, request: $request);
$handleResult = null;
$response = $server->handleAuthorizeUpdated(function ($message) use (&$handleResult) {
$handleResult = 'authorized-updated-event-handled';
})->serve();
$this->assertSame('authorized-updated-event-handled', $handleResult);
$this->assertSame('success', \strval($response->getBody()));
}
public function test_it_will_handle_verify_ticket_refresh_event()
{
$body = '
some_appid
1413192605
component_verify_ticket
some_verify_ticket
';
$encryptor = new Encryptor('wx5823bf96d3bd56c7', 'QDG6eK', 'jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C');
$request = $this->createEncryptedXmlMessageRequest($body, $encryptor);
$server = new Server(
encryptor: $encryptor,
request: $request
);
$handleResult = null;
$response = $server->handleVerifyTicketRefreshed(function ($message) use (&$handleResult) {
$handleResult = 'verify-ticket-refreshed-event-handled';
})->serve();
$this->assertSame('verify-ticket-refreshed-event-handled', $handleResult);
$this->assertSame('success', \strval($response->getBody()));
}
}
================================================
FILE: tests/Pay/ApplicationTest.php
================================================
101111111,
'secret_key' => 'mock-secret-key',
'private_key' => 'mock-private-key',
'certificate' => '/path/to/certificate.cert',
'certificate_serial_no' => 'MOCK-CERTIFICATE-SERIAL-NO',
]
);
$this->assertInstanceOf(Merchant::class, $app->getMerchant());
$this->assertSame($app->getMerchant(), $app->getMerchant());
}
public function test_get_client()
{
$app = new Application(
[
'mch_id' => 101111111,
'secret_key' => 'mock-secret-key',
'private_key' => 'mock-private-key',
'certificate' => '/path/to/certificate.cert',
'certificate_serial_no' => 'MOCK-CERTIFICATE-SERIAL-NO',
]
);
$this->assertInstanceOf(Client::class, $app->getClient());
$this->assertSame($app->getHttpClient(), $app->getHttpClient());
}
public function test_get_server()
{
$app = new Application(
[
'mch_id' => 101111111,
'secret_key' => 'mock-secret-key',
'private_key' => 'mock-private-key',
'certificate' => '/path/to/certificate.cert',
'certificate_serial_no' => 'MOCK-CERTIFICATE-SERIAL-NO',
]
);
$this->assertInstanceOf(Server::class, $app->getServer());
$this->assertSame($app->getServer(), $app->getServer());
}
public function test_get_and_set_validator()
{
$app = new Application(
[
'mch_id' => 101111111,
'secret_key' => 'mock-secret-key',
'private_key' => 'mock-private-key',
'certificate' => '/path/to/certificate.cert',
'certificate_serial_no' => 'MOCK-CERTIFICATE-SERIAL-NO',
]
);
$this->assertInstanceOf(Validator::class, $app->getValidator());
$this->assertSame($app->getValidator(), $app->getValidator());
$validator = \Mockery::mock(Validator::class);
$app->setValidator($validator);
$this->assertSame($validator, $app->getValidator());
}
}
================================================
FILE: tests/Pay/ClientTest.php
================================================
shouldReceive('createSignature')->andReturn('mock-signature');
$options = [
'headers' => [
'accept' => 'application/json',
],
];
$client->request('GET', 'https://api2.mch.weixin.qq.com/v3/certificates', $options);
$this->assertSame('GET', $client->getRequestMethod());
$this->assertSame('https://api2.mch.weixin.qq.com/v3/certificates', $client->getRequestUrl());
$this->assertSame('Content-Type: application/json', $client->getRequestOptions()['headers'][3]);
$this->assertSame('accept: application/json', $client->getRequestOptions()['headers'][0]);
}
public function test_v2_request_with_array()
{
$client = Client::mock();
$client->shouldReceive('createSignature')->never();
$client->shouldReceive('attachLegacySignature')->with([
'foo' => 'bar',
])->andReturn(['foo' => 'bar', 'sign' => 'mock-signature']);
$client->post('certificates', [
'body' => [
'foo' => 'bar',
],
]);
$this->assertSame('POST', $client->getRequestMethod());
$this->assertSame('https://api.mch.weixin.qq.com/certificates', $client->getRequestUrl());
$this->assertContains('Content-Type: text/xml', $client->getRequestOptions()['headers']);
$this->assertSame(Xml::build(['foo' => 'bar', 'sign' => 'mock-signature']), $client->getRequestOptions()['body']);
}
public function test_v2_request_without_body()
{
$client = Client::mock();
$client->shouldReceive('createSignature')->never();
$client->shouldReceive('attachLegacySignature')->with([
'foo' => 'bar',
])->andReturn(['foo' => 'bar', 'sign' => 'mock-signature']);
$client->post('certificates', ['foo' => 'bar']);
$this->assertSame('POST', $client->getRequestMethod());
$this->assertSame('https://api.mch.weixin.qq.com/certificates', $client->getRequestUrl());
$this->assertContains('Content-Type: text/xml', $client->getRequestOptions()['headers']);
$this->assertSame(Xml::build(['foo' => 'bar', 'sign' => 'mock-signature']), $client->getRequestOptions()['body']);
}
public function test_v2_request_with_xml_option()
{
$client = Client::mock();
$client->shouldReceive('createSignature')->never();
$client->shouldReceive('attachLegacySignature')->with([
'foo' => 'bar',
])->andReturn(['foo' => 'bar', 'sign' => 'mock-signature']);
$client->post('certificates', ['xml' => ['foo' => 'bar']]);
$this->assertSame('POST', $client->getRequestMethod());
$this->assertSame('https://api.mch.weixin.qq.com/certificates', $client->getRequestUrl());
$this->assertContains('Content-Type: text/xml', $client->getRequestOptions()['headers']);
$this->assertSame(Xml::build(['foo' => 'bar', 'sign' => 'mock-signature']), $client->getRequestOptions()['body']);
}
public function test_v2_request_with_xml_string()
{
// XML array will attach signature
$client = Client::mock();
$client->shouldReceive('createSignature')->never();
$client->shouldReceive('attachLegacySignature')->with([
'foo' => 'bar',
])->andReturn(['foo' => 'bar', 'sign' => 'mock-signature'])->once();
$client->post('certificates', ['xml' => ['foo' => 'bar']]);
$this->assertSame('POST', $client->getRequestMethod());
$this->assertSame('https://api.mch.weixin.qq.com/certificates', $client->getRequestUrl());
$this->assertContains('Content-Type: text/xml', $client->getRequestOptions()['headers']);
$this->assertSame('barmock-signature', $client->getRequestOptions()['body']);
// XML string will not attach signature
$client = Client::mock();
$client->shouldReceive('createSignature')->never();
$client->shouldReceive('attachLegacySignature')->never();
$client->post('certificates', ['xml' => Xml::build(['foo' => 'bar'])]);
$this->assertSame('POST', $client->getRequestMethod());
$this->assertSame('https://api.mch.weixin.qq.com/certificates', $client->getRequestUrl());
$this->assertContains('Content-Type: text/xml', $client->getRequestOptions()['headers']);
$this->assertSame(Xml::build(['foo' => 'bar']), $client->getRequestOptions()['body']);
}
public function test_v2_request_with_xml_string_as_body()
{
$client = Client::mock();
$client->shouldReceive('createSignature')->never();
$client->shouldReceive('attachLegacySignature')->with([
'foo' => 'bar',
])->andReturn(['foo' => 'bar', 'sign' => 'mock-signature']);
$client->post('certificates', ['body' => Xml::build(['foo' => 'bar'])]);
$this->assertSame('POST', $client->getRequestMethod());
$this->assertSame('https://api.mch.weixin.qq.com/certificates', $client->getRequestUrl());
$this->assertContains('Content-Type: text/xml', $client->getRequestOptions()['headers']);
$this->assertSame(Xml::build(['foo' => 'bar']), $client->getRequestOptions()['body']);
}
public function test_v2_request_appauth_getaccesstoken()
{
$client = Client::mock('{"retcode":-1,"access_token":"mock-token"}', 200, ['Content-Type' => 'application/json']);
$client->shouldReceive('createSignature')->never();
$client->shouldReceive('isV3Request')->andReturn(false);
$client->shouldReceive('attachLegacySignature')->with([
'foo' => 'bar',
])->andReturn(['foo' => 'bar', 'sign' => 'mock-signature']);
$response = $client->get('/appauth/getaccesstoken', ['query' => ['foo' => 'bar']]);
$this->assertSame('GET', $client->getRequestMethod());
$this->assertEquals(['foo' => 'bar', 'sign' => 'mock-signature'], $client->getRequestOptions()['query']);
$this->assertSame('https://api.mch.weixin.qq.com/appauth/getaccesstoken?foo=bar&sign=mock-signature', $client->getRequestUrl());
$this->assertContains('Content-Type: text/xml', $client->getRequestOptions()['headers']);
}
public function test_v3_upload_media()
{
$client = Client::mock();
$client->shouldReceive('createSignature')->with(
'POST',
'/v3/merchant/media/upload',
\Mockery::on(function ($options) {
return $options['body'] === json_encode([
'filename' => 'image.jpg',
'sha256' => hash('sha256', file_get_contents('./tests/fixtures/files/image.jpg')),
]);
})
)->andReturn('mock-signature');
$response = new MockResponse('{"media_id":"mock-media-id"}');
$client->shouldReceive('request')->with(
'POST',
'/v3/merchant/media/upload',
\Mockery::on(function ($options) {
return $options['body'] !== json_encode([
'filename' => 'image.jpg',
'sha256' => hash('sha256', file_get_contents('./tests/fixtures/files/image.jpg')),
]);
})
)->andReturn($response);
$this->assertSame($response, $client->uploadMedia('/v3/merchant/media/upload', './tests/fixtures/files/image.jpg'));
}
public function test_v3_with_serial_header()
{
$client = Client::mock();
$client->shouldReceive('createSignature')->never();
$client->shouldReceive('attachLegacySignature')->with([
'foo' => 'bar',
])->andReturn(['foo' => 'bar', 'sign' => 'mock-signature']);
$client->withSerialHeader()->post('certificates', ['body' => Xml::build(['foo' => 'bar'])]);
$this->assertSame('Wechatpay-Serial: PUB_KEY_ID_MOCK', $client->getRequestOptions()['headers'][0]);
}
}
================================================
FILE: tests/Pay/MerchantTest.php
================================================
assertSame(100001, $merchant->getMerchantId());
$this->assertSame($privateKey, $merchant->getPrivateKey());
$this->assertSame('v3SecretKey', $merchant->getSecretKey());
$this->assertSame('v2SecretKey', $merchant->getV2SecretKey());
$this->assertSame($publicKey, $merchant->getCertificate());
}
}
================================================
FILE: tests/Pay/ServerTest.php
================================================
'application/json',
],
fopen(__DIR__.'/../fixtures/files/pay_demo.json', 'r')
));
/** @var Merchant&LegacyMockInterface $merchant */
$merchant = \Mockery::mock(Merchant::class);
$merchant->shouldReceive('getSecretKey')->andReturn('key');
$server = new Server($merchant, $request);
$response = $server->serve();
$this->assertSame('{"code":"SUCCESS","message":"成功"}', \strval($response->getBody()));
}
public function test_legacy_encryped_by_aesecb_refund_request()
{
/** @var Merchant&LegacyMockInterface $merchant */
$merchant = \Mockery::mock(Merchant::class);
$merchant->shouldReceive(['getV2SecretKey' => random_bytes(32)]);
$symmtricKey = $merchant->getV2SecretKey();
$server = new Server($merchant, new ServerRequest(
'POST',
'http://easywechat.com/sample-webhook-handler',
[
'Content-Type' => 'text/xml',
],
Xml::build([
'return_code' => 'SUCCESS',
'req_info' => AesEcb::encrypt(Xml::build([
'refund_id' => '50000408942018111907145868882',
'transaction_id' => '4200000215201811190261405420',
]), md5($symmtricKey), ''),
])
));
$response = $server->with(function (Message $message): ResponseInterface {
$source = $message->getOriginalContents();
$parsed = $message->toArray();
$this->assertStringContainsString('', $source);
$this->assertStringContainsString('', $source);
$this->assertStringNotContainsString('', $source);
$this->assertStringNotContainsString('', $source);
$this->assertArrayNotHasKey('return_code', $parsed);
$this->assertArrayNotHasKey('req_info', $parsed);
$this->assertArrayHasKey('refund_id', $parsed);
$this->assertArrayHasKey('transaction_id', $parsed);
return new Response(
200,
['Content-Type' => 'text/xml'],
'SUCCESS'
);
})->serve();
$this->assertEquals(200, $response->getStatusCode());
$this->assertSame('SUCCESS', \strval($response->getBody()));
}
public function test_legacy_encryped_by_aesgcm_notification_request()
{
/** @var Merchant&LegacyMockInterface $merchant */
$merchant = \Mockery::mock(Merchant::class);
$merchant->shouldReceive(['getSecretKey' => random_bytes(32)]);
$symmtricKey = $merchant->getSecretKey();
$server = new Server($merchant, new ServerRequest(
'POST',
'http://easywechat.com/sample-webhook-handler',
[
'Content-Type' => 'text/xml',
],
Xml::build([
'event_type' => 'TRANSACTION.SUCCESS',
'event_algorithm' => 'AEAD_AES_256_GCM',
'event_nonce' => $nonce = bin2hex(random_bytes(6)),
'event_associated_data' => $aad = '',
'event_ciphertext' => AesGcm::encrypt(Xml::build([
'state' => 'USER_PAID',
'service_id' => '1234352342',
]), $symmtricKey, iv: $nonce, aad: $aad),
])
));
$response = $server->with(function (Message $message): ResponseInterface {
$source = $message->getOriginalContents();
$parsed = $message->toArray();
$this->assertStringContainsString('', $source);
$this->assertStringContainsString('', $source);
$this->assertStringContainsString('', $source);
$this->assertStringContainsString('', $source);
$this->assertStringContainsString('', $source);
$this->assertStringContainsString('', $source);
$this->assertStringNotContainsString('', $source);
$this->assertStringNotContainsString('', $source);
$this->assertArrayHasKey('event_type', $parsed);
$this->assertArrayHasKey('event_algorithm', $parsed);
$this->assertArrayHasKey('event_nonce', $parsed);
$this->assertArrayHasKey('event_associated_data', $parsed);
$this->assertArrayHasKey('event_ciphertext', $parsed);
$this->assertArrayHasKey('state', $parsed);
$this->assertArrayHasKey('service_id', $parsed);
return new Response(
500,
['Content-Type' => 'text/xml'],
'ERROR_NAMEERROR_DESCRIPTION'
);
})->serve();
$this->assertEquals(500, $response->getStatusCode());
$this->assertSame('ERROR_NAMEERROR_DESCRIPTION', \strval($response->getBody()));
}
}
================================================
FILE: tests/Pay/UtilsTest.php
================================================
'mock-appid',
'timeStamp' => 1601234567,
'nonceStr' => 'mock-nonce',
'package' => 'prepay_id=mock-prepay-id',
'signType' => 'MD5',
];
$merchant = \Mockery::mock(Merchant::class);
$merchant->allows()->getV2SecretKey()->andReturn('mock-v2-secret-key');
$utils = new Utils(merchant: $merchant);
$this->assertSame('C52D6B09E8A039D6E8696A014BB37160', $utils->createV2Signature($params));
$params['signType'] = 'HMAC-SHA256';
$this->assertSame('BAC9240577E86EDC7753264E502196C61F78F24777E9E7CCE82A7BD97F906EED', $utils->createV2Signature($params));
}
public function test_encrypt_with_rsa_public_key()
{
$privateKey = new PrivateKey('mock-private-key');
$publicKey = \Mockery::mock(PublicKey::class);
$merchant = new Merchant(
mchId: 100001,
privateKey: $privateKey,
certificate: $publicKey,
secretKey: 'v3SecretKey',
v2SecretKey: 'v2SecretKey',
platformCerts: [
'PUB_KEY_ID_MOCK' => '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlReZ1YnfAohRIfUqIeyP
aO0PlkMw1RLPdZbEZmldbGrIrOh/0XqSzNZ+mtB6H0eB7TSaoGFtdp/AWy3tb67m
1T62OrEhz6bnSKMcZkYVmODyxZvcwsCZ3zqCaFo7FrGmh1o9M0/Xfa5SOX4jVGni
3iM7r7YD/NiW2RCYDtjMoLTmVgrzv45Mzu2XpJqtNbUJIRRhVSnjsAZRC6spWH+b
QpYIkVd4qmYE0qdpIQBMYOV1w7v1pYn6Z5QdKG4keemADTn4QaZZHrryTcHNYVsZ
2OZ3aybrevSV3wDGnYGk2nt2xtkdfaNfFn4dGW+p4an5M4fRK+CnYpeTgI6POABk
pwIDAQAB
-----END PUBLIC KEY-----',
]
);
$utils = new Utils(merchant: $merchant);
$this->assertIsString($utils->encryptWithRsaPublicKey('mock-plaintext', 'PUB_KEY_ID_MOCK'));
$this->assertIsString($utils->encryptWithRsaPublicKey('mock-plaintext'));
$this->expectException(InvalidConfigException::class);
$utils->encryptWithRsaPublicKey('mock-plaintext', 'PUB_KEY_ID_OTHER');
$this->expectException(EncryptionFailureException::class);
$utils->encryptWithRsaPublicKey('', 'PUB_KEY_ID_MOCK');
}
}
================================================
FILE: tests/TestCase.php
================================================
addToAssertionCount($container->Mockery_getExpectationCount());
}
\Mockery::close();
}
public function createEncryptedXmlMessageRequest($plainMessageXml, Encryptor $encryptor, array $query = []): ServerRequest
{
$body = $encryptor->encrypt($plainMessageXml);
$xml = Xml::parse($body);
return (new ServerRequest('POST', 'http://easywechat.com/server', [], $body))->withQueryParams([
'msg_signature' => $xml['MsgSignature'],
'timestamp' => $xml['TimeStamp'],
'nonce' => $xml['Nonce'],
...$query,
]);
}
}
================================================
FILE: tests/Work/AccessTokenTest.php
================================================
'mock_access_token',
'expires_in' => '1500',
];
$response->allows()->toArray(false)->andReturn($result);
$config = [
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
];
$options = [
'query' => [
'corpid' => $config['corp_id'],
'corpsecret' => $config['secret'],
],
];
$httpClient->allows()->request('GET', '/cgi-bin/gettoken', $options)->andReturn($response);
$accessToken = new AccessToken($config['corp_id'], $config['secret'], null, null, $httpClient);
$this->assertSame($result['access_token'], $accessToken->getToken());
}
public function test_get_token_from_cache()
{
$cache = \Mockery::mock(CacheInterface::class);
$key = 'mock-cache-key';
$result = [
'access_token' => 'mock_access_token',
'expires_in' => '1500',
];
$cache->expects()->get($key)->andReturn($result['access_token']);
$config = [
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
];
$accessToken = new AccessToken($config['corp_id'], $config['secret'], $key, $cache);
$this->assertSame($result['access_token'], $accessToken->getToken());
}
public function test_set_key()
{
$config = [
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
];
$key = 'mock-cache-key';
$accessToken = new AccessToken($config['corp_id'], $config['secret'], $key);
$this->assertSame($key, $accessToken->getKey());
}
}
================================================
FILE: tests/Work/AccountTest.php
================================================
'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes_key',
'agent_id' => 1000001,
]
);
$this->assertInstanceOf(AccountInterface::class, $app->getAccount());
}
/**
* @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
*/
public function test_set_account_to_application()
{
$accountConfig = [
'corp_id' => 'wx3cf0f39249111111',
'secret' => 'mock-account-secret',
'token' => 'mock-account-token',
'aes_key' => 'mock-account-aes-key',
];
$account = new Account(
corpId: $accountConfig['corp_id'],
secret: $accountConfig['secret'],
token: $accountConfig['token'],
aesKey: $accountConfig['aes_key'],
);
$config = [
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes_key',
];
$app = new Application($config);
$this->assertInstanceOf(AccountInterface::class, $app->getAccount());
$this->assertSame($config['corp_id'], $app->getAccount()->getCorpId());
$app->setAccount($account);
$this->assertNotSame($config['corp_id'], $app->getAccount()->getCorpId());
$this->assertSame($accountConfig['corp_id'], $app->getAccount()->getCorpId());
}
public function test_get_account_corp_id()
{
$config = [
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes-key',
];
$account = new Account(
corpId: $config['corp_id'],
secret: $config['secret'],
token: $config['token'],
aesKey: $config['aes_key']
);
$this->assertSame($config['corp_id'], $account->getCorpId());
}
public function test_get_account_secret()
{
$config = [
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes-key',
];
$account = new Account(
corpId: $config['corp_id'],
secret: $config['secret'],
token: $config['token'],
aesKey: $config['aes_key']
);
$this->assertSame($config['secret'], $account->getSecret());
}
public function test_get_account_token()
{
$config = [
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes-key',
];
$account = new Account(
corpId: $config['corp_id'],
secret: $config['secret'],
token: $config['token'],
aesKey: $config['aes_key']
);
$this->assertSame($config['token'], $account->getToken());
}
public function test_get_account_aes_key()
{
$config = [
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'mock-aes-key',
];
$account = new Account(
corpId: $config['corp_id'],
secret: $config['secret'],
token: $config['token'],
aesKey: $config['aes_key']
);
$this->assertSame($config['aes_key'], $account->getAesKey());
}
}
================================================
FILE: tests/Work/ApplicationTest.php
================================================
'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(ApplicationInterface::class, $app);
$this->assertInstanceOf(AccountInterface::class, $app->getAccount());
$this->assertSame($app->getAccount(), $app->getAccount());
// set
$account = new Account(corpId: 'wx3cf0f39249000060', secret: 'mock-secret', token: 'mock-token', aesKey: 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG');
$app->setAccount($account);
$this->assertSame($account, $app->getAccount());
}
public function test_get_and_set_encryptor()
{
$app = new Application(
[
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(Encryptor::class, $app->getEncryptor());
$this->assertSame($app->getEncryptor(), $app->getEncryptor());
// set
$encryptor = new Encryptor(corpId: 'wx3cf0f39249000060', token: 'mock-token', aesKey: 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG');
$app->setEncryptor($encryptor);
$this->assertSame($encryptor, $app->getEncryptor());
}
public function test_get_and_set_request()
{
$app = new Application(
[
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(ServerRequestInterface::class, $app->getRequest());
$this->assertSame($app->getRequest(), $app->getRequest());
// set
$request = \Mockery::mock(ServerRequestInterface::class);
$app->setRequest($request);
$this->assertSame($request, $app->getRequest());
}
public function test_get_and_set_server()
{
$app = new Application(
[
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(ServerInterface::class, $app->getServer());
$this->assertSame($app->getServer(), $app->getServer());
// set
$server = new Server(
encryptor: $app->getEncryptor(),
request: \Mockery::mock(ServerRequestInterface::class)
);
$app->setServer($server);
$this->assertSame($server, $app->getServer());
}
public function test_get_and_set_client()
{
$app = new Application(
[
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(AccessTokenAwareClient::class, $app->getClient());
$this->assertSame($app->getClient(), $app->getClient());
// set
$client = new AccessTokenAwareClient;
$app->setClient($client);
$this->assertSame($client, $app->getClient());
}
public function test_get_and_set_http_client()
{
$app = new Application(
[
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(HttpClientInterface::class, $app->getHttpClient());
$this->assertSame($app->getHttpClient(), $app->getHttpClient());
// set
$client = new AccessTokenAwareClient;
$app->setHttpClient($client);
$this->assertSame($client, $app->getHttpClient());
}
public function test_get_and_set_access_token()
{
$app = new Application(
[
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(AccessTokenInterface::class, $app->getAccessToken());
$this->assertSame($app->getAccessToken(), $app->getAccessToken());
// set
$accessToken = new AccessToken('wx3cf0f39249000060', 'mock-secret');
$app->setAccessToken($accessToken);
$this->assertSame($accessToken, $app->getAccessToken());
}
public function test_get_and_set_cache()
{
$app = new Application(
[
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(CacheInterface::class, $app->getCache());
$this->assertSame($app->getCache(), $app->getCache());
// set
$cache = \Mockery::mock(Psr16Cache::class);
$app->setCache($cache);
$this->assertSame($cache, $app->getCache());
}
public function test_get_and_set_config()
{
$app = new Application(
[
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$this->assertInstanceOf(ConfigInterface::class, $app->getConfig());
$this->assertSame($app->getConfig(), $app->getConfig());
// set
$config = new Config(
[
'corp_id' => 'wx3cf0f39249000060-2',
'secret' => 'mock-secret-2',
'token' => 'mock-token-2',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$app->setConfig($config);
$this->assertSame($config, $app->getConfig());
}
public function test_get_and_set_ticket()
{
$app = new Application(
[
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
'agent_id' => 100001,
]
);
$this->assertInstanceOf(JsApiTicket::class, $app->getTicket());
// set
$ticket = new JsApiTicket('wx3cf0f39249000060', 'mock-token', $app->getCache(), $app->getClient());
$app->setTicket($ticket);
$this->assertSame($ticket, $app->getTicket());
}
public function test_get_utils()
{
$app = new Application(
[
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
'agent_id' => 100001,
]
);
$this->assertInstanceOf(Utils::class, $app->getUtils());
}
public function test_get_oauth()
{
$app = new Application(
[
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
]
);
$oauth = $app->getOauth();
$this->assertInstanceOf(WeWork::class, $oauth);
$ref = new \ReflectionProperty($oauth, 'agentId');
$this->assertNull($ref->getValue($oauth));
// with default agent id
$app = new Application(
[
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
'aes_key' => 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
'agent_id' => '100001',
]
);
$oauth = $app->getOauth();
$this->assertInstanceOf(WeWork::class, $oauth);
$ref = new \ReflectionProperty($oauth, 'agentId');
$this->assertSame(100001, $ref->getValue($oauth));
}
}
================================================
FILE: tests/Work/ConfigTest.php
================================================
'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
]
);
$this->assertInstanceOf(ConfigInterface::class, $app->getConfig());
}
/**
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
* @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
*/
public function test_set_config_to_application()
{
$config = [
'corp_id' => 'wx3cf0f39249111111',
'secret' => 'mock-account-secret',
'token' => 'mock-account-token',
'aes_key' => 'mock-account-aes-key',
'agent_id' => 1000001,
];
$config = new Config($config);
$applicationConfig = [
'corp_id' => 'wx3cf0f39249000060',
'secret' => 'mock-secret',
'token' => 'mock-token',
];
$app = new Application(
[
'corp_id' => $applicationConfig['corp_id'],
'secret' => $applicationConfig['secret'],
'token' => $applicationConfig['token'],
]
);
$this->assertInstanceOf(ConfigInterface::class, $app->getConfig());
$this->assertSame($applicationConfig['corp_id'], $app->getConfig()->get('corp_id'));
$this->assertSame(false, $app->getConfig()->has('aes_key'));
$app->setConfig($config);
$this->assertNotSame($applicationConfig['corp_id'], $app->getConfig()->get('corp_id'));
$this->assertSame($config['corp_id'], $app->getConfig()->get('corp_id'));
$this->assertSame(true, $app->getConfig()->has('aes_key'));
}
public function test_init_config_can_check_missing_keys()
{
$config = [
'secret' => 'mock-account-secret',
'token' => 'mock-account-token',
'aes_key' => 'mock-account-aes_key',
'agent_id' => 1000001,
];
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(\sprintf('"%s" cannot be empty.', 'corp_id'));
new Config($config);
}
}
================================================
FILE: tests/Work/JsApiTicketTest.php
================================================
assertInstanceOf(JsApiTicket::class, $ticket);
$this->assertSame('work.jsapi_ticket.mock-corpid', $ticket->getKey());
$ticket->setKey('mock-key');
$this->assertSame('mock-key', $ticket->getKey());
$ticket = new JsApiTicket('mock-corpid', 'test-key');
$this->assertSame('test-key', $ticket->getKey());
}
public function test_get_agent_key()
{
$ticket = new JsApiTicket('mock-corpid');
$this->assertInstanceOf(JsApiTicket::class, $ticket);
$this->assertSame('work.jsapi_ticket.mock-corpid.100001', $ticket->getAgentKey(100001));
$ticket->setKey('mock-key');
$this->assertSame('mock-key.100001', $ticket->getAgentKey(100001));
$ticket = new JsApiTicket('mock-corpid', 'test-key');
$this->assertSame('test-key.100001', $ticket->getAgentKey(100001));
}
public function test_get_ticket()
{
$cacheKey = 'work.jsapi_ticket.mock-corpid';
$ticket = [
'ticket' => 'mock-ticket',
'expires_in' => 7200,
];
$response = \Mockery::mock(ResponseInterface::class);
$response->allows()->toArray(false)->andReturn($ticket);
$client = \Mockery::mock(HttpClientInterface::class);
$cache = \Mockery::mock(CacheInterface::class);
$cache->expects()->get($cacheKey)->andReturn($ticket['ticket']);
$jsApiTicket = new JsApiTicket('mock-corpid', cache: $cache, httpClient: $client);
$this->assertSame($ticket['ticket'], $jsApiTicket->getTicket());
// 设为过期
$cache->expects()->get($cacheKey)->andReturn(false);
$cache->expects()->set($cacheKey, $ticket['ticket'], $ticket['expires_in'])->andReturn(true);
$client->allows()->request('GET', '/cgi-bin/get_jsapi_ticket')
->andReturn($response);
$this->assertSame($ticket['ticket'], $jsApiTicket->getTicket());
}
public function test_get_agent_ticket()
{
$cacheKey = 'work.jsapi_ticket.mock-corpid.100001';
$ticket = [
'ticket' => 'mock-ticket',
'expires_in' => 7200,
];
$response = \Mockery::mock(ResponseInterface::class);
$response->allows()->toArray(false)->andReturn($ticket);
$client = \Mockery::mock(HttpClientInterface::class);
$cache = \Mockery::mock(CacheInterface::class);
$cache->expects()->get($cacheKey)->andReturn($ticket['ticket']);
$jsApiTicket = new JsApiTicket('mock-corpid', cache: $cache, httpClient: $client);
$this->assertSame($ticket['ticket'], $jsApiTicket->getAgentTicket(100001));
// 设为过期
$cache->expects()->get($cacheKey)->andReturn(false);
$cache->expects()->set($cacheKey, $ticket['ticket'], $ticket['expires_in'])->andReturn(true);
$client->allows()->request('GET', '/cgi-bin/ticket/get', ['query' => ['type' => 'agent_config']])
->andReturn($response);
$this->assertSame($ticket['ticket'], $jsApiTicket->getAgentTicket(100001));
}
public function test_config_signature()
{
$nonce = 'mock-nonce';
$timestamp = 1601234567;
$cacheKey = 'work.jsapi_ticket.mock-corpid';
$cache = \Mockery::mock(CacheInterface::class);
$cache->expects()->get($cacheKey)->andReturn('mock-ticket');
$ticket = new JsApiTicket('mock-corpid', cache: $cache);
$result = $ticket->createConfigSignature('https://www.easywechat.com/', $nonce, $timestamp);
$data = [
'appId' => 'mock-corpid',
'nonceStr' => 'mock-nonce',
'timestamp' => 1601234567,
'url' => 'https://www.easywechat.com/',
'signature' => '22772d2fb393ab9f7f6a5a54168a566fbf1ab767',
];
$this->assertSame($data, $result);
}
public function test_agent_config_signature()
{
$nonce = 'mock-nonce';
$timestamp = 1601234567;
$cacheKey = 'work.jsapi_ticket.mock-corpid.100001';
$cache = \Mockery::mock(CacheInterface::class);
$cache->expects()->get($cacheKey)->andReturn('mock-ticket');
$ticket = new JsApiTicket('mock-corpid', cache: $cache);
$result = $ticket->createAgentConfigSignature(100001, 'https://www.easywechat.com/', $nonce, $timestamp);
$data = [
'corpid' => 'mock-corpid',
'agentid' => 100001,
'nonceStr' => 'mock-nonce',
'timestamp' => 1601234567,
'url' => 'https://www.easywechat.com/',
'signature' => '22772d2fb393ab9f7f6a5a54168a566fbf1ab767',
];
$this->assertSame($data, $result);
}
public function test_get_ticket_signature()
{
$ticket = new JsApiTicket('mock-corpid', 'mock-secret');
$sign = $ticket->getTicketSignature('mock-ticket', 'mock-nonce', 1601234567, 'https://www.easywechat.com/');
$this->assertSame('22772d2fb393ab9f7f6a5a54168a566fbf1ab767', $sign);
}
}
================================================
FILE: tests/Work/ServerTest.php
================================================
withQueryParams([
'msg_signature' => '5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3',
'timestamp' => '1409659589',
'nonce' => '263014780',
'echostr' => 'P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ==',
]);
$app = new Application([
'corp_id' => 'wx5823bf96d3bd56c7',
'secret' => 'secret',
'token' => 'QDG6eK',
'aes_key' => 'jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C',
]);
$app->setRequest($request);
$response = $app->getServer()->serve();
$this->assertSame('1616140317555161061', \strval($response->getBody()));
}
public function test_it_will_validate_message()
{
$body = '
';
$request = (new ServerRequest('POST', 'http://easywechat.com/server', [], $body))->withQueryParams([
'msg_signature' => '477715d11cdb4164915debcba66cb864d751f3e6',
'timestamp' => '1409659813',
'nonce' => '1372623149',
]);
$app = new Application([
'corp_id' => 'wx5823bf96d3bd56c7',
'secret' => '',
'token' => 'QDG6eK',
'aes_key' => 'jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C',
]);
$app->setRequest($request);
$response = $app->getServer()->serve();
$this->assertSame('SUCCESS', \strval($response->getBody()));
}
public function test_it_will_response_success_without_handlers()
{
$body = '
';
$request = (new ServerRequest('POST', 'http://easywechat.com/server', [], $body))->withQueryParams([
'msg_signature' => '477715d11cdb4164915debcba66cb864d751f3e6',
'timestamp' => '1409659813',
'nonce' => '1372623149',
]);
$app = new Application([
'corp_id' => 'wx5823bf96d3bd56c7',
'secret' => '',
'token' => 'QDG6eK',
'aes_key' => 'jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C',
]);
$app->setRequest($request);
$response = $app->getServer()->serve();
$this->assertSame('SUCCESS', \strval($response->getBody()));
}
public function test_it_will_respond_from_message_handlers()
{
$app = new Application([
'corp_id' => 'wx5823bf96d3bd56c7',
'secret' => '',
'token' => 'QDG6eK',
'aes_key' => 'jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C',
]);
$request = $this->createEncryptedXmlMessageRequest('
1403610513
change_contact
', $app->getEncryptor());
$app->setRequest($request);
$response = $app->getServer()
->addMessageListener(
'event',
function ($message) {
return 'hello';
}
)
->addEventListener(
'scancode_push',
function ($message) {
return 'world';
}
)
->serve();
$message = Xml::parse(\strval($response->getBody()));
$response = Xml::parse($app->getEncryptor()->decrypt($message['Encrypt'], $message['MsgSignature'], $message['Nonce'], $message['TimeStamp']));
$this->assertSame('sys', $response['ToUserName']);
$this->assertSame('toUser', $response['FromUserName']);
$this->assertSame('text', $response['MsgType']);
$this->assertSame('hello', $response['Content']);
}
public function test_it_will_respond_from_event_handlers()
{
$app = new Application([
'corp_id' => 'wx5823bf96d3bd56c7',
'secret' => '',
'token' => 'QDG6eK',
'aes_key' => 'jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C',
]);
$request = $this->createEncryptedXmlMessageRequest('
1403610513
change_contact
', $app->getEncryptor());
$app = new Application([
'corp_id' => 'wx5823bf96d3bd56c7',
'secret' => '',
'token' => 'QDG6eK',
'aes_key' => 'jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C',
]);
$app->setRequest($request);
$response = $app->getServer()
->addMessageListener(
'event',
function ($message) {
return 'hello';
}
)
->addEventListener(
'change_contact',
function ($message) {
return 'world';
}
)
->serve();
$message = Xml::parse(\strval($response->getBody()));
$response = Xml::parse($app->getEncryptor()->decrypt($message['Encrypt'], $message['MsgSignature'], $message['Nonce'], $message['TimeStamp']));
$this->assertSame('sys', $response['ToUserName']);
$this->assertSame('toUser', $response['FromUserName']);
$this->assertSame('text', $response['MsgType']);
$this->assertSame('hello', $response['Content']);
}
}
================================================
FILE: tests/Work/UtilsTest.php
================================================
['api1', 'api2'],
'openTagList' => ['openTag1', 'openTag2'],
'debug' => true,
'beta' => true,
'url' => 'https://www.easywechat.com/',
'nonceStr' => 'mock-nonce',
'timestamp' => 1601234567,
'appId' => 'mock-appid',
'signature' => '22772d2fb393ab9f7f6a5a54168a566fbf1ab767',
];
$signatue = [
'url' => 'https://www.easywechat.com/',
'nonceStr' => 'mock-nonce',
'timestamp' => 1601234567,
'appId' => 'mock-appid',
'signature' => '22772d2fb393ab9f7f6a5a54168a566fbf1ab767',
];
$ticket = \Mockery::mock(JsApiTicket::class);
$ticket->shouldReceive('createConfigSignature')->andReturn($signatue);
$app = \Mockery::mock(Application::class);
$app->allows()->getTicket()->andReturn($ticket);
$utils = new Utils($app);
$result = $utils->buildJsSdkConfig('https://www.easywechat.com/', ['api1', 'api2'], ['openTag1', 'openTag2'], true, true);
$this->assertSame($data, $result);
}
public function test_build_js_sdk_agent_config()
{
$data = [
'jsApiList' => ['api1', 'api2'],
'openTagList' => ['openTag1', 'openTag2'],
'debug' => true,
'url' => 'https://www.easywechat.com/',
'nonceStr' => 'mock-nonce',
'timestamp' => 1601234567,
'corpid' => 'mock-corpid',
'agentid' => 100001,
'signature' => '22772d2fb393ab9f7f6a5a54168a566fbf1ab767',
];
$signatue = [
'url' => 'https://www.easywechat.com/',
'nonceStr' => 'mock-nonce',
'timestamp' => 1601234567,
'corpid' => 'mock-corpid',
'agentid' => 100001,
'signature' => '22772d2fb393ab9f7f6a5a54168a566fbf1ab767',
];
$ticket = \Mockery::mock(JsApiTicket::class);
$ticket->shouldReceive('createAgentConfigSignature')->andReturn($signatue);
$app = \Mockery::mock(Application::class);
$app->allows()->getTicket()->andReturn($ticket);
$utils = new Utils($app);
$result = $utils->buildJsSdkAgentConfig(100001, 'https://www.easywechat.com/', ['api1', 'api2'], ['openTag1', 'openTag2'], true);
$this->assertSame($data, $result);
}
}
================================================
FILE: tests/bootstrap.php
================================================
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
define('TEST_ROOT', __DIR__);
define('STUBS_ROOT', __DIR__.'/fixtures');
$_SERVER['HTTP_HOST'] = 'localhost';
include __DIR__.'/../vendor/autoload.php';
================================================
FILE: tests/fixtures/cert.pem
================================================
-----BEGIN CERTIFICATE-----
MIIDsjCCApqgAwIBAgIEDcDfgzANBgkqhkiG9w0BAQsFADB0MQswCQYDVQQGEwJT
QTERMA8GA1UECBMITXkgU3RhdGUxEDAOBgNVBAcTB015IENpdHkxEzARBgNVBAoT
Ck15IENvbXBhbnkxEDAOBgNVBAsTB015IFRlYW0xGTAXBgNVBAMTEERlbW8gQ2Vy
dGlmaWNhdGUwIBcNMjIwMzA0MTUxNzAxWhgPMjI5NTEyMTcxNTE3MDFaMHQxCzAJ
BgNVBAYTAlNBMREwDwYDVQQIEwhNeSBTdGF0ZTEQMA4GA1UEBxMHTXkgQ2l0eTET
MBEGA1UEChMKTXkgQ29tcGFueTEQMA4GA1UECxMHTXkgVGVhbTEZMBcGA1UEAxMQ
RGVtbyBDZXJ0aWZpY2F0ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
APX8l0tL4xSuOqTxjdp560g8G+kt9YpRmhyYWdF6sztqYG1LdaBBxF1qFMU0/mwk
v7G0YbcqEuwh+V0+veRYxPIpZJ5f9fqt6uY99BzRHbcur1XNlvKrJean2Zu0T+XH
rFbGuDa+MvqPevwyymZkvxodh/RHkUCgjCmFMkH6KGa3SjpgBBn1/j6lM+PG4+Cr
glear4YefgtfyqeGUcT9kmmyBQKl9jcM4392WsZEyfk17e9JYivH4Zcpzb2/47ZM
TqXQymor4NFtSQ0FytMigoKzVSH5QWxiNZPe8/8Vn96sPiPmouy69dicexD2yti4
ThYuSp59Uu0iDgJgEjulQKcCAwEAAaNKMEgwJwYDVR0RBCAwHoILb3ZlcnRydWUu
bWWCCWxvY2FsaG9zdIcEfwAAATAdBgNVHQ4EFgQUYYqZN/c2sBfiE8VFV09T+lBo
KpQwDQYJKoZIhvcNAQELBQADggEBALsMXtmqvYVBSGPX1sP11K/Hw/oVdX+mOWEY
5o73URfJ9iYTQ1zfUpwzK1RBWFhqYpUmFy4butt3RKPcmvu505/fZuyWFRD4tjKY
MnazZ1n3/tqMePgjrx0UY9M4IAzd7JB8eIXAiyn/jf09uwkRrPwtKlAPxUDvaZVa
NlZ5SogUanDS2vGSCpedvYXt2F/RxbodwO/DfkFdBfmafHWWqeUPjlLSa9uyser9
oKmO70LGHeT0wMnll7Z4nYUScFfrBMnqoA0eH8nnZsBvydc8SvSjIqVwiYdmjshP
CdebaN9CH/9US2sqCunHCo1E+EKI90FOeKu2kinW3HUvmg3XCOI=
-----END CERTIFICATE-----
================================================
FILE: tests/fixtures/files/demo_cert.pem
================================================
-----BEGIN CERTIFICATE-----
VGhpcyBpcyBhIGRlbW8gY2VydCBjb250ZW50cy4=
-----END CERTIFICATE-----
================================================
FILE: tests/fixtures/files/demo_key.pem
================================================
-----BEGIN PUBLIC KEY-----
VGhpcyBpcyBhIGRlbW8gcHVibGljIGtleSBjb250ZW50cy4=
-----END PUBLIC KEY-----
================================================
FILE: tests/fixtures/files/empty.file
================================================
================================================
FILE: tests/fixtures/files/pay_demo.json
================================================
{"id":"EV-2018022511223320873","create_time":"2015-05-20T13:29:35+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"\u652f\u4ed8\u6210\u529f","resource":{"nonce":"iv","associated_data":"aad","ciphertext":"gjxWKg2rMkwEcv\/Hx9otXWwpEfyk\/lltqRdgs1spC5vCj8VJn8lrmMuGArlZsXB4lhcJ5mBLo2mbQRlfZ0bobHV4DXspkyTec7\/6E5W+MP1MI0CeO7phqbx6pYtrmlhEfKpcCaDUClbAuNv5YnO1buG9eKA+E7u+VbCTaVQTYkdWaM0VNQjI89m3ys+HUWl2s4cjAa3OSdrGo3AI9HJwIGoaX2F+gcBZTiheNNpaxKAdCqZVBP965tvew6qv2UHqwppKtgh91OTvKnbvH7lT0DFavgd+eqeB18E9cnCEh\/vYAFyU2LMbi2pkp5P5Q7PGXJBqg1XtvtkkFOxGwh8r7eEKCReCrDnP8jr6YgJP7bC+3kBXpFV+QzGOVuOB9liUH1yHkzz8gR2bMA9l23gp393fgoPlkZdx7wqHKZ3qrrc8mBIVHzbbv95w7NfpWutToai\/qOEfGYrawkZLACE+c\/U+zPdcpuWWQFgR0q4o+8+LLvgg+rppJCqKsiZq229Ux1SRl1sq6CEocR5bP\/7uWSuWDAb0VSy33Amg07Wtb1BHThwowOtuZNQVVJo3XucRi6W3ETzXsSw="}}
================================================
FILE: tests/fixtures/private.key
================================================
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQD1/JdLS+MUrjqk
8Y3aeetIPBvpLfWKUZocmFnRerM7amBtS3WgQcRdahTFNP5sJL+xtGG3KhLsIfld
Pr3kWMTyKWSeX/X6rermPfQc0R23Lq9VzZbyqyXmp9mbtE/lx6xWxrg2vjL6j3r8
MspmZL8aHYf0R5FAoIwphTJB+ihmt0o6YAQZ9f4+pTPjxuPgq4JXmq+GHn4LX8qn
hlHE/ZJpsgUCpfY3DON/dlrGRMn5Ne3vSWIrx+GXKc29v+O2TE6l0MpqK+DRbUkN
BcrTIoKCs1Uh+UFsYjWT3vP/FZ/erD4j5qLsuvXYnHsQ9srYuE4WLkqefVLtIg4C
YBI7pUCnAgMBAAECggEBAONzz5XBMtUxkWppLQiiiWs+oXRIme1vLPhZ61tmgIpk
/4qwJrCrf139M/1x1fu7M0GnEF+kWODdPU36MO4PIvTkT3SeOL21ySliifGHb1mt
olTNiFEU7jPMasutu981dWa70yRTVKIYv9ipQjvR1l7YhZjcADRo/5F45xLYtDjc
XH8HnWb+OB2uPG72HDOtNkg55V1oCcTZqlRw1P8MpibIW/OiE5s70/USqR9v+Dua
GUWKXEggD80GsyB8T5SYEG9KV0GqDDnJ2ebvrCniBkwFkjGlNy6VC7T5WzwMP7af
NM1a5Rl4r5SgLkhU9Boug9xh78HNcpEyIoYRIgbYKiECgYEA/R6X0uugUqVnoStu
U9dOcaeuxbqg8uVmmq4hRBsuwL1MT2mhQrjkpiGzmf8BFgZhPmdBPNbkiEFfWzJl
G/aADemwycICyKEQJrsTv830HBB40icxDesnfGXrFSN1rPutyrvuk+O60QpfrCKV
vAmvebfsOmI7rZUCjO4wm3FupncCgYEA+Mk30o7pkKnlbbmzIGnpnT0JJO2Ukg03
TbbUJ9n39eR0Q4yU0qn9GkUD6j3JUzN35kLdorD8GtRECT+Dwe/MTJmXOmSa+pNv
r2Oz6+VkIozK8Arb1UhXZvdxmEK+G8JbGb9TBdY+g5KEUzxiJVvGaohNEmUrdiU+
mhUwJM4mU1ECgYEAjHRDbwjMx898t5Qv/loE71BKzPGIif/9dWuWjgI/aTghdhd5
IlsSlZUx4gv8gEo9/7CwJKBh47HSxfoq3N9lo1K/hNUhUk79dWBtzwrrn/8L7CFP
ORf5qy+qyOoKTFjD0TGDa5D8gy6sdAok6Fi/hF0ouiT0VJfQ+H7bfgXtjnUCgYAL
qGosPLQnKj7tAFmreCsRSi3mhBeFLIdd5eZVI7qh1B26mJjUslCA7aD8Vf7cHjpN
GO8H06FMpIu3nzlOWi1JnZzfiJ1WhpgiMNraf/pMQCq2Stv4R5aI5al2CBKefGIG
d9etG1f8lF4NBHRY6c8HaPGrngAGXkJrt/h0kRBssQKBgHj7HfSxz1prctAj/zSH
6KuxvZuUy33vjazfIyTFuZpLypUqduA+FdpRy/4LOe1SvM7ocs6wUplVRVt0m6/N
8mTtP+V5aKeT03wor8n9AU37nLJXp1LrYiLiBkv8xVqCao50nI5TmfGDScaowILc
wv9NyxIRjUZ1EaLp16JDQaWN
-----END PRIVATE KEY-----