Commit d822c260 by 冯佳佳

Initial commit

parents

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

# src_dir: src
coverage_clover: coverage.clover
json_path: coveralls-upload.json
\ No newline at end of file
APP_ENV=local
APP_KEY=base64:8i/NA9BZqqS8Rd/tL3ctIGKsh37OkOrY3iRXoxLr1HQ=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://153.34.241.104:8888/
APP_LOCALE=zh
APP_FALLBACK_LOCALE=en
APP_LOCALE_PHP=zh_CN
APP_TIMEZONE=PRC
USER_IMAGE_URL_PREFIX=http://oigy7evem.bkt.clouddn.com/
SMS_BASE_URL=https://api.netease.im/sms/
SMS_TEMPLATE_URL=sendtemplate.action
SMS_CODE_URL=sendcode.action
SMS_VERIFY_URL=verifycode.action
SMS_APP_KEY=ebf758ec81cf9a4cbb7b59eefef0a9ee
SMS_APP_SECRET=e4cc7ab12c8f
SMS_CODE_LEN=4
APP_STORE_HACK_ON=1
APP_STORE_HACK_TELEPHONE=15501681055
APP_STORE_HACK_SMS=1989
HE_CLOUD_API_ADDRESS=http://api.js.cmcconenet.com
HE_CLOUD_API_KEY=aFpHq1TkvggQrHkTgMlTKA2pXAI=
HE_CLOUD_TOKEN=Rqb8bogu6hchuIMaNzfzFpsDDOSuxKJB
HE_CLOUD_ENCODING_AES_KEY=LhNFQMGp6K86jCxF5QyJCf5GOe7zbhyJztRkx2nHDTr
QINIU_ACCESS_KEY=wlMcrYajGXGtzOfzJKtVRhx_nyk_NDLhWs43sACg
QINIU_SECRET=UUpPA9ek1VAuFEqHhNa-kw6bTL83D1UKYPBU2tqz
QINIU_CALLBACK_BASE_URL=https://apidev.tg.shzaonuo.com/
QINIU_USER_BUCKET=user
QINIU_USER_BUCKET_URL=http://p2a3zwe04.bkt.clouddn.com/
QINIU_SHOP_BUCKET=shop
QINIU_SHOP_BUCKET_URL=http://p2a3w4wx1.bkt.clouddn.com/
QINIU_REPAIR_BUCKET=repair
QINIU_REPAIR_BUCKET_URL=http://p2a3dr73w.bkt.clouddn.com/
WEBSOCKET_PUSH_SERVER=172.17.16.16:1238
AMAP_API_URL=http://restapi.amap.com/v3/geocode/regeo
AMAP_KEY=de5fb056635efe79e01afbe47d1563de
WECHAT_APPID=wx4891d9f7b1305812
WECHAT_APPSECRET=0bfa4f989ffe981623074a30784b9c3c
WECHAT_MINI_PROGRAM_ID=wx3c08b58c17c85a13
WECHAT_MINI_PROGRAM_SECRET=21025e813ef22e4cfef6d583bcb766e2
WECHAT_MCHID=1446773302
WECHAT_KEY=xiaobanjMHSkIp96j8MB8xKxbWebl9jE
WECHAT_UNIFIED_ORDER_URL=https://api.mch.weixin.qq.com/pay/unifiedorder
WECHAT_OPEN_ID_URL=https://api.weixin.qq.com/sns/jscode2session
WECHAT_REFUND_URL=https://api.mch.weixin.qq.com/secapi/pay/refund
WECHAT_QUERY_URL=https://api.mch.weixin.qq.com/pay/orderquery
WECHAT_SSL_CERT_PATH=app/Certs/Wechat/apiclient_cert.pem
WECHAT_SSL_KEY_PATH=app/Certs/Wechat/apiclient_key.pem
QQ_ANDROID_APP_ID=1106267569
QQ_ANDROID_APP_SECRET=G7FtJy6p0pSaB9ro
QQ_iOS_APP_ID=1106267645
QQ_ANDROID_APP_SECRET=Qb4PARHVWPgAmh5m
ALIPAY_APPID=2017070107614869
ALIPAY_MINIPROGRAM_APPID=2017090908631937
ALIPAY_PUB_KEY=app/Certs/Alipay/alipay_public_key.pem
ALIPAY_MCH_PUB_KEY=app/Certs/Alipay/alipay_mch_public_key.pem
ALIPAY_MCH_PRIVATE_KEY=app/Certs/Alipay/alipay_mch_private_key.pem
ALIPAY_MINIPROGRAM_PUB_KEY=app/Certs/Alipay/alipay_miniprogram_public_key.pem
ALIPAY_MINIPROGRAM_PRIVATE_KEY=app/Certs/Alipay/alipay_miniprogram_private_key.pem
SHOP_RANGE=5
SHOP_SEARCH_RANGE=20
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=suishenwan
DB_USERNAME=root
DB_PASSWORD=123123
SESSION_DRIVER=database
QUEUE_DRIVER=sync
JWT_SECRET=ieButHiml02OljSkQV2sWcMA6gHcrVxb
WECHAT_MINI_PROGRAM_ID=wx3185fb4a3633beb0
WECHAT_MINI_PROGRAM_SECRET=f60f2550f098eddfe4a8ff86bcf80fc0
TENCENT_MQ_HOST=https://cmq-queue-sh.api.qcloud.com
TENCENT_MQ_SECRET_ID=AKIDQp9OXawOAqWAjCAr9LRRL9vcEj8QMkke
TENCENT_MQ_SECRET_KEY=wnXDmFbqy1yoXhmldQ8kEf1GOPLBufMy
TENCENT_OPEN_TOPIC=test-open
\ No newline at end of file
* text=auto
*.css linguist-vendored
*.scss linguist-vendored
*.js linguist-vendored
CHANGELOG.md export-ignore
\ No newline at end of file
/node_modules
/public/storage
/public/hot
/storage/*.key
/vendor
.idea
Homestead.json
Homestead.yaml
.env
.DS_Store
Thumbs.db
*.sublime-project
*.sublime-workspace
.project
/nbproject
_ide_helper.php
composer.phar
error.log
Todo.rtf
.vagrant
/.vagrant
npm-debug.log
yarn-error.log
/public/jpush.log
\ No newline at end of file
preset: laravel
\ No newline at end of file
git:
submodules: false
language: php
cache:
directories:
- vendor
- $HOME/.composer/cache
php:
- 5.6
- 7.0
- 7.1
matrix:
fast_finish: true
include:
- php: 7.0.12 # for coverage
env: DB_CONNECTION=mysql DB_DATABASE=boilerplate_test DB_USERNAME=root DB_PASSWORD='' DB_PORT=3306 EXEC_COVERAGE=true
sudo: required
dist: trusty
exclude:
- php: 5.6
env: DB_CONNECTION=mysql DB_DATABASE=boilerplate_test DB_USERNAME=root DB_PASSWORD='' DB_PORT=3306 EXEC_COVERAGE=true
- php: 7.0
env: DB_CONNECTION=mysql DB_DATABASE=boilerplate_test DB_USERNAME=root DB_PASSWORD='' DB_PORT=3306 EXEC_COVERAGE=true
- php: 7.1
env: DB_CONNECTION=mysql DB_DATABASE=boilerplate_test DB_USERNAME=root DB_PASSWORD='' DB_PORT=3306 EXEC_COVERAGE=true
allow_failures:
- env: DB_DATABASE=sqlite
- php: 7.0.12 # dist: trusty A dummy to run trusty, the test is not actually executed
env: DB_CONNECTION=mysql DB_DATABASE=boilerplate_test DB_USERNAME=root DB_PASSWORD='' DB_PORT=3306 EXEC_COVERAGE=true
before_install:
- if [[ "$DB_CONNECTION" == "pgsql" ]]; then psql -c "DROP DATABASE IF EXISTS boilerplate_test;" -U postgres; fi
- if [[ "$DB_CONNECTION" == "pgsql" ]]; then psql -c "create database boilerplate_test;" -U postgres; fi
- if [[ "$DB_CONNECTION" == "mysql" ]]; then mysql -e "create database IF NOT EXISTS boilerplate_test;" -uroot; fi
env:
- DB_CONNECTION=mysql DB_DATABASE=boilerplate_test DB_USERNAME=root DB_PASSWORD='' DB_PORT=3306
- DB_CONNECTION=pgsql DB_DATABASE=boilerplate_test DB_USERNAME=postgres DB_PASSWORD='' DB_PORT=5432
- DB_CONNECTION=mysql DB_DATABASE=boilerplate_test DB_USERNAME=root DB_PASSWORD='' DB_PORT=3306 EXEC_COVERAGE=true
- DB_DATABASE=sqlite
before_script:
- if [[ $EXEC_COVERAGE != 'true' ]]; then phpenv config-rm xdebug.ini ; fi
- if [[ $EXEC_COVERAGE = 'true' ]]; then echo "memory_limit=-1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini ; fi
- composer self-update || true
- composer install --dev --no-interaction -o --no-scripts
- composer run-script post-root-package-install
- composer run-script post-create-project-cmd
- composer run-script post-install-cmd
script:
- if [[ $EXEC_COVERAGE = 'true' ]]; then phpdbg -qrr ./vendor/bin/phpunit --coverage-clover=coverage.clover ; fi
- if [[ $EXEC_COVERAGE != 'true' ]]; then ./vendor/bin/phpunit ; fi
after_success:
- if [[ $EXEC_COVERAGE = 'true' ]]; then php vendor/bin/coveralls -v -x coverage.clover ; fi
after_failure:
- cat storage/logs/laravel-`date +"%Y-%m-%d"`.log
\ No newline at end of file
#Suishengwan webservice project
#### Init steps
1. clone project
```
git clone git@139.224.35.235:binqi.yuan/suishenwan_webservice.git
```
2. Go to project directory, rename .env.example to .env
```
mv .env.example .env
```
3. run `composer update`
4. modify .env file to change db connections
```
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=suishenwan
DB_USERNAME=root
DB_PASSWORD=123123
```
5. run migration to create the database tables
```
php artisan migrate --seed
```
6. use git subtree to use shared components
```
//init remote
git remote add modules git@139.224.35.235:binqi.yuan/suishenwan_module.git
git remote add common git@139.224.35.235:binqi.yuan/suishenwan_common.git
git remote add db git@139.224.35.235:binqi.yuan/suishenwan_database.git
//subtree add modules
git subtree add --prefix=app/Modules modules master --squash
git subtree add --prefix=app/Common common master --squash
git subtree add --prefix=database db master --squash
```
7. use your own branch to start develop
\ No newline at end of file
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA4G2FytLndzQPksUkOlAtv1WbQYsg4M5YUcWOcFn/fJlGUNZrHWV3V+7zHP/tdm30ecaQbIodjhnzsQZ/TumF55x+4AeTeqLFuS0DELYkJn3rX/r3xNviaP+1Dkuqon/RgmAIzh0XAU2DJIZ6otooqhA2ZtonFl+T5xKH9bPBATOyupZQ1YGsS+dpGtt9Pk1zla5xTU70s7r6z5GnWKQTekGAgxYt2NT7zjEf/I8nfAmEXpvMwDOhZnNgav47lkDmogn+CXNdwMiOLGhl/G/ZdumgE9gk4QIBO/oQtrYtbNyZbCBg5eqZiN6cOXOmyfey3zYaI0TcQPte15oIHS35hQIDAQABAoIBABUqnzS64XO/qDxadYk+aKIkC8mJuqcZLwE/VajJBCyXNCeJoX6bRD853Rn+FUJXKniVvqdN+22civxGNZmWsrdebiTo8gLd+TH2ydQ4qX4r4BgkTlv1tQvcGhJoFobO8U6PiiUOX04TJmw6drSHSNCJSOg4aPlWOFfRyprkwi4/qbWloxuUSPQ0+zmdaGxaqbe79UKzigzqsVXVgSFopOZlB/OcDMWvvAd1zawW5CDteDhFomOB0zLgqsO+fTCgIVOvOpKP7TYu+uTL2eu9weRDrQhzsW3grhhPke2nTbNp78XW2mUdNld8fHib24frYsfW9718uddLyFoy5E2YjKECgYEA+/JE86Q+M7WjxwGeW6hQk2qAI526FRP0SeYajIBambLF7IniEMQaSwSSPZEqpeG2RZiG/bCyqzkb75g+vJ/APeF/ytJK+8FJcgQGUxaY4lOSPmgqa8y0XfOHbCqGvZ4IjC9B/fMBCGT1YFeTVDXa6NuFtK/xEHtoo80iUdwo4g0CgYEA5AnojBFbI757pyB16aQbhX1oVEkKbQuN8GH+/w639tD4WpWDHzREqceuU92jsy/REJAUSNJHvDSNwOg7qubgAO/l7bnZkz0Tdp9NdbHf2AhliK4sy8a5aBkfLVbpwh2eczdgLbAKL1NCE19Qw71eEzsTBzUZbOzkyvIlRVSTL1kCgYA99Y2ZcVnOs6vMRAyis9jk9/r9R0u85URdbBY5WVNumvVrv1j2EJP6wOwJ8gpP8xs1MFZ6SxsVWp0RJhq/nnXTggJAackA8r7SKEU558O/XRgI+ur7ycLNnBdAtZCfTx8BApozDrDBVLq3b7IOspPcUigmkGIzUHYiWk9HXGI9fQKBgQCkw2P6kC/By8ecIaAQiDo6YToYbA3UbBzKKoQL1Z6l/qbzDEQJL8LMyTHz9phox4vO48tEMmsSWQZy81jpSpdfFfaTpUzHTcHaW4+kEjkh5i82amKDebpMtJoKMFoFn1D0/nXHjQJO32FGjf/U7eYjDvPYqU0NnrxQxlSXm1wdQQKBgQC90UO5iFrrZK3I+dxygV+7k0Bjre5lBWG7IMKhAJgZj2NygpRJ/O3FVfbuhL4iCYBNTlb+pggp0y00g07n915j3aQ/aYk+HEoqE0pQ8zIGpIoTHM343GOH43yyeVe5/ID4K1bxCZ2H3jiNTM7UdO0YZjM3P4MYYQXU18IOlDExAQ==
-----END RSA PRIVATE KEY-----
\ No newline at end of file
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4G2FytLndzQPksUkOlAtv1WbQYsg4M5YUcWOcFn/fJlGUNZrHWV3V+7zHP/tdm30ecaQbIodjhnzsQZ/TumF55x+4AeTeqLFuS0DELYkJn3rX/r3xNviaP+1Dkuqon/RgmAIzh0XAU2DJIZ6otooqhA2ZtonFl+T5xKH9bPBATOyupZQ1YGsS+dpGtt9Pk1zla5xTU70s7r6z5GnWKQTekGAgxYt2NT7zjEf/I8nfAmEXpvMwDOhZnNgav47lkDmogn+CXNdwMiOLGhl/G/ZdumgE9gk4QIBO/oQtrYtbNyZbCBg5eqZiN6cOXOmyfey3zYaI0TcQPte15oIHS35hQIDAQAB
-----END PUBLIC KEY-----
\ No newline at end of file
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAx/lG8E1hDTDEFoYQtJMjCO0XHoaphq5MFv1WZtBvo6vJ4GSjwkF8z9yS2s54z/oLbR2m0ddo0Q8+rv2KTCBhvZz5zd/72Ynwu8WXemgGnHyhjyq13Q4gkcymukonP0XECQvlVCr3pu3YLv0uVzC7B+zTby5rdOqW9DgwfkS8QWHa3HonBxg1dknhAmS3Rl43sWPv71C5V9O24Ud865PbhMP3kPnIeNXkngQHFfq8LRgKNr7YK8Cww4AgN2wUenGLIZrnYl2rXTHTNcjFHqvUb/egQrjM+CxKoKqNnXRPpz+0DIa66Vh46uRr+vJYcayptBk42HYF8lWKbtzfGp8F0QIDAQABAoIBAQCTYNgzShP40LPzlaLCMp5jebjMOpq+M77IQrVm2L8udPE3e3RlOjZuSzXAJONNBA9fv7aueH87dGzSMvG14TenswU4AZdvYAYXnSxifkBBHGlFRkj6PesrCRTnvrbmHti3ghjlyzTxxeDJ4LZCdBujX5sEGcYASNQv8SlsJeRImjRagDEOuvRFr08iDvooISEXgG7TfZStm2b32x4vOVRyoSmnUSgujr2xmX6zLQva0QDgCrO9oiNkGCRZOrsRyuu7RHpnKKFb/Aermo3ne8Pn5oBYD6Xyop9vcRsCkjwlrTapXpvcXnxMQE2YQTJkrTaj7rj9xt2oxtGWtf/iG/cxAoGBAOQSVmzX3/Mjw5xoU2LO5O+70yVAqEuqf6AV6csJXzqfHqlTp4BJMryLQqXJ2lXCkNHJdhslwy5Hvh2NDPXLGIt7fjPrB+ghXyi05N0i7SzRhxqBYbDgxkXlpeOHwjStvOIl3PG7f/ri0XJUHnJ895BWUFIFMdVYjUQcFy+oYVPXAoGBAOB2Hidf2rnvHbN/ARbG6sM9HD0KON5n+upRqYT3xPcp1xrYn7BY5lyg2P8HKV+Gzjk/iPTzDEf/7SFrr4MGlBk0mg18nn/7POJOVe/8iqGUFK3f9E2gKXqo6Ouz+Xlh5YzmXBQLbJ50TRkcWa7CnKh8sDgQbnegGP6y5iFLS76XAoGAAxVUYchRWMIlBNpMNkvBwJPzeM909wDpFMr3DC2mQe6gxX1CCHP04aOoVQFzmDE3L/7fP+K0zs1dfpzHjhMe09Ppkt4cj0DUPoKjjXHJbw+uGeeh4HhJdexy366YK4olwZDteb8lLckfN8J3Xujdl+/yygkT8WRvFHqkvZozJqUCgYAtaji3psFOlX7g7nV98klVr2ujPgo7lbZC6rrt2GPVznVjTSkiORqC61h8YSqR1WisVJqVVQfLGZEVDgC49f/JCceRqwE2y9KJx2fD4sj54Eg+1e1MN3etBbf62LNFR/V2CLXgqF8VwFpJFl9e6Klhvbi53zk6ov3rqq69VcrBiQKBgQDQySqesjCSvhcG3m8abK283JiIgs+og5iJHE1EeLDKJJViUX0xLOKhQIq7NgutVJ/lKehwaSqmULxc6vWLn717VyJ+GVqCeszyHALOpNvjOMgcQTU08ZshNPgoCjt18GhQ5ZruietF2OvzuHkVHLg+MnHrKn01HyEhB0NU/bY19A==
-----END RSA PRIVATE KEY-----
\ No newline at end of file
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx/lG8E1hDTDEFoYQtJMjCO0XHoaphq5MFv1WZtBvo6vJ4GSjwkF8z9yS2s54z/oLbR2m0ddo0Q8+rv2KTCBhvZz5zd/72Ynwu8WXemgGnHyhjyq13Q4gkcymukonP0XECQvlVCr3pu3YLv0uVzC7B+zTby5rdOqW9DgwfkS8QWHa3HonBxg1dknhAmS3Rl43sWPv71C5V9O24Ud865PbhMP3kPnIeNXkngQHFfq8LRgKNr7YK8Cww4AgN2wUenGLIZrnYl2rXTHTNcjFHqvUb/egQrjM+CxKoKqNnXRPpz+0DIa66Vh46uRr+vJYcayptBk42HYF8lWKbtzfGp8F0QIDAQAB
-----END PUBLIC KEY-----
\ No newline at end of file
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2J8XSVliMFk51D6BTB2otLINtmIJYWjgDzOhSJbENz8zevWbMFndLfbkBdutmHrlsZM1wSn7tR3wugs0px1EaX9c9hBuET+7fIlya8sc7iUaJiI+S5sL60vK2A5yM8Rlx2yJNg4MYgMjty0wFogQd2V9aCThriW796rYLuqIHrgt5DWSaBYYuvZDQjYdvnd1p4agJOEux1LfVjtkcgu9UBfwg5oWL5RZpWiI5tR7MG0JOzZbrAY+EPOtOnh5tWoEjOZiQD6E0XcmOO4jOxI7x5DJ2om+AHHU3cpVUqRt/F6tKbnxuv8R406ZQZyJ5omK3/8G+ibb8keYuv+qMzHANwIDAQAB
-----END PUBLIC KEY-----
\ No newline at end of file
-----BEGIN CERTIFICATE-----
MIIEbDCCA9WgAwIBAgIEAWJK2zANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMC
Q04xEjAQBgNVBAgTCUd1YW5nZG9uZzERMA8GA1UEBxMIU2hlbnpoZW4xEDAOBgNV
BAoTB1RlbmNlbnQxDDAKBgNVBAsTA1dYRzETMBEGA1UEAxMKTW1wYXltY2hDQTEf
MB0GCSqGSIb3DQEJARYQbW1wYXltY2hAdGVuY2VudDAeFw0xNzA4MDcwOTAwNDZa
Fw0yNzA4MDUwOTAwNDZaMIGbMQswCQYDVQQGEwJDTjESMBAGA1UECBMJR3Vhbmdk
b25nMREwDwYDVQQHEwhTaGVuemhlbjEQMA4GA1UEChMHVGVuY2VudDEOMAwGA1UE
CxMFTU1QYXkxMDAuBgNVBAMUJ+iLj+W3numaj+i6q+eOqeS/oeaBr+aKgOacr+ac
iemZkOWFrOWPuDERMA8GA1UEBBMINDEyOTEyMTcwggEiMA0GCSqGSIb3DQEBAQUA
A4IBDwAwggEKAoIBAQDeUEFC0H3NiPALgWZQGtAEFoyiAMEcGKWKxDAXA+7RTzkH
Y6rRqWa4UtmLn+y2Dq3Bqj0JV9/hpxH4XDGmyVEPoeX1vrvjY+hZa5vsHo5iAowC
+/5tfbSK0MCIqLVu32RUL/2XNKzu1uI9qJCyG5S5xviwY+LUsIiQVSYS68xxPmQi
UvB/Si7nPVu8flQp/CErGj67+UnfRstzdlXmIedVZI2B/zDY36GWz99OcC1vKAoH
1Qyr0djSPKUjBW728SgKgt7koS1DV4tQdd+Z3d0JUMaf1xC3HQgYxrIsOAo/mRki
fCvRG19WB6UgQn57pAPQ1aRmc8uHoc4K0t5PG3z3AgMBAAGjggFGMIIBQjAJBgNV
HRMEAjAAMCwGCWCGSAGG+EIBDQQfFh0iQ0VTLUNBIEdlbmVyYXRlIENlcnRpZmlj
YXRlIjAdBgNVHQ4EFgQUkwjPtBG/QHSUDjRnzQs7jkYgkHwwgb8GA1UdIwSBtzCB
tIAUPgUm9iJitBVbiM1kfrDUYqflhnShgZCkgY0wgYoxCzAJBgNVBAYTAkNOMRIw
EAYDVQQIEwlHdWFuZ2RvbmcxETAPBgNVBAcTCFNoZW56aGVuMRAwDgYDVQQKEwdU
ZW5jZW50MQwwCgYDVQQLEwNXWEcxEzARBgNVBAMTCk1tcGF5bWNoQ0ExHzAdBgkq
hkiG9w0BCQEWEG1tcGF5bWNoQHRlbmNlbnSCCQC7VJcrvADoVzAOBgNVHQ8BAf8E
BAMCBsAwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwIwDQYJKoZIhvcNAQEFBQADgYEA
NkWBjd8qNtg5LT8u+lns5kmoqMgJmPqWsLkeAdDzGQgk0umVIivnbvjBK9gyQDo8
M3uQjHDOeoL9kpYQoZCzcC/0NqMluXjmvfXiarc1lv2RYu4nNoUVp4ix/15dFhML
pS65pTZ3LXXDigY76nFOu6XztJNvylnDZ/c7nejsC3g=
-----END CERTIFICATE-----
-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDeUEFC0H3NiPAL
gWZQGtAEFoyiAMEcGKWKxDAXA+7RTzkHY6rRqWa4UtmLn+y2Dq3Bqj0JV9/hpxH4
XDGmyVEPoeX1vrvjY+hZa5vsHo5iAowC+/5tfbSK0MCIqLVu32RUL/2XNKzu1uI9
qJCyG5S5xviwY+LUsIiQVSYS68xxPmQiUvB/Si7nPVu8flQp/CErGj67+UnfRstz
dlXmIedVZI2B/zDY36GWz99OcC1vKAoH1Qyr0djSPKUjBW728SgKgt7koS1DV4tQ
dd+Z3d0JUMaf1xC3HQgYxrIsOAo/mRkifCvRG19WB6UgQn57pAPQ1aRmc8uHoc4K
0t5PG3z3AgMBAAECggEAIepAan8AEjEH3dl50FKm1VjTT4up6i1gY9EWPQyejFP3
sUblMmMThp8tDP3y0LtgiqD7+sbrIrOoLCl0catYsHfUay8T3tbJBYtDGDx5ID6f
OX1UDUQWHO9H0BFczHNMDQPdPgoNL8qcbSegG2vVvpm6Kr6yRhxAWTSEQHK0l7nS
F30WM0uTtu4iaJi71MCvZZSHiRkr1hJettfeECJYZoCxxKpI/+DXV2bi1xVbyBTl
k4/n6sBV7lSS5ELsm4RGkV9YIMuHmjeV0qGn4pnvt79tCK72KAP5a06OorrVHUqH
IKymJqi8MTPceI4h2D2Q3XN0YUUjAsko2bg54kQBgQKBgQD4dck0IizWQdu2fb3W
n/42I7XEA9YtgXuiQRAnSgzTi6Yk98vcVyDDUi4xfw8JzxvPSpIlItJVEEiQSJOt
9nK6VXW5ZAGiG6C2RKrtZ4bWEYmp57C0mu3Q3X7NBez/mRkvkc2p64ZN4o9p4pBL
NKow0EFH+0LaTVHkgef39Qh91wKBgQDlD1f3p8jtClIYMYKrLjW7wUmd2+o+VpFT
Dkfx39Kx9GzS0UdpwUAXdrWX8a9q33raMj0hih5GSc0hYOA+TVZ7feZxwDwvfsra
uY/9Z7ShoYKs35Tz0i6quqQtbOz47bDo63uvivf8C/juXR+tdJFt8Dw7he9v7IT5
sduzVXfV4QKBgQCGJFmf+v+IIgB0k4jF8pV2N2twS737zZepb0VAYRtxr0jhVqPK
74Nx0NG9yWKeIiJalWE4CYfTgzoaJAUPfCpO7crkb9jt48qt/X7nM+i5dLiFceCW
cbsJ9Dv8h0GAcfEGHMsT/WQCctqJCVhsMh/cwOMt8LsUT4ByRayu061k+wKBgQC0
Pz22uUZoGS3+sb8kWwmXhIMcgHg0s8RJujws/jb7J98Wie6LLrHzhMtjFKE4FUHE
P7JRGTG3l82ejXAINq1uIeVb76yspzaTpV/ERX4jjkeZJ5s7vlJQsOwOft9/BvOm
Zd9/hHid0wIA+DC8OrVR8LBFGqEOzuzY2/eJiCDzoQKBgQDmPl4D02GIeORgO46R
/SVVMdK4/wz9OhwaWX2NNkHi6d5YZjR+e0w7XmmmT1n8C+Dcf0i3EdSCH2ci9kYU
dQ5A0wHPVYX1tw6yeqQYXYyfVHwcLCZO4sTJXUwD2OZ4AncjhI3PG1YnhJUov0Y8
dVXi8bkgyP/Wo47YevasN7t2qQ==
-----END PRIVATE KEY-----
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 13/03/2017
* Time: 1:40 PM
*/
namespace App\Common;
/**
* Class Alipay
* @package App\Common
*/
/**
* Class Alipay
* @package App\Common
*/
use App\Common\Enums\AlipayLoginType;
use App\Common\Util\OrderUtil;
use Illuminate\Support\Facades\Log;
/**
* Class Alipay
* @package App\Common
*/
class Alipay
{
/**
* order Id
* @var
*/
private $order_id;
/**
* Order price
* @var
*/
private $price;
/**
* pay description
* @var
*/
private $body;
/**
* @var
*/
private $subject;
/**
* Callback Url
* @var
*/
private $call_back_url;
/**
* @var
*/
private $refund_fee;
/**
* @var
*/
private $refund_id;
/**
* @var
*/
private $op_user_id;
/**
* @var
*/
private $pay_no;
/**
* WechatPay constructor.
* @param $order_id
* @param $price
* @param $body
* @param $call_back_url
*/
public function __construct($order_id="", $price=0, $body="", $call_back_url="", $subject="")
{
$this->order_id = $order_id;
$this->price = $price;
$this->body = $body;
$this->call_back_url = $call_back_url;
$this->subject = $subject;
}
/**
* @param mixed $refund_fee
*/
public function setRefundFee($refund_fee)
{
$this->refund_fee = $refund_fee;
}
/**
* @param mixed $op_user_id
*/
public function setOpUserId($op_user_id)
{
$this->op_user_id = $op_user_id;
}
/**
* @param mixed $refund_id
*/
public function setRefundId($refund_id)
{
$this->refund_id = $refund_id;
}
/**
* @param mixed $pay_no
*/
public function setPayNo($pay_no)
{
$this->pay_no = $pay_no;
}
/**
* @param $success
* @param $error_messge
* @param string $payInfo
* @return array
*/
private function response($success, $error_messge, $payInfo="")
{
$result = array('success'=>$success, 'error_message'=>$error_messge, 'payInfo'=>$payInfo);
return $result;
}
/**
* @param $type
* @return \AopClient
*/
private function getAopClient($type = AlipayLoginType::APP)
{
$aop = new \AopClient();
$aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
$aop->appId = $type == AlipayLoginType::APP ? config('constants.alipay.app_id') : config('constants.alipay.app_miniprogram_id');
$aop->rsaPrivateKeyFilePath = $type == AlipayLoginType::APP ? config('constants.alipay.alipay_mch_private_key') : config('constants.alipay.alipay_miniprogram_private_key');
$aop->format = "json";
$aop->charset = "UTF-8";
$aop->signType = "RSA2";
$aop->alipayPublicKey=config('constants.alipay.alipay_pub_key');
return $aop;
}
/**
* 获取第三方登录字串
*
* @return string
*/
public function getAppAuthCode()
{
$params = array(
"apiname" => 'com.alipay.account.auth',
"method" => 'alipay.open.auth.sdk.code.get',
"app_id"=> config('constants.alipay.app_id'),
"app_name"=>'mc',
"biz_type" => 'openservice',
'pid' => '2088721389489661',
'product_id' => 'APP_FAST_LOGIN',
'scope' => 'kuaijie',
'target_id' => OrderUtil::generateCosumeOrderId(),
"auth_type" => 'AUTHACCOUNT',
"sign_type" => 'RSA2'
);
$aop = $this->getAopClient();
$sign = $aop->generateSign($params, 'RSA2');
$params['sign'] = $sign;
return http_build_query($params);
}
/**
* 无线账户授权
*
* @param $code
* @param $type
* @return bool|mixed|\SimpleXMLElement
*/
public function alipaySystemAccountAuth($code, $type = AlipayLoginType::APP)
{
$aop = $this->getAopClient($type);
$request = new \AlipaySystemOauthTokenRequest();
$request->setCode($code);
$request->setGrantType('authorization_code');
$response = $aop->execute($request);
Log::info('response is $response!');
if (isset($response->alipay_system_oauth_token_response))
{
return ['access_token' => $response->alipay_system_oauth_token_response->access_token, 'user_id'=> $response->alipay_system_oauth_token_response->user_id];
}
return false;
}
/**
* 用户信息共享
*
* @param $access_token
* @param $type
* @return bool|mixed|\SimpleXMLElement
*/
public function alipayUserInfoShare($access_token, $type = AlipayLoginType::APP)
{
$aop = $this->getAopClient($type);
$request = new \AlipayUserInfoShareRequest();
$response = $aop->execute($request, $access_token);
Log::info('response is $response!');
if (isset($response->alipay_user_info_share_response))
{
return (array)$response->alipay_user_info_share_response;
}
return false;
}
/**
* @param $property_id
* @return array|bool
*/
public function alipayTradePrecreate($property_id)
{
$aop = $this->getAopClient();
$bizContent = $this->getPrecreateAppBizContent($property_id);
$request = new \AlipayTradePrecreateRequest();
$request->setNotifyUrl($this->call_back_url);
$request->setBizContent($bizContent);
$response = $aop->execute($request);
if (isset($response->alipay_trade_precreate_response))
{
return (array)$response->alipay_trade_precreate_response;
}
return false;
}
/**
* @param $property_id
*
* @return string
*/
private function getPrecreateAppBizContent($property_id)
{
$param = array(
"out_trade_no"=>$this->order_id,
"subject" => "优卡充充值",
'store_id' => $property_id,
"total_amount" => $this->price,
"timeout_express" => "10m",
);
return json_encode($param);
}
/**
* @return mixed
*/
public function getUnifiedOrderInfo()
{
$aop = $this->getAopClient();
$request = new \AlipayTradeAppPayRequest();
$bizContent = $this->getAppBizContent();
$request->setNotifyUrl($this->call_back_url);
$request->setBizContent($bizContent);
$response = $aop->sdkExecute($request);
return $this->response("success", "", $response);
}
/**
* @return string
*/
private function getAppBizContent()
{
$param = array(
"body" => $this->body,
"subject" => $this->body,
"out_trade_no"=>$this->order_id,
"timeout_express" => "40m",
"total_amount" => $this->price,
"product_code" => "QUICK_MSECURITY_PAY"
);
return json_encode($param);
}
/**
* @param $input
* @return bool
*/
public function checkSign($input)
{
$aop = new \AopClient();
$aop->alipayPublicKey=config('constants.alipay.alipay_pub_key');
$flag = $aop->rsaCheckV1($input, config('constants.alipay.alipay_pub_key'), "RSA2");
return $flag;
}
/**
*
*/
public function refund()
{
$aop = new \AopClient();
$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
$aop->appId = config('constants.alipay.app_id');
$aop->rsaPrivateKeyFilePath = config('constants.alipay.alipay_mch_private_key');
$aop->alipayPublicKey= config('constants.alipay.alipay_pub_key');
$aop->postCharset='UTF-8';
$aop->format='json';
$request = new \AlipayTradeRefundRequest();
$bizContent = $this->getRefundBizContent();
$request->setBizContent($bizContent);
$response = $aop->execute ( $request);
$this->response(true, "", htmlspecialchars($response));
}
/**
* @return string
*/
private function getRefundBizContent()
{
$param = array(
"out_trade_no" => $this->order_id,
"trade_no" => $this->pay_no,
"refund_amount"=>$this->refund_fee,
"refund_reason" => "refund",
"out_request_no" => $this->refund_id,
"operator_id" => "OP001",
"store_id" => "NJ_S_001",
"terminal_id" => "NJ_T_001"
);
return json_encode($param);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 25/04/2017
* Time: 11:47 AM
*/
namespace App\Common;
class Amap
{
public static function getAdCodeUsingLatAndLng($lat, $lng)
{
$url = config('constants.amap.url').'?key='.config('constants.amap.key').'&location='.$lng.','.$lat;
$result = Http::Get($url);
$result = json_decode($result, true);
return $result['regeocode']['addressComponent']['adcode'];
}
}
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 20/03/2017
* Time: 2:17 PM
*/
namespace App\Common;
class Byte
{
/**
* 转换一个String字符串为byte数组(10进制)
* @param $str
* @return array
*/
public static function getBytes_10($str) {
$len = strlen($str);
$bytes = array();
for($i=0;$i<$len;$i++) {
if(ord($str[$i]) >= 128){
$byte = ord($str[$i]) - 256;
}else{
$byte = ord($str[$i]);
}
$bytes[] = $byte ;
}
return $bytes;
}
/**
* 转换一个String字符串为byte数组(16进制)
* @param $str
* @return array
*/
public static function getBytes_16($str) {
$len = strlen($str);
$bytes = array();
for($i=0;$i<$len;$i++) {
if(ord($str[$i]) >= 128){
$byte = ord($str[$i]) - 256;
}else{
$byte = ord($str[$i]);
}
$bytes[] = "0x".dechex($byte) ;
}
return $bytes;
}
/**
* 转换一个String字符串为byte数组(2进制)
* @param $str
* @return array
*/
public static function StrToBin($str){
//1.列出每个字符
$arr = preg_split('/(?<!^)(?!$)/u', $str);
//2.unpack字符
foreach($arr as &$v){
$temp = unpack('H*', $v);
$v = base_convert($temp[1], 16, 2);
unset($temp);
}
return $arr;
}
/**
* 转换一个byte数组为String(2进制)
* @param $str 需要转换的字符串
* @return string
*/
function BinToStr($str){
$arr = explode(' ', $str);
foreach($arr as &$v){
$v = pack("H".strlen(base_convert($v, 2, 16)), base_convert($v, 2, 16));
}
return $v;
}
/**
* 将字节数组转化为String类型的数据
* @param $bytes
* @return string
*/
public static function toStr($bytes) {
$str = '';
foreach($bytes as $ch) {
$str .= chr($ch);
}
return $str;
}
/**
* 转换一个int为byte数组
* @param $val
* @return array
*/
public static function integerToBytes($val) {
$byt = array();
$byt[0] = ($val & 0xff);
$byt[1] = ($val >> 8 & 0xff);
$byt[2] = ($val >> 16 & 0xff);
$byt[3] = ($val >> 24 & 0xff);
return $byt;
}
/**
* 从字节数组中指定的位置读取一个Integer类型的数据
* @param $bytes 字节数组
* @param $position 指定的开始位置
* @return 一个Integer类型的数据
*/
public static function bytesToInteger($bytes, $position) {
$val = 0;
$val = $bytes[$position + 3] & 0xff;
$val <<= 8;
$val |= $bytes[$position + 2] & 0xff;
$val <<= 8;
$val |= $bytes[$position + 1] & 0xff;
$val <<= 8;
$val |= $bytes[$position] & 0xff;
return $val;
}
/**
* 转换一个short字符串为byte数组
* @param $val
* @return array
*/
public static function shortToBytes($val) {
$byt = array();
$byt[0] = ($val & 0xff);
$byt[1] = ($val >> 8 & 0xff);
return $byt;
}
/**
* 从字节数组中指定的位置读取一个Short类型的数据。
* @param $bytes
* @param $position
* @return short
*/
public static function bytesToShort($bytes, $position) {
$val = 0;
$val = $bytes[$position + 1] & 0xFF;
$val = $val << 8;
$val |= $bytes[$position] & 0xFF;
return $val;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 24/02/2017
* Time: 5:11 PM
*/
namespace App\Common;
class CropAvatar {
private $src;
private $data;
private $file;
private $dst;
private $type;
private $extension;
private $msg;
private $imgWidth;
private $imgHeight;
function __construct($src, $data, $file, $imgWidth, $imgHeight) {
$this ->imgWidth = $imgWidth;
$this ->imgHeight = $imgHeight;
$this -> setSrc($src);
$this -> setData($data);
$this -> setFile($file);
$this -> crop($this -> src, $this -> dst, $this -> data);
}
private function setSrc($src) {
if (!empty($src)) {
$type = exif_imagetype($src);
if ($type) {
$this -> src = $src;
$this -> type = $type;
$this -> extension = image_type_to_extension($type);
$this -> setDst();
}
}
}
private function setData($data) {
if (!empty($data)) {
$this -> data = json_decode(stripslashes($data));
}
}
private function setFile($file) {
$errorCode = $file['error'];
if ($errorCode === UPLOAD_ERR_OK) {
$type = exif_imagetype($file['tmp_name']);
if ($type) {
$extension = image_type_to_extension($type);
$src = config("constants.common.temp_file_location") . date('YmdHis') . '.original' . $extension;
if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_JPEG || $type == IMAGETYPE_PNG) {
if (file_exists($src)) {
unlink($src);
}
$result = move_uploaded_file($file['tmp_name'], $src);
if ($result) {
$this -> src = $src;
$this -> type = $type;
$this -> extension = $extension;
$this -> setDst();
} else {
$this -> msg = 'Failed to save file';
}
} else {
$this -> msg = 'Please upload image with the following types: JPG, PNG, GIF';
}
} else {
$this -> msg = 'Please upload image file';
}
} else {
$this -> msg = $this -> codeToMessage($errorCode);
}
}
private function setDst() {
$this -> dst = config("constants.common.temp_file_location") . date('YmdHis') . '.png';
}
private function crop($src, $dst, $data) {
if (!empty($src) && !empty($dst) && !empty($data)) {
switch ($this -> type) {
case IMAGETYPE_GIF:
$src_img = imagecreatefromgif($src);
break;
case IMAGETYPE_JPEG:
$src_img = imagecreatefromjpeg($src);
break;
case IMAGETYPE_PNG:
$src_img = imagecreatefrompng($src);
break;
}
if (!$src_img) {
$this -> msg = "Failed to read the image file";
return;
}
$size = getimagesize($src);
$size_w = $size[0]; // natural width
$size_h = $size[1]; // natural height
$src_img_w = $size_w;
$src_img_h = $size_h;
$degrees = $data -> rotate;
// Rotate the source image
if (is_numeric($degrees) && $degrees != 0) {
// PHP's degrees is opposite to CSS's degrees
$new_img = imagerotate( $src_img, -$degrees, imagecolorallocatealpha($src_img, 0, 0, 0, 127) );
imagedestroy($src_img);
$src_img = $new_img;
$deg = abs($degrees) % 180;
$arc = ($deg > 90 ? (180 - $deg) : $deg) * M_PI / 180;
$src_img_w = $size_w * cos($arc) + $size_h * sin($arc);
$src_img_h = $size_w * sin($arc) + $size_h * cos($arc);
// Fix rotated image miss 1px issue when degrees < 0
$src_img_w -= 1;
$src_img_h -= 1;
}
$tmp_img_w = $data -> width;
$tmp_img_h = $data -> height;
$dst_img_w = $this ->imgWidth;
$dst_img_h = $this ->imgHeight;
$src_x = $data -> x;
$src_y = $data -> y;
if ($src_x <= -$tmp_img_w || $src_x > $src_img_w) {
$src_x = $src_w = $dst_x = $dst_w = 0;
} else if ($src_x <= 0) {
$dst_x = -$src_x;
$src_x = 0;
$src_w = $dst_w = min($src_img_w, $tmp_img_w + $src_x);
} else if ($src_x <= $src_img_w) {
$dst_x = 0;
$src_w = $dst_w = min($tmp_img_w, $src_img_w - $src_x);
}
if ($src_w <= 0 || $src_y <= -$tmp_img_h || $src_y > $src_img_h) {
$src_y = $src_h = $dst_y = $dst_h = 0;
} else if ($src_y <= 0) {
$dst_y = -$src_y;
$src_y = 0;
$src_h = $dst_h = min($src_img_h, $tmp_img_h + $src_y);
} else if ($src_y <= $src_img_h) {
$dst_y = 0;
$src_h = $dst_h = min($tmp_img_h, $src_img_h - $src_y);
}
// Scale to destination position and size
$ratio = $tmp_img_w / $dst_img_w;
$dst_x /= $ratio;
$dst_y /= $ratio;
$dst_w /= $ratio;
$dst_h /= $ratio;
$dst_img = imagecreatetruecolor($dst_img_w, $dst_img_h);
// Add transparent background to destination image
imagefill($dst_img, 0, 0, imagecolorallocatealpha($dst_img, 0, 0, 0, 127));
imagesavealpha($dst_img, true);
$result = imagecopyresampled($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
if ($result) {
if (!imagepng($dst_img, $dst)) {
$this -> msg = "Failed to save the cropped image file";
}
} else {
$this -> msg = "Failed to crop the image file";
}
imagedestroy($src_img);
imagedestroy($dst_img);
}
}
private function codeToMessage($code) {
switch ($code) {
case UPLOAD_ERR_INI_SIZE:
$message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
break;
case UPLOAD_ERR_FORM_SIZE:
$message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
break;
case UPLOAD_ERR_PARTIAL:
$message = 'The uploaded file was only partially uploaded';
break;
case UPLOAD_ERR_NO_FILE:
$message = 'No file was uploaded';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = 'Missing a temporary folder';
break;
case UPLOAD_ERR_CANT_WRITE:
$message = 'Failed to write file to disk';
break;
case UPLOAD_ERR_EXTENSION:
$message = 'File upload stopped by extension';
break;
default:
$message = 'Unknown upload error';
}
return $message;
}
public function getResult() {
return !empty($this -> data) ? $this -> dst : $this -> src;
}
public function getMsg() {
return $this -> msg;
}
public function getSrc() {
return $this -> src;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 30/08/2017
* Time: 7:50 PM
*/
namespace App\Common\Enums;
class AlipayLoginType
{
const APP = 1;
const MINIPROGRAM = 2;
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: machengjun
* Date: 2018/2/10
* Time: 下午2:42
*/
namespace App\Common\Enums;
class HtTab
{
const GUIDE_PERMISSION = 'G_P';
const GUIDE_ORDER = 'G';
const RENT_ORDER = 'R';
const RENT_REFUND = 'RF';
const IMG_HEAD_URL = 'https://dev-1255927177.cos.ap-shanghai.myqcloud.com';
const AUDIO_HEAD_URL = 'https://dev-1255927177.cos.ap-shanghai.myqcloud.com';
const RENT_SALE_LOCK = 'R_S_L';
const DEFAULT_LIMIT = 10;
const RENT_PRODUCTION_NAME = '晓兔智能讲解器';
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 11/02/2017
* Time: 9:47 AM
*/
namespace App\Common\Enums;
class LoginType
{
const PASSWORD = 1;
const SMS = 2;
const QQ = 3;
const WECHAT = 4;
const ALIPAY = 5;
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 11/03/2017
* Time: 11:26 AM
*/
namespace App\Common\Enums;
class PayMethod
{
const ALIPAY = 1;
const WECHATPAY = 2;
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 11/03/2017
* Time: 1:19 PM
*/
namespace App\Common\Enums;
class PaySource
{
const APP = 1;
const JS = 2;
const MINI_PROGRAM = 3;
const NATIVE = 4;
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 11/02/2017
* Time: 9:47 AM
*/
namespace App\Common\Enums;
class SmsType
{
const REGISTER = 1;
const RESET_PASSWORD = 2;
const SMS_LOGIN = 3;
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 10/02/2017
* Time: 5:47 PM
*/
namespace App\Common;
class Http
{
public static function Post($curlPost, $url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
$return_str = curl_exec($curl);
curl_close($curl);
return $return_str;
}
public static function Get($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
$return_str = curl_exec($curl);
curl_close($curl);
return $return_str;
}
public static function PostWithHeader($curlPost, $curlHeader, $url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $curlHeader);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
$return_str = curl_exec($curl);
curl_close($curl);
return $return_str;
}
public static function GetWithHeader($curlHeader, $url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, $curlHeader);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
$return_str = curl_exec($curl);
curl_close($curl);
return $return_str;
}
public static function WechatPostWithSecurity($curlPost, $url, $useCert=false)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
if($useCert == true){
//设置证书
//使用证书:cert 与 key 分别属于两个.pem文件
curl_setopt($curl,CURLOPT_SSLCERTTYPE,'PEM');
curl_setopt($curl,CURLOPT_SSLCERT, config('constants.wechat.ssl_cert_path'));
curl_setopt($curl,CURLOPT_SSLKEYTYPE,'PEM');
curl_setopt($curl,CURLOPT_SSLKEY, config('constants.wechat.ssl_key_path'));
}
$return_str = curl_exec($curl);
curl_close($curl);
return $return_str;
}
public static function DeleteWithHeader($curlHeader, $url)
{
$curl = curl_init();
curl_setopt($curl,CURLOPT_HTTPHEADER,$curlHeader);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_CUSTOMREQUEST,'DELETE');
ob_start();
curl_exec($curl);
$result = ob_get_contents();
ob_end_clean();
curl_close($curl);
return $result;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 12/02/2017
* Time: 10:58 PM
*/
namespace App\Common;
use Exception;
class Jpush
{
public static function pushNotification($userIds, $title, $msg, $params)
{
$client = new \JPush(config('constants.jpush.access_key'), config('constants.jpush.secret'));
try
{
$res = $client->push()
->setPlatform('all')
->addAlias($userIds)
->addIosNotification($msg, 'iOS sound', "+1", true, 'iOS category', $params)
->setMessage($msg, $title, null, $params)
->setOptions(null, 864000, null, (bool)config('constants.jpush.production'))
->send();
}
catch(Exception $e)
{
$res = 'false';
}
return $res;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 25/04/2017
* Time: 8:49 PM
*/
namespace App\Common\MQ;
class CheckoutMessageHandler extends HttpConsumer
{
/**
* UnlockMessageHandler constructor.
*/
public function __construct()
{
parent::__construct(config('constants.mq.url'),
config('constants.mq.ak'),
config('constants.mq.sk'),
config('constants.mq.checkout.consumer'),
config('constants.mq.checkout.topic'));
}
protected function handleMessage()
{
return true;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 25/04/2017
* Time: 8:49 PM
*/
namespace App\Common\MQ;
class CmdStatusMessageHandler extends HttpConsumer
{
/**
* UnlockMessageHandler constructor.
*/
public function __construct()
{
parent::__construct(config('constants.mq.url'),
config('constants.mq.ak'),
config('constants.mq.sk'),
config('constants.mq.cmd_status.consumer'),
config('constants.mq.cmd_status.topic'));
}
protected function handleMessage()
{
return true;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 25/04/2017
* Time: 8:17 PM
*/
namespace App\Common\MQ;
use App\Common\Http;
class HttpConsumer
{
//签名
private static $signature = "Signature";
//Consumer ID
private static $consumerid = "ConsumerID";
//访问码
private static $aks = "AccessKey";
/**
* @var
*/
private $url;
/**
* @var
*/
private $ak;
/**
* @var
*/
private $sk;
/**
* @var
*/
private $cid;
/**
* @var
*/
private $topic;
/**
* HttpConsumer constructor.
* @param $url
* @param $ak
* @param $sk
* @param $cid
* @param $topic
*/
public function __construct($url, $ak, $sk, $cid, $topic)
{
$this->url = $url;
$this->ak = $ak;
$this->sk = $sk;
$this->cid = $cid;
$this->topic = $topic;
}
protected function handleMessage()
{
return true;
}
public function consume()
{
$newline = "\n";
while (true)
{
try
{
//构造时间戳
$date = time()*1000;
//签名字符串
$signString = $this->topic.$newline.$this->cid.$newline.$date;
//计算签名
$sign = Util::calSignature($signString,$this->sk);
//构造签名标记
$signFlag = $this::$signature.":".$sign;
//构造密钥标记
$akFlag = $this::$aks.":".$this->ak;
//标记
$consumerFlag = $this::$consumerid.":".$this->cid;
//构造HTTP请求发送内容类型标记
$contentFlag = "Content-Type:text/html;charset=UTF-8";
//构造HTTP头部信息
$headers = array(
$signFlag,
$akFlag,
$consumerFlag,
$contentFlag,
);
//构造HTTP请求URL
$getUrl = $this->url."/message/?topic=".$this->topic."&time=".$date."&num=32";
$result = Http::GetWithHeader($headers, $getUrl);
//解析HTTP应答信息
$messages = json_decode($result,true);
//如果应答信息中的没有包含任何的Topic信息,则直接跳过
if (count($messages) ==0)
{
continue;
}
//依次遍历每个Topic消息
foreach ((array)$messages as $message)
{
var_dump($message);
if ($this->handleMessage())
{
//构造删除Topic消息URL
$delUrl = $this->url."/message/?msgHandle=".$message['msgHandle']."&topic=".$this->topic."&time=".$date;
//签名字符串
$signString = $this->topic.$newline.$this->cid.$newline.$message['msgHandle'].$newline.$date;
//计算签名
$sign = Util::calSignature($signString,$this->sk);
//构造签名标记
$signFlag = $this::$signature.":".$sign;
//构造密钥标记
$akFlag = $this::$aks.":".$this->ak;
//构造消费者组标记
$consumerFlag = $this::$consumerid.":".$this->cid;
//构造HTTP请求头部信息
$delHeaders = array(
$signFlag,
$akFlag,
$consumerFlag,
$contentFlag,
);
$result = Http::DeleteWithHeader($delHeaders, $delUrl);
}
}
}
catch (\Exception $e)
{
//打印异常信息
echo $e->getMessage();
}
}
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 25/04/2017
* Time: 7:58 PM
*/
namespace App\Common\MQ;
use App\Common\Http;
/**
* Class HttpProducer
* @package App\Common\MQ
*/
class HttpProducer
{
//签名
private static $signature = "Signature";
//在MQ控制台创建的Producer ID
private static $producerId = "ProducerID";
//阿里云身份验证码
private static $aks = "AccessKey";
/**
* @var
*/
private $url;
/**
* @var
*/
private $ak;
/**
* @var
*/
private $sk;
/**
* @var
*/
private $pid;
/**
* @var
*/
private $topic;
/**
* @var
*/
private $content;
/**
* @var
*/
private $tag;
/**
* @var
*/
private $key;
/**
* HttpProducer constructor.
* @param $url
* @param $ak
* @param $sk
* @param $pid
* @param $topic
* @param $content
* @param $tag
* @param $key
*/
public function __construct($url, $ak, $sk, $pid, $topic, $content, $tag, $key)
{
$this->url = $url;
$this->ak = $ak;
$this->sk = $sk;
$this->pid = $pid;
$this->topic = $topic;
$this->content = $content;
$this->tag = $tag;
$this->key = $key;
}
/**
* @param array $headerParam
* @param array $urlParam
* @return mixed
*/
public function produce($headerParam=array(), $urlParam=array())
{
$date = time()*1000;
$newline = "\n";
//POST请求url
$postUrl = $this->url."/message/?topic=".$this->topic."&time=".$date."&tag=".$this->tag."&key=".$this->key;
foreach ($urlParam as $key=>$value)
{
$postUrl.='&'.$key.'='.$value;
}
//签名字符串
$signString = $this->topic.$newline.$this->pid.$newline.md5($this->content).$newline.$date;
//计算签名
$sign = Util::calSignature($signString,$this->sk);
//构造签名标记
$signFlag = $this::$signature.":".$sign;
//构造密钥标记
$akFlag = $this::$aks.":".$this->ak;
//标记
$producerFlag = $this::$producerId.":".$this->pid;
//构造HTTP请求头部内容类型标记
$contentFlag = "Content-Type:text/html;charset=UTF-8";
//构造HTTP请求头部
$headers = array(
$signFlag,
$akFlag,
$producerFlag,
$contentFlag,
);
foreach ($headerParam as $key=>$value)
{
array_push($headers, $key.':'.$value);
}
$result = Http::PostWithHeader($this->content, $headers, $postUrl);
$result = json_decode($result, true);
return $result;
}
/**
* @param $delayTime
* @return mixed
*/
public function produceDelayMessage($delayTime)
{
$deliveryTime = time()*1000 + $delayTime * 1000;
$param['startdelivertime'] = $deliveryTime;
return $this->produce(array(), $param);
}
/**
* @param $shardingKey
* @return mixed
*/
public function produceOrderMessage($shardingKey)
{
$param = array();
$param['isOrder'] = true;
$param['shardingKey'] = $shardingKey;
return $this->produce($param);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 25/04/2017
* Time: 8:49 PM
*/
namespace App\Common\MQ;
class UnlockMessageHandler extends HttpConsumer
{
/**
* UnlockMessageHandler constructor.
*/
public function __construct()
{
parent::__construct(config('constants.mq.url'),
config('constants.mq.ak'),
config('constants.mq.sk'),
config('constants.mq.box_unlock.consumer'),
config('constants.mq.box_unlock.topic'));
}
protected function handleMessage()
{
return true;
}
}
\ No newline at end of file
<?php
namespace App\Common\MQ;
/**
* Created by PhpStorm.
* User: billy
* Date: 25/04/2017
* Time: 7:57 PM
*/
class Util
{
//计算签名
public static function calSignature($str,$key)
{
$sign = "";
if(function_exists("hash_hmac"))
{
$sign = base64_encode(hash_hmac("sha1",$str,$key,true));
}
else
{
$blockSize = 64;
$hashfunc = "sha1";
if(strlen($key) > $blockSize)
{
$key = pack('H*',$hashfunc($key));
}
$key = str_pad($key,$blockSize,chr(0x00));
$ipad = str_repeat(chr(0x36),$blockSize);
$opad = str_repeat(chr(0x5c),$blockSize);
$hmac = pack(
'H*',$hashfunc(
($key^$opad).pack(
'H*',$hashfunc($key^$ipad).$str
)
)
);
$sign = base64_encode($hmac);
}
return $sign;
}
//计算时间戳
public static function microtime_float()
{
list($usec,$sec) = explode(" ",microtime());
return ((float)$usec+(float)$sec);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 12/02/2017
* Time: 11:03 AM
*/
namespace App\Common;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
class Qiniu
{
public static function getUpToken($bucket, $postfix, $policy, $fileName='')
{
if ($fileName == '')
{
$fileName = Utils::guid().'.'.$postfix;
}
else
{
$fileName = $fileName.'.'.$postfix;
}
$policy['saveKey'] = $fileName;
$auth = new Auth(config('constants.qiniu.access_key'), config('constants.qiniu.secret'));
$token = $auth->uploadToken($bucket, null, 3600, $policy);
return $token;
}
public static function uploadFile($bucket, $filePath, $postfix="png", $fileName='')
{
$token = Qiniu::getUpToken($bucket, $postfix, array(), $fileName);
$uploadMgr = new UploadManager();
$ret = $uploadMgr->putFile($token, null, $filePath);
$result = array();
if(!empty($ret[0]))
{
$result = $ret[0]['key'];
}
else
{
$result = "";
}
return $result;
}
public static function fileUploadWithCorp($avatar_src, $avatar_data, $avatar_file, $width, $height, $bucket, $domain)
{
if($width == 0 && $height == 0)
{
$data_Array = json_decode($avatar_data, true);
$width = $data_Array['width'];
$height = $data_Array['height'];
}
$crop = new CropAvatar($avatar_src, $avatar_data, $avatar_file, $width, $height);
$origin = $crop->getSrc();
$result = $crop->getResult();
$response = Qiniu::uploadFile($bucket, $result);
if(!empty($response))
{
$response = $domain.$response;
@unlink($origin);
@unlink($result);
}
$response = array(
'state' => 200,
'message' => $crop -> getMsg(),
'result' => $response,
'filename' => substr($response, strrpos($response, '/') + 1)
);
return json_encode($response);
}
}
\ No newline at end of file
suishengwan common project
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 11/02/2017
* Time: 5:20 PM
*/
namespace App\Common;
class RegExpPattern
{
/**
* 验证手机号
*/
const REGEX_MOBILE = '/^1[34578]\d{9}$/';
//验证用户名
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 10/02/2017
* Time: 6:23 PM
*/
namespace App\Common;
use Illuminate\Support\Facades\Log;
/**
* Class Sms
* @package App\Common
*/
class Sms
{
/**
* @return array
*/
private static function getHeadArray()
{
$AppKey = config('constants.sms.app_key');
$AppSecret = config('constants.sms.app_Secret');
$Nonce = rand(100000, 999999);
$CurTime = time();
$CheckSum = strtolower(sha1($AppSecret . $Nonce . $CurTime));
$head_arr = array();
$head_arr[] = 'Content-Type: application/x-www-form-urlencoded';
$head_arr[] = 'charset: utf-8';
$head_arr[] = 'AppKey:' . $AppKey;
$head_arr[] = 'Nonce:' . $Nonce;
$head_arr[] = 'CurTime:' . $CurTime;
$head_arr[] = 'CheckSum:' . $CheckSum;
return $head_arr;
}
/**
* @param $mobile
* @return bool
*/
public static function sendCode($mobile)
{
$target = config('constants.sms.base_url').config('constants.sms.code_url');
$head_arr = self::getHeadArray();
$post_data = "mobile=".$mobile."&codeLen=".config('constants.sms.code_len');
if (config('constants.sms.template_id'))
{
$post_data .= "&templateid=".config('constants.sms.template_id');
}
$result = Http::PostWithHeader($post_data, $head_arr, $target);
Log::info('send code result: '.$result);
if (strstr($result,"\"code\":200"))
return true;
else
return false;
}
/**
* @param $mobile
* @param $code
* @return bool
*/
public static function verifyCode($mobile, $code)
{
$target = config('constants.sms.base_url').config('constants.sms.verify_url');
$head_arr = self::getHeadArray();
$post_data = "mobile=".$mobile."&code=".$code;
$result = Http::PostWithHeader($post_data, $head_arr, $target);
if (strstr($result,"\"code\":200"))
return true;
else
return false;
}
/**
* @param $mobiles
* @param $template_id
* @param $params
* @return bool
*/
public static function sendTemplateMessage($mobiles, $template_id, $params)
{
$target = config('constants.sms.base_url').config('constants.sms.template_url');
$head_arr = self::getHeadArray();
$post_data = "templateid=".$template_id."&mobiles=".json_encode($mobiles)."&params=".json_encode($params);
$result = Http::PostWithHeader($post_data, $head_arr, $target);
if (strstr($result,"\"code\":200"))
return true;
else
return false;
}
}
\ No newline at end of file
<?php
namespace App\Common\TencentMQ;
/*
Account 对象非线程安全,如果多线程使用,需要每个线程单独初始化Account对象类
*/
class Account
{
private $secretId;
private $secretKey;
private $cmq_client;
/*
@type host: string
@param host: 访问的url,例如:https://cmq-queue-gz.api.qcloud.com
@type secretId: string
@param secretId: 用户的secretId, 腾讯云官网获取
@type secretKey: string
@param secretKey: 用户的secretKey,腾讯云官网获取
@note: Exception
:: CMQClientParameterException host格式错误
*/
public function __construct($host, $secretId, $secretKey) {
$this->host = $host;
$this->secretId = $secretId;
$this->secretKey = $secretKey;
$this->cmq_client = new CMQClient($host, $secretId, $secretKey);
}
/*
* @type sign_method:string
* @param sign_method : only support sha1 and sha256
*/
public function set_sign_method($sign_method='sha1')
{
$this->cmq_client->set_sign_method($sign_method);
}
/* 设置访问的url
@type host: string
@param host: 访问的url,例如:http://cmq-queue-gz.api.tencentyun.com
@type secretId: string
@param secretId: 用户的secretId,腾讯云官网获取
@type secretKey: string
@param secretKey: 用户的secretKey,腾讯云官网获取
@note: Exception
:: CMQClientParameterException host格式错误
*/
public function set_client($host, $secretId=NULL, $secretKey=NULL) {
if ($secretId == NULL) {
$secretId = $this->secretId;
}
if ($secretKey == NULL) {
$secretKey = $this->secretKey;
}
$this->cmq_client = new CMQClient($host, $secretId, $secretKey);
}
/* 获取queue client
@rtype: CMQClient object
@return: 返回使用的CMQClient object
*/
public function get_client() {
return $this->cmq_client;
}
/* 获取Account的一个Queue对象
@type queue_name: string
@param queue_name: 队列名
@rtype: Queue object
@return: 返回该Account的一个Queue对象
*/
public function get_queue($queue_name) {
return new Queue($queue_name, $this->cmq_client);
}
/* 列出Account的队列
@type searchWord: string
@param searchWord: 队列名的前缀
@type limit: int
@param limit: list_queue最多返回的队列数
@type offset: string
@param offset: list_queue的起始位置,上次list_queue返回的next_offset
@rtype: tuple
@return: QueueURL的列表和下次list queue的起始位置; 如果所有queue都list出来,next_offset为"".
*/
public function list_queue($searchWord = "", $limit = -1, $offset = "") {
$params = array();
if ($searchWord != "") {
$params['searchWord'] = $searchWord;
}
if ($limit != -1) {
$params['limit'] = $limit;
}
if ($offset != "") {
$params['offset'] = $offset;
}
$ret_pkg = $this->cmq_client->list_queue($params);
if ($offset == "") {
$next_offset = count($ret_pkg['queueList']);
}
else {
$next_offset = $offset + count($ret_pkg['queueList']);
}
if ($next_offset >= $ret_pkg['totalCount']) {
$next_offset = "";
}
return array("totalCount"=>$ret_pkg['totalCount'],
"queueList"=>$ret_pkg['queueList'], "next_offset"=>$next_offset);
}
/* 列出Account的主题
@type searchWord: string
@param searchWord: 主题关键字
@type limit: int
@param limit: 最多返回的主题数目
@type offset: string
@param offset: list_topic的起始位置,上次list_topic返回的next_offset
@rtype: tuple
@return: TopicURL的列表和下次list topic的起始位置; 如果所有topic都list出来,next_offset为"".
*/
public function list_topic($searchWord = "", $limit = -1, $offset = ""){
$params = array();
if($searchWord != ""){
$params['searchWord'] = $searchWord;
}
if($limit != -1){
$params['limit'] = $limit;
}
if($offset != ""){
$params['offset'] = $offset;
}
$resp = $this->cmq_client->list_topic($params);
if ($offset == ""){
$next_offset = count($resp['topicList']);
}
else{
$next_offset = $offset + count($resp['topicList']);
}
if($next_offset >= $resp['totalCount']){
$next_offset = "";
}
return array("totalCoult" => $resp['totalCount'],
"topicList" =>$resp['topicList'],
"next_offset" => $next_offset);
}
/* 获取Account的一个Topic对象
@type topic_name: string
@param queue_name:
@rtype: Topic object
@return: 返回该Account的一个Topic对象
*/
public function get_topic($topic_name)
{
return new Topic($topic_name,$this->cmq_client);
}
/* 获取Account的一个Subscription对象
@type topic_name: string
@param queue_name:
@type subscription_name :string
@param subscription_name:
@rtype: Subscription object
@return: 返回该Account的一个Subscription对象
*/
public function get_subscription($topic_name, $subscription_name)
{
return new Subscription($topic_name, $subscription_name,$this->cmq_client);
}
}
<?php
namespace App\Common\TencentMQ;
class CMQClient
{
private $host;
private $secretId;
private $secretKey;
private $version;
private $http;
private $method;
private $URISEC = '/v2/index.php';
public function __construct($host, $secretId, $secretKey, $version = "SDK_PHP_1.3", $method = "POST") {
$this->process_host($host);
$this->secretId = $secretId;
$this->secretKey = $secretKey;
$this->version = $version;
$this->method = $method;
$this->sign_method='HmacSHA1';
$this->http = new CMQHttp($this->host);
}
protected function process_host($host) {
if (strpos($host,"http://") === 0) {
$_host = substr($host,7,strlen($host)-7);
}
elseif (strpos($host,"https://") === 0) {
$_host = substr($host,8,strlen($host)-8);
}
else {
throw new CMQClientParameterException("Only support http(s) prototol. Invalid endpoint:" . $host);
}
if ($_host[strlen($_host)-1]=="/") {
$this->host = substr($_host,0,strlen($_host)-1);
}
else {
$this->host = $_host;
}
}
public function set_sign_method($sign_method = 'sha1')
{
if ($sign_method == 'sha1' || $sign_method == 'HmacSHA256')
$this->sign_method = 'HmacSHA1';
elseif ($sign_method == 'sha256')
$this->sign_method = 'HmacSHA256';
else
throw new CMQClientParameterException('Only support sign method HmasSHA256 or HmacSHA1 . Invalid sign method:' . $sign_method);
}
public function set_method($method='POST') {
$this->method = $method;
}
public function set_connection_timeout($connection_timeout) {
$this->http->set_connection_timeout($connection_timeout);
}
public function set_keep_alive($keep_alive) {
$this->http->set_keep_alive($keep_alive);
}
protected function build_req_inter($action, $params, &$req_inter) {
$_params = $params;
$_params['Action'] = ucfirst($action);
$_params['RequestClient'] = $this->version;
if(!isset($_params['SecretId']))
$_params['SecretId'] = $this->secretId;
if (!isset($_params['Nonce']))
$_params['Nonce'] = rand(1, 65535);
if (!isset($_params['Timestamp']))
$_params['Timestamp'] = time();
if (!isset($_params['SignatureMethod']))
$_params['SignatureMethod'] = $this->sign_method;
$plainText = Signature::makeSignPlainText($_params,
$this->method, $this->host, $req_inter->uri);
$_params['Signature'] = Signature::sign($plainText, $this->secretKey,$this->sign_method);
$req_inter->data = http_build_query($_params);
$this->build_header($req_inter);
}
protected function build_header(&$req_inter) {
if ($this->http->is_keep_alive()) {
$req_inter->header["Connection"] = "Keep-Alive";
}
}
protected function check_status($resp_inter) {
if ($resp_inter->status != 200) {
throw new CMQServerNetworkException($resp_inter->status, $resp_inter->header, $resp_inter->data);
}
$resp = json_decode($resp_inter->data, TRUE);
$code = $resp['code'];
$message = $resp['message'];
$requestId = $resp['requestId'];
if ($code != 0) {
throw new CMQServerException($message=$message, $request_id=$requestId, $code=$code, $data=$resp);
}
}
protected function request($action, $params) {
// make request internal
$req_inter = new RequestInternal($this->method, $this->URISEC);
$this->build_req_inter($action, $params, $req_inter);
$iTimeout = 0;
if(array_key_exists("UserpollingWaitSeconds", $params))
{
$iTimeout=(int)$params['UserpollingWaitSeconds'] ;
}
// send request
$resp_inter = $this->http->send_request($req_inter, $iTimeout );
return $resp_inter;
}
//===============================================queue operation===============================================
public function create_queue($params) {
$resp_inter = $this->request('CreateQueue', $params);
$this->check_status($resp_inter);
}
public function delete_queue($params) {
$resp_inter = $this->request('DeleteQueue', $params);
$this->check_status($resp_inter);
}
public function rewindQueue($params){
$resp_inter = $this->request('RewindQueue', $params);
$this->check_status($resp_inter);
}
public function list_queue($params) {
$resp_inter = $this->request('ListQueue', $params);
$this->check_status($resp_inter);
$ret = json_decode($resp_inter->data, TRUE);
return $ret;
}
public function set_queue_attributes($params) {
$resp_inter = $this->request('SetQueueAttributes', $params);
$this->check_status($resp_inter);
}
public function get_queue_attributes($params) {
$resp_inter = $this->request('GetQueueAttributes', $params);
$this->check_status($resp_inter);
$ret = json_decode($resp_inter->data, TRUE);
return $ret;
}
public function send_message($params) {
$resp_inter = $this->request('SendMessage', $params);
$this->check_status($resp_inter);
$ret = json_decode($resp_inter->data, TRUE);
return $ret['msgId'];
}
public function batch_send_message($params) {
$resp_inter = $this->request('BatchSendMessage', $params);
$this->check_status($resp_inter);
$ret = json_decode($resp_inter->data, TRUE);
return $ret['msgList'];
}
public function receive_message($params) {
$resp_inter = $this->request('ReceiveMessage', $params);
$this->check_status($resp_inter);
$ret = json_decode($resp_inter->data, TRUE);
return $ret;
}
public function batch_receive_message($params) {
$resp_inter = $this->request('BatchReceiveMessage', $params);
$this->check_status($resp_inter);
$ret = json_decode($resp_inter->data, TRUE);
return $ret['msgInfoList'];
}
public function delete_message($params) {
$resp_inter = $this->request('DeleteMessage', $params);
$this->check_status($resp_inter);
}
public function batch_delete_message($params) {
$resp_inter = $this->request('BatchDeleteMessage', $params);
$this->check_status($resp_inter);
}
//=============================================topic operation================================================
public function create_topic($params){
$resp_inter = $this->request("CreateTopic", $params);
$this->check_status($resp_inter);
}
public function delete_topic($params){
$resp_inter = $this->request("DeleteTopic", $params);
$this->check_status($resp_inter);
}
public function list_topic($params){
$resp_inter = $this->request("ListTopic", $params);
$this->check_status($resp_inter);
$ret = json_decode($resp_inter->data, TRUE);
return $ret;
}
public function set_topic_attributes($params){
$resp_inter = $this->request("SetTopicAttributes", $params);
$this->check_status($resp_inter);
}
public function get_topic_attributes($params){
$resp_inter = $this->request("GetTopicAttributes", $params);
$this->check_status($resp_inter);
$ret = json_decode($resp_inter->data, TRUE);
return $ret;
}
public function publish_message($params){
$resp_inter = $this->request("PublishMessage", $params);
$this->check_status($resp_inter);
$ret = json_decode($resp_inter->data, TRUE);
return $ret ;
}
public function batch_publish_message($params){
$resp_inter = $this->request("BatchPublishMessage", $params);
$this->check_status($resp_inter);
$ret = json_decode($resp_inter->data, TRUE);
return $ret ;
}
//============================================subscription operation=============================================
public function create_subscription($params){
$resp_inter = $this->request("Subscribe", $params);
$this->check_status($resp_inter);
}
public function clear_filterTags($params){
$resp_inter = $this->request("ClearSubscriptionFilterTags", $params);
$this->check_status($resp_inter);
}
public function delete_subscription($params){
$resp_inter = $this->request("Unsubscribe", $params);
$this->check_status($resp_inter);
}
public function get_subscription_attributes($params){
$resp_inter = $this->request("GetSubscriptionAttributes", $params);
$this->check_status($resp_inter);
$ret = json_decode($resp_inter->data, TRUE);
return $ret;
}
public function set_subscription_attributes($params){
$resp_inter = $this->request("SetSubscriptionAttributes", $params);
$this->check_status($resp_inter);
}
public function list_subscription($params){
$resp_inter = $this->request("ListSubscriptionByTopic", $params);
$this->check_status($resp_inter);
$ret = json_decode($resp_inter->data, TRUE);
return $ret;
}
}
<?php
namespace App\Common\TencentMQ;
class CMQExceptionBase extends \RuntimeException
{
/*
@type code: int
@param code: 错误类型
@type message: string
@param message: 错误描述
@type data: array
@param data: 错误数据
*/
public $code;
public $message;
public $data;
public function __construct($message, $code=-1, $data=array())
{
parent::__construct($message, $code, null);
$this->code = $code;
$this->message = $message;
$this->data = $data;
}
public function __toString()
{
return "CMQExceptionBase " . $this->get_info();
}
public function get_info()
{
$info = array("code" => $this->code,
"data" => json_encode($this->data),
"message" => $this->message);
return json_encode($info);
}
}
class CMQClientException extends CMQExceptionBase
{
public function __construct($message, $code=-1, $data=array())
{
parent::__construct($message, $code, $data);
}
public function __toString()
{
return "CMQClientException " . $this->get_info();
}
}
class CMQClientNetworkException extends CMQClientException
{
/* 网络异常
@note: 检查endpoint是否正确、本机网络是否正常等;
*/
public function __construct($message, $code=-1, $data=array())
{
parent::__construct($message, $code, $data);
}
public function __toString()
{
return "CMQClientNetworkException " . $this->get_info();
}
}
class CMQClientParameterException extends CMQClientException
{
/* 参数格式错误
@note: 请根据提示修改对应参数;
*/
public function __construct($message, $code=-1, $data=array())
{
parent::__construct($message, $code, $data);
}
public function __toString()
{
return "CMQClientParameterException " . $this->get_info();
}
}
class CMQServerNetworkException extends CMQExceptionBase
{
//服务器网络异常
public $status;
public $header;
public $data;
public function __construct($status = 200, $header = NULL, $data = "")
{
if ($header == NULL) {
$header = array();
}
$this->status = $status;
$this->header = $header;
$this->data = $data;
}
public function __toString()
{
$info = array("status" => $this->status,
"header" => json_encode($this->header),
"data" => $this->data);
return "CMQServerNetworkException " . json_encode($info);
}
}
class CMQServerException extends CMQExceptionBase
{
/* cmq处理异常
@note: 根据code进行分类处理,常见错误类型:
: 4000 参数不合法
: 4100 鉴权失败:密钥不存在/失效
: 4300 账户欠费了
: 4400 消息大小超过队列属性设置的最大值
: 4410 已达到队列最大的消息堆积数
: 4420 qps限流
: 4430 删除消息的句柄不合法或者过期了
: 4440 队列不存在
: 4450 队列个数超过限制
: 4460 队列已经存在
: 6000 服务器内部错误
: 6010 批量删除消息失败(具体原因还要看每个消息删除失败的错误码)
: 7000 空消息,即队列当前没有可用消息
: 更多错误类型请登录腾讯云消息服务官网进行了解;
*/
public $request_id;
public function __construct($message, $request_id, $code=-1, $data=array())
{
parent::__construct($message, $code, $data);
$this->request_id = $request_id;
}
public function __toString()
{
return "CMQServerException " . $this->get_info() . ", RequestID:" . $this->request_id;
}
}
?>
<?php
namespace App\Common\TencentMQ;
class CMQHttp
{
private $connection_timeout;
private $keep_alive;
private $host;
public function __construct($host, $connection_timeout=10, $keep_alive=true) {
$this->connection_timeout = $connection_timeout;
$this->keep_alive = $keep_alive;
$this->host = $host . "" . "/v2/index.php";
$this->curl = NULL;
}
public function set_method($method='POST') {
$this->method = $method;
}
public function set_connection_timeout($connection_timeout) {
$this->connection_timeout = $connection_timeout;
}
public function set_keep_alive($keep_alive) {
$this->keep_alive = $keep_alive;
}
public function is_keep_alive() {
return $this->keep_alive;
}
public function send_request($req_inter, $userTimeout) {
if(!$this->keep_alive)
{
$this->curl = curl_init();
}
else
{
if($this->curl == NULL)
$this->curl = curl_init();
}
if($this->curl == NULL)
{
throw new CMQClientException("Curl init failed");
return;
}
$url = $this->host;
if ($req_inter->method == 'POST')
{
curl_setopt($this->curl, CURLOPT_POST, 1);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $req_inter->data);
}
else
{
$url .= $req_inter->uri . '?' . $req_inter->data;
}
if (isset($req_inter->header)) {
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $req_inter->header);
}
curl_setopt($this->curl, CURLOPT_URL, $url);
curl_setopt($this->curl, CURLOPT_TIMEOUT, $this->connection_timeout +$userTimeout );
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
if (false !== strpos($url, "https")) {
// 证书
// curl_setopt($ch,CURLOPT_CAINFO,"ca.crt");
curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, false);
}
$resultStr = curl_exec($this->curl);
if(curl_errno($this->curl)) {
throw new CMQClientNetworkException(curl_error($this->curl));
}
$info = curl_getinfo($this->curl);
$resp_inter = new ResponseInternal($info['http_code'], NULL, $resultStr);
return $resp_inter;
}
}
class RequestInternal
{
public $header;
public $method;
public $uri;
public $data;
public function __construct($method = "", $uri = "", $header = NULL, $data = "") {
if ($header == NULL) {
$header = array();
}
$this->method = $method;
$this->uri = $uri;
$this->header = $header;
$this->data = $data;
}
public function __toString()
{
$info = array("method" => $this->method,
"uri" => $this->uri,
"header" => json_encode($this->header),
"data" => $this->data);
return json_encode($info);
}
}
class ResponseInternal
{
public $header;
public $status;
public $data;
public function __construct($status = 0, $header = NULL, $data = "") {
if ($header == NULL) {
$header = array();
}
$this->status = $status;
$this->header = $header;
$this->data = $data;
}
public function __toString()
{
$info = array("status" => $this->status,
"header" => json_encode($this->header),
"data" => $this->data);
return json_encode($info);
}
}
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 10/02/2018
* Time: 2:47 PM
*/
namespace App\Common\TencentMQ;
use Illuminate\Support\Facades\Log;
class HttpProducer
{
private $host;
private $secretId;
private $secretKey;
/*
@type host: string
@param host: 访问的url,例如:https://cmq-queue-gz.api.qcloud.com
@type secretId: string
@param secretId: 用户的secretId, 腾讯云官网获取
@type secretKey: string
@param secretKey: 用户的secretKey,腾讯云官网获取
@note: Exception
:: CMQClientParameterException host格式错误
*/
public function __construct($host, $secretId, $secretKey) {
$this->host = $host;
$this->secretId = $secretId;
$this->secretKey = $secretKey;
$this->cmq_client = new CMQClient($host, $secretId, $secretKey);
}
public function sendMessage($queueName, $messageBody, $delay = 0) {
$account = new Account($this->host, $this->secretId, $this->secretKey);
$queue = $account->get_queue($queueName);
$msg = new Message($messageBody);
$re_msg = $queue->send_message($msg, $delay);
Log::info('ret_msg is'.json_encode($re_msg));
return $re_msg;
}
}
\ No newline at end of file
<?php
namespace App\Common\TencentMQ;
/**
* Sign
* 签名类
*/
class Signature
{
/**
* sign
* 生成签名
* @param string $srcStr 拼接签名源文字符串
* @param string $secretKey secretKey
* @param string $method 请求方法
* @return
*/
public static function sign($srcStr, $secretKey, $method = 'HmacSHA1')
{
switch ($method) {
case 'HmacSHA1':
$retStr = base64_encode(hash_hmac('sha1', $srcStr, $secretKey, true));
break;
case 'HmacSHA256':
$retStr = base64_encode(hash_hmac('sha256', $srcStr, $secretKey, true));
break;
default:
throw new Exception($method . ' is not a supported encrypt method');
return false;
break;
}
return $retStr;
}
/**
* makeSignPlainText
* 生成拼接签名源文字符串
* @param array $requestParams 请求参数
* @param string $requestMethod 请求方法
* @param string $requestHost 接口域名
* @param string $requestPath url路径
* @return
*/
public static function makeSignPlainText($requestParams,
$requestMethod = 'POST', $requestHost = YUNAPI_URL,
$requestPath = '/v2/index.php')
{
$url = $requestHost . $requestPath;
// 取出所有的参数
$paramStr = self::_buildParamStr($requestParams, $requestMethod);
$plainText = $requestMethod . $url . $paramStr;
return $plainText;
}
/**
* _buildParamStr
* 拼接参数
* @param array $requestParams 请求参数
* @param string $requestMethod 请求方法
* @return
*/
protected static function _buildParamStr($requestParams, $requestMethod = 'POST')
{
$paramStr = '';
ksort($requestParams);
$i = 0;
foreach ($requestParams as $key => $value)
{
if ($key == 'Signature')
{
continue;
}
// 排除上传文件的参数
if ($requestMethod == 'POST' && substr($value, 0, 1) == '@') {
continue;
}
// 把 参数中的 _ 替换成 .
if (strpos($key, '_'))
{
$key = str_replace('_', '.', $key);
}
if ($i == 0)
{
$paramStr .= '?';
}
else
{
$paramStr .= '&';
}
$paramStr .= $key . '=' . $value;
++$i;
}
return $paramStr;
}
}
<?php
namespace App\Common\TencentMQ;
class Subscription
{
private $topic_name;
private $subscription_name;
private $cmq_client;
private $encoding;
public function __construct($topic_name,$subscription_name,$cmq_client,$encoding = false){
$this->topic_name = $topic_name;
$this->subscription_name = $subscription_name;
$this->cmq_client = $cmq_client;
$this->encoding = $encoding;
}
public function set_encoding($encoding){
$this->encoding = $encoding;
}
/*
* create subscription
* @type subscription_meta :SubscriptionMeta
*/
public function create($subscription_meta){
$params=array(
'topicName' => $this->topic_name,
'subscriptionName' => $this->subscription_name,
'notifyStrategy' => $subscription_meta->NotifyStrategy,
'notifyContentFormat' => $subscription_meta->NotifyContentFormat,
);
if ($subscription_meta->Endpoint != ""){
$params['endpoint'] = $subscription_meta->Endpoint;
}
if($subscription_meta->Protocol !=""){
$params['protocol'] = $subscription_meta->Protocol;
}
if(! $subscription_meta->bindindKey != null && is_array($subscription_meta->bindindKey) && !empty($subscription_meta->bindindKey)){
$n = 1;
foreach ($subscription_meta->bindindKey as $tag)
{
$key = 'bindindKey.' . $n;
$params[$key] = $tag;
$n += 1 ;
}
}
if(! $subscription_meta->FilterTag != null && is_array($subscription_meta->FilterTag) && !empty($subscription_meta->FilterTag)){
$n = 1;
foreach ($subscription_meta->FilterTag as $tag)
{
$key = 'filterTag.' . $n;
$params[$key] = $tag;
$n += 1 ;
}
}
$this->cmq_client->create_subscription($params);
}
/*
* delete subscription
*/
public function delete(){
$params=array(
'topicName' => $this->topic_name,
'subscriptionName' => $this->subscription_name
);
$this->cmq_client->delete_subscription($params);
}
/*
* clear subscription tags
*/
public function clearFilterTags(){
$params=array(
'topicName' => $this->topic_name,
'subscriptionName' => $this->subscription_name
);
$this->cmq_client->clear_filterTags($params);
}
/*
* get attributes
*
* @return subscription_meta :SubscriptionMeta
*/
public function get_attributes(){
$params=array(
'topicName' => $this->topic_name,
'subscriptionName' => $this->subscription_name
);
$resp = $this->cmq_client->get_subscription_attributes($params);
$subscription_meta = new SubscriptionMeta();
$this->__resp2meta($subscription_meta, $resp);
return $subscription_meta;
}
/*
* set attributes
* @type subscription_meta : SubscriptionMeta
*
*/
public function set_attributes($subscription_meta){
$params = array(
'topicName' => $this->topic_name,
'subscriptionName' => $this->subscription_name
);
if ($subscription_meta->NotifyStrategy !=""){
$params['notifyStrategy'] = $subscription_meta->NotifyStrategy;
}
if ($subscription_meta->NotifyContentFormat != ""){
$params['notifyContentFormat']=$subscription_meta->NotifyContentFormat;
}
if ($subscription_meta->Endpoint != ""){
$params['endpoint'] = $subscription_meta->Endpoint;
}
if($subscription_meta->Protocol !=""){
$params['protocol'] = $subscription_meta->Protocol;
}
if(! $subscription_meta->bindindKey != null && is_array($subscription_meta->bindindKey) && !empty($subscription_meta->bindindKey)){
$n = 1;
foreach ($subscription_meta->bindindKey as $tag)
{
$key = 'bindindKey.' . $n;
$params[$key] = $tag;
$n += 1 ;
}
}
if(! $subscription_meta->FilterTag != null && is_array($subscription_meta->FilterTag) && !empty($subscription_meta->FilterTag)){
$n = 1;
foreach ($subscription_meta->FilterTag as $tag)
{
$key = 'filterTag.' . $n;
$params[$key] = $tag;
$n += 1 ;
}
}
$this->cmq_client->set_subscription_attributes($params);
}
protected function __resp2meta($subscription_meta, $resp){
if (isset($resp['endpoint'])) {
$subscription_meta->Endpoint = $resp['endpoint'];
}
if (isset($resp['protocol'])) {
$subscription_meta->Protocol = $resp['protocol'];
}
if (isset($resp['notifyStrategy'])) {
$subscription_meta->NotifyStrategy = $resp['notifyStrategy'];
}
if (isset($resp['notifyContentFormat'])) {
$subscription_meta->NotifyContentFormat = $resp['notifyContentFormat'];
}
if( isset($resp['bindindKey'])){
foreach ($resp['bindindKey'] as $tag){
array_push($subscription_meta->bindindKey, $tag);
}
}
if( isset($resp['filterTags'])){
foreach ($resp['filterTags'] as $tag){
array_push($subscription_meta->FilterTag, $tag);
}
}
}
}
class SubscriptionMeta
{
// default NotifyStrategy BACKOFF_RETRY
// default NotifyContentFormat JSON
/* 订阅属性
@note: 可修改
:: Endpoint 推送消息地址
:: Protocal 协议
:: FilterTag 订阅 标签
:: NotifyStrategy 重试策略
:: NotifyContentFormat 推送消息格式
*/
public $Endpoint;
public $Protocol;
public $FilterTag;
public $NotifyStrategy;
public $NotifyContentFormat;
public function __construct(){
$this->Endpoint = "";
$this->Protocol= "";
$this->FilterTag = array();
$this->NotifyStrategy = "BACKOFF_RETRY";
$this->NotifyContentFormat = "JSON";
$this->bindindKey = array();
}
public function __toString(){
$info = array(
"endpoint" => $this->Endpoint,
"protocol" => $this->Protocol,
"filterTag" => $this->FilterTag,
"notifyStrategy" => $this->NotifyStrategy,
"notifyContentFormat" => $this->NotifyContentFormat,
"bindingKey" => $this->bindindKey,
);
return json_encode($info);
}
}
<?php
namespace App\Common\TencentMQ;
class Topic
{
private $topic_name;
private $cmq_client;
private $encoding;
public function __construct($topic_name, $cmq_client, $encoding=false){
$this->topic_name = $topic_name;
$this->cmq_client = $cmq_client;
$this->encoding = $encoding ;
}
public function set_encoding($encoding){
$this->encoding = $encoding;
}
/*
* create topic
* @type topic_meta : TopicMeta
* @param topic_meta :
*/
public function create($topic_meta){
$params = array(
'topicName' => $this->topic_name,
'filterType'=>$topic_meta->filterType
);
if ( $topic_meta->maxMsgSize >0 ){
$params['maxMsgSize'] = $topic_meta->maxMsgSize;
}
$this->cmq_client->create_topic($params);
}
/*
* get attributes
*
* @return topic_meta :TopicMeta
*
*/
public function get_attributes(){
$params = array(
'topicName' => $this->topic_name,
);
$resp = $this->cmq_client->get_topic_attributes($params);
$topic_meta = new TopicMeta();
$this->__resp2meta($topic_meta, $resp);
return $topic_meta;
}
/*
* set attributes
*
* @type topic_meta :TopicMeta
* @param topic_meta :
*/
public function set_attributes($topic_meta){
$params = array(
'topicName' => $this->topic_name,
'maxMsgSize' => strval($topic_meta->maxMsgSize)
);
$this->cmq_client->set_topic_attributes($params);
}
/*
* delete topic
*/
public function delete(){
$params = array(
'topicName' => $this->topic_name
);
$this->cmq_client->delete_topic($params);
}
/*
* 推送消息 非批量
* @type message :string
* @param message
*
* @type vTagList :list
* @param vTagList 标签
*
* @return message handle
*/
public function publish_message($message ,$vTagList= null , $routingKey = null){
$params=array(
'topicName' => $this->topic_name,
'msgBody' => $message,
);
if( $routingKey != null){
$params['routingKey'] = $routingKey;
}
if ($vTagList != null && is_array($vTagList) && !empty($vTagList))
{
$n = 1 ;
foreach ($vTagList as $tag){
$key = 'msgTag.' . $n;
$params[$key]=$tag;
$n += 1 ;
}
}
$msgId = $this->cmq_client->publish_message($params);
return $msgId;
}
/*
* 批量推送消息
* @type vmessageList :list
* @param vmessageList:
*
* @type vtagList :list
* @param vtagList
*
* @return : return message handle list
*/
public function batch_publish_message($vmessageList, $vtagList = null ,$routingKey=null){
$params = array(
'topicName' => $this->topic_name,
);
if($routingKey !=null){
$params['routingKey'] = $routingKey;
}
$n = 1 ;
if( is_array($vmessageList) && !empty($vmessageList))
{
foreach ($vmessageList as $msg){
$key = 'msgBody.' . $n ;
if($this->encoding){
$params[$key] = base64_encode($msg);
}
else
{
$params[$key] = $msg;
}
$n += 1 ;
}
}
if ($vtagList != null && is_array($vtagList) && !empty($vtagList))
{
$n = 1 ;
foreach ($vtagList as $tag){
$key = 'msgTag.' . $n ;
$params[$key] = $tag ;
$n += 1 ;
}
}
$msgList = $this->cmq_client->batch_publish_message($params);
$retMessageList = array();
foreach ($msgList as $msg){
if(isset($msg['msgId'])){
$retmsgId = $msg['msgId'];
$retMessageList [] = $retmsgId;
}
}
return $retMessageList;
}
/* 列出Topic的Subscriptoin
@type topic_name :string
@param topic_name:
@type searchWord: string
@param searchWord: 订阅关键字
@type limit: int
@param limit: 最多返回的订阅数目
@type offset: string
@param offset: list_subscription的起始位置,上次list_subscription返回的next_offset
@rtype: tuple
@return: subscriptionURL的列表和下次list subscription的起始位置; 如果所有subscription都list出来,next_offset为"".
*/
public function list_subscription($searchWord ="", $limit = -1, $offset =""){
$params = array('topicName' => $this->topic_name);
if($searchWord != ""){
$params['searchWord'] = $searchWord;
}
if($limit != -1){
$params['limit'] = $limit;
}
if($offset != ""){
$params['offset'] = $offset;
}
$resp = $this->cmq_client->list_subscription($params);
if ($offset == ""){
$next_offset = count($resp['subscriptionList']);
}
else{
$next_offset = $offset + count($resp['subscriptionList']);
}
if($next_offset >= $resp['totalCount']){
$next_offset = "";
}
return array("totalCoult" => $resp['totalCount'],
"subscriptionList" =>$resp['subscriptionList'],
"next_offset" => $next_offset);
}
protected function __resp2meta($topic_meta, $resp){
if(isset($resp['maxMsgSize'])){
$topic_meta->maxMsgSize = $resp['maxMsgSize'];
}
if(isset($resp['msgRetentionSeconds'])){
$topic_meta->msgRetentionSeconds = $resp['msgRetentionSeconds'];
}
if(isset($resp['createTime'])){
$topic_meta->createTime = $resp['createTime'];
}
if(isset($resp['lastModifyTime'])){
$topic_meta->lastModifyTime = $resp['lastModifyTime'];
}
if(isset($resp['filterType'])){
$topic_meta->filterType = $resp['filterType'];
}
}
}
class TopicMeta
{
// default maxMsgSize 65536
// default msgRetentionSeconds 86400, one day
/* 主题属性
@note: 可修改
:: maxMsgSize 消息最大值
@note: 不可修改
:: msgRetentionSeconds 消息最长保存时间,默认为 一天
:: createTime 创建时间
:: lastModifyTime 上次修改时间
*/
public $maxMsgSize;
public $msgRetentionSeconds;
public $createTime;
public $lastModifyTime;
public function __construct(){
$this->maxMsgSize = 65536 ;
$this->msgRetentionSeconds= 86400;
$this->createTime = 0;
$this->lastModifyTime = 0;
$this->filterType = 1;
}
public function __toString(){
$info = array(
"maxMsgSize" => $this->maxMsgSize,
"msgRetentionSeconds" => $this->msgRetentionSeconds,
"createTime" => $this->createTime,
"lastModifyTime" => $this->lastModifyTime,
"filterType" => $this->filterType
);
return json_encode($info);
}
}
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 10/02/2017
* Time: 6:23 PM
*/
namespace App\Common;
use App\Common\Enums\LoginType;
/**
* Class ThirdPartyLogin
* @package App\Common
*/
class ThirdPartyLogin
{
public static function verify($openId, $accessToken, $type)
{
if ($type == LoginType::QQ)
{
return self::qq_verify($openId, $accessToken);
}
else if($type == LoginType::WECHAT)
{
return self::wechat_verify($openId, $accessToken);
}
}
private static function qq_verify($openId, $accessToken)
{
$target = "https://graph.qq.com/oauth2.0/me?access_token=".$accessToken;
$result = Http::Get($target);
if($result != null)
{
if (preg_match('/openid":"'.$openId.'"/', $result))
{
return true;
}
}
return false;
}
private static function wechat_verify($openId, $accessToken)
{
$target = "https://api.weixin.qq.com/sns/auth?access_token=".$accessToken."&openid=".$openId;
$result = Http::Get($target);
if($result != null)
{
if (preg_match('/"errcode":0,/', $result))
{
return true;
}
}
return false;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 11/03/2017
* Time: 11:12 AM
*/
namespace App\Common\Util;
class OrderUtil
{
private static function generateOrderId()
{
$time_ms_array = explode(" ", microtime());
$ms_part = sprintf("%06d", $time_ms_array[0] * 1000 * 1000);
$s_part = $time_ms_array[1];
return date('YmdHis', $s_part) . $ms_part . rand(10000000,99999999);
}
public static function generateRechargeOrderId()
{
return 'ykr'.self::generateOrderId();
}
public static function generateCosumeOrderId()
{
return 'ykc'.self::generateOrderId();
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 12/02/2017
* Time: 11:06 AM
*/
namespace App\Common;
class Utils
{
/**
* @return string
*/
public static function guid()
{
$timestamp = time();
$ranstr = rand(9999, 9999999999);
return md5($timestamp . $ranstr) . substr(md5($ranstr), 0, 8);
}
/**
* xml转为数组
*/
public static function xmlToArray($xmlStr)
{
$msg = array();
$postStr = $xmlStr;
$msg = json_decode(json_encode(simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $msg;
}
/**
* @param $number
* @param int $precision
* @return float|int
*/
public static function round_up($number, $precision = 3)
{
$fig = (int) str_pad('1', $precision, '0');
return (ceil($number * $fig) / $fig);
}
/**
* @param $number
* @param int $precision
* @return float|int
*/
public static function round_down($number, $precision = 3)
{
$fig = (int) str_pad('1', $precision, '0');
return (floor($number * $fig) / $fig);
}
/**
* @param $data
* @param $key
* @return mixed
*/
public static function array_remove($data, $key)
{
if(!array_key_exists($key, $data)){
return $data;
}
$keys = array_keys($data);
$index = array_search($key, $keys);
if($index !== FALSE){
array_splice($data, $index, 1);
}
return $data;
}
/**
* @param $day1
* @param $day2
* @return float|int
*/
public static function diffBetweenTwoDays ($day1, $day2)
{
$second1 = strtotime($day1);
$second2 = strtotime($day2);
if ($second1 < $second2) {
$tmp = $second2;
$second2 = $second1;
$second1 = $tmp;
}
return ($second1 - $second2) / 86400;
}
}
\ No newline at end of file
<?php
namespace App\Console\Commands;
use App\Modules\Models\DayIncome\DayIncome;
use App\Repositories\Business\RentRepository;
use Illuminate\Console\Command;
class DayProfit extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'DayProfit {--day=}';
/**
* The console command description.
*
* @var string
*/
protected $description = '每日的收益数据整理';
protected $rent;
public function __construct(RentRepository $rent)
{
parent::__construct();
$this->rent = $rent;
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//
$day = $this->option('day');
echo 'ma'.$day;
exit;
}
}
<?php
namespace App\Console;
use App\Console\Commands\DayProfit;
use App\Console\Commands\GetElectricity;
use App\Console\Commands\OrderDetection;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
Commands\DayProfit::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command(DayProfit::class)->everyMinute()->appendOutputTo('day.log');;
}
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
require base_path('routes/console.php');
}
}
<?php
/**
* Created by PhpStorm.
* User: billy
* Date: 11/02/2017
* Time: 1:49 PM
*/
namespace App\Exceptions\Api;
use Exception;
/**
* Class ApiException
* @package App\Exceptions\Api
*/
class ApiException extends Exception
{
/**
* @var
*/
private $response_code;
/**
* @var
*/
private $param;
/**
* ApiException constructor.
* @param string $code
* @param int $message
* @param array $param
* @param int $response_code
*/
public function __construct($code, $message, $param=array(), $response_code=200)
{
$this->code = $code;
$this->message = $message;
$this->param = $param;
$this->response_code = $response_code;
}
/**
* @return mixed
*/
public function getResponseCode()
{
return $this->response_code;
}
/**
* @return mixed
*/
public function getParam()
{
return $this->param;
}
/**
* @param mixed $response_code
*/
public function setResponseCode($response_code)
{
$this->response_code = $response_code;
}
/**
* @param mixed $param
*/
public function setParam($param)
{
$this->param = $param;
}
}
\ No newline at end of file
<?php
namespace App\Exceptions;
use Exception;
/**
* Class GeneralException.
*/
class GeneralException extends Exception
{
}
<?php
namespace App\Exceptions;
use App\Modules\Enums\ErrorCode;
use App\Exceptions\Api\ApiException;
use Exception;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\Finder\Exception\AccessDeniedException;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
\Illuminate\Auth\AuthenticationException::class,
\Illuminate\Auth\Access\AuthorizationException::class,
\Symfony\Component\HttpKernel\Exception\HttpException::class,
\Illuminate\Database\Eloquent\ModelNotFoundException::class,
\Illuminate\Session\TokenMismatchException::class,
\Illuminate\Validation\ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $exception
* @return void
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
/*
* Redirect if token mismatch error
* Usually because user stayed on the same screen too long and their session expired
*/
if ($exception instanceof TokenMismatchException) {
return redirect()->route('frontend.auth.login');
}
/*
* All instances of GeneralException redirect back with a flash message to show a bootstrap alert-error
*/
if ($exception instanceof GeneralException) {
return redirect()->back()->withInput()->withFlashDanger($exception->getMessage());
}
/**
* Api Exceptions
*/
if ($exception instanceof ApiException){
$responseArray = array_merge($exception->getParam(), ["error_code"=>$exception->getCode(), 'error_message'=>$exception->getMessage()]);
return response()->json($responseArray, $exception->getResponseCode());
}
if ($exception instanceof AuthorizationException){
$responseArray = ["error_code"=>ErrorCode::UNAUTHORIZED, 'error_message'=>$exception->getMessage()];
return response()->json($responseArray, '403');
}
return parent::render($request, $exception);
}
/**
* Convert an authentication exception into an unauthenticated response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Auth\AuthenticationException $exception
* @return \Illuminate\Http\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest(route('frontend.auth.login'));
}
}
<?php
namespace App\Helpers\Auth;
/**
* Class Auth.
*/
class Auth
{
/**
* Remove old session variables from admin logging in as user.
*/
public function flushTempSession()
{
// Remove any old session variables
session()->forget('admin_user_id');
session()->forget('admin_user_name');
session()->forget('temp_user_id');
}
}
<?php
namespace App\Helpers\Frontend\Auth;
/**
* Class Socialite.
*/
class Socialite
{
/**
* Generates social login links based on what is enabled.
*
* @return string
*/
public function getSocialLinks()
{
$socialite_enable = [];
$socialite_links = '';
if (config('services.bitbucket.client_id')) {
$socialite_enable[] = link_to_route('frontend.auth.social.login', trans('labels.frontend.auth.login_with', ['social_media' => 'Bit Bucket']), 'bitbucket');
}
if (config('services.facebook.client_id')) {
$socialite_enable[] = link_to_route('frontend.auth.social.login', trans('labels.frontend.auth.login_with', ['social_media' => 'Facebook']), 'facebook');
}
if (config('services.google.client_id')) {
$socialite_enable[] = link_to_route('frontend.auth.social.login', trans('labels.frontend.auth.login_with', ['social_media' => 'Google']), 'google');
}
if (config('services.github.client_id')) {
$socialite_enable[] = link_to_route('frontend.auth.social.login', trans('labels.frontend.auth.login_with', ['social_media' => 'Github']), 'github');
}
if (config('services.linkedin.client_id')) {
$socialite_enable[] = link_to_route('frontend.auth.social.login', trans('labels.frontend.auth.login_with', ['social_media' => 'Linked In']), 'linkedin');
}
if (config('services.twitter.client_id')) {
$socialite_enable[] = link_to_route('frontend.auth.social.login', trans('labels.frontend.auth.login_with', ['social_media' => 'Twitter']), 'twitter');
}
for ($i = 0; $i < count($socialite_enable); $i++) {
$socialite_links .= ($socialite_links != '' ? '&nbsp;|&nbsp;' : '').$socialite_enable[$i];
}
return $socialite_links;
}
/**
* List of the accepted third party provider types to login with.
*
* @return array
*/
public function getAcceptedProviders()
{
return [
'bitbucket',
'facebook',
'google',
'github',
'linkedin',
'twitter',
];
}
}
<?php
namespace App\Helpers\Macros;
use Collective\Html\FormBuilder;
use App\Helpers\Macros\Traits\Dropdowns;
/**
* Class Macros.
*/
class Macros extends FormBuilder
{
use Dropdowns;
}
<?php
namespace App\Http\Composers\Backend;
use Illuminate\View\View;
use App\Modules\Repositories\Backend\Access\User\UserRepository;
/**
* Class SidebarComposer.
*/
class SidebarComposer
{
/**
* @var UserRepository
*/
protected $userRepository;
/**
* SidebarComposer constructor.
*
* @param UserRepository $userRepository
*/
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
/**
* @param View $view
*
* @return bool|mixed
*/
public function compose(View $view)
{
if (config('access.users.requires_approval')) {
$view->with('pending_approval', $this->userRepository->getUnconfirmedCount());
} else {
$view->with('pending_approval', 0);
}
}
}
<?php
namespace App\Http\Composers;
use Illuminate\View\View;
/**
* Class GlobalComposer.
*/
class GlobalComposer
{
/**
* Bind data to the view.
*
* @param View $view
*
* @return void
*/
public function compose(View $view)
{
// $view->with('logged_in_user', access()->user());
}
}
<?php
/**
* Created by PhpStorm.
* User: machengjun
* Date: 2018/3/12
* Time: 下午5:23
*/
namespace App\Http\Controllers\Api\Business;
use App\Http\Controllers\Controller;
use App\Http\Requests\Business\Api\BusinessLoginRequest;
use App\Repositories\Business\BusinessRepository;
use App\Repositories\CustomerRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
/**
* Class CustomerController
* @package App\Http\Controllers\Api
*/
class BusinessController extends Controller
{
protected $business;
public function __construct(BusinessRepository $business)
{
$this->business = $business;
}
public function login(BusinessLoginRequest $request)
{
Log::info("[businessLogin]params" . json_encode($request->all()));
$response = $this->business->login($request->only("username", "password"));
return $this->responseSuccess($response);
}
public function refreshToken()
{
$response = $this->business->refreshToken();
return $this->responseSuccess($response);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: machengjun
* Date: 2018/3/22
* Time: 下午3:26
*/
namespace App\Http\Controllers\Api\Business;
use App\Http\Controllers\Controller;
use App\Repositories\Business\BusinessRepository;
use App\Repositories\Business\RepairRepository;
use App\Repositories\CustomerRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
/**
* Class CustomerController
* @package App\Http\Controllers\Api
*/
class CommunicationController extends Controller
{
protected $repair;
public function __construct(RepairRepository $repair)
{
$this->repair = $repair;
}
public function repairCreate(Request $request)
{
Log::info("[businessRepairCreate]params" . json_encode($request->all()));
$input = $request->all();
$input['system_users_id'] = $request->get('user')->id;
$this->repair->create($input);
return $this->responseSuccess();
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: machengjun
* Date: 2018/3/22
* Time: 下午3:26
*/
namespace App\Http\Controllers\Api\Business;
use App\Http\Controllers\Controller;
use App\Http\Requests\Business\Api\BusinessLoginRequest;
use App\Repositories\Business\BusinessRepository;
use App\Repositories\Business\MachineRepository;
use App\Repositories\Business\SpotRepository;
use App\Repositories\CustomerRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
/**
* Class CustomerController
* @package App\Http\Controllers\Api
*/
class MachineController extends Controller
{
protected $business;
protected $spot;
protected $machine;
public function __construct(BusinessRepository $business, SpotRepository $spot, MachineRepository $machine)
{
$this->business = $business;
$this->spot = $spot;
$this->machine = $machine;
}
public function getSpotMachine(Request $request)
{
Log::info("[businessLogin]params" . json_encode($request->all()));
$spot_id = $request->get('spot_id');
//验证指定景点权限
$this->spot->spotPermission($request->get('user'), $spot_id);
$machines_obj = $this->machine->getSpotMachineList($spot_id);
$response['machine'] = $this->_formatSpotMachine($machines_obj);
return $this->responseSuccess($response);
}
private function _formatSpotMachine($machines_obj)
{
$data = [];
if ($machines_obj != null) {
foreach ($machines_obj as $k => $v) {
$data[$k]['id'] = $v->id;
$data[$k]['mac_no'] = $v->mac_no;
}
}
return $data;
}
}
\ No newline at end of file
<?php
namespace App\Http\Controllers\Api\Business;
use App\Common\Enums\HtTab;
use App\Exceptions\Api\ApiException;
use App\Http\Controllers\LoginController;
use App\Modules\Enums\ErrorCode;
use App\Repositories\Business\GuideRepository;
use App\Repositories\Business\MachineRepository;
use App\Repositories\Business\ProductionRepository;
use App\Repositories\Business\RentRepository;
use App\Repositories\Business\ReportRepository;
use App\Repositories\Business\SpotRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class RentController extends LoginController
{
protected $rent;
protected $spot;
public function __construct(RentRepository $rent, SpotRepository $spot)
{
$this->rent = $rent;
$this->spot = $spot;
}
public function rentList(Request $request)
{
Log::info("[businessRentList] params:" . json_encode($request->all()));
$spot_id = $this->spot->getToShowSpot($request->get('user'));
$data = $request->only('page', 'limit');
$data['page'] = isset($data['page']) ? $data['page'] : 0;
$data['limit'] = isset($data['limit']) ? $data['limit'] : HtTab::DEFAULT_LIMIT;
$search = $request->only('day', 'month', 'status', 'total');
if ($spot_id == 14) {
$rent_records_obj = $this->rent->getSpotAllStatusRentTest($spot_id, $data['page'], $data['limit'], $search);
}else{
$rent_records_obj = $this->rent->getSpotAllStatusRent($spot_id, $data['page'], $data['limit'], $search);
}
$response['data'] = $this->_formatAllStatusRent($rent_records_obj, $spot_id);
return $this->responseSuccess($response);
}
public function rentDetail(Request $request)
{
Log::info("[businessRentDetail] params:" . json_encode($request->all()));
if (!$rent_no = $request->get('rent_no')) {
throw new ApiException(ErrorCode::PARAM_ERROR, trans('api.error.param_error'));
}
$spot_id = $this->spot->getToShowSpot($request->get('user'));
if ($spot_id == 14) {
$rent_obj = $this->rent->getSpotRentDetailTest($rent_no, $spot_id);
}else{
$rent_obj = $this->rent->getSpotRentDetail($rent_no, $spot_id);
}
$response['data'] = $this->_formatSpotRentDetail($rent_obj);
return $this->responseSuccess($response);
}
private function _formatSpotRentDetail($rent_obj)
{
$data = [
'spot_name' => $rent_obj->spot->spotname,
'rent_price' => feeMes($rent_obj->free_time, $rent_obj->one_day_price),
'deposit' => round($rent_obj->deposit / 100, 2),
'is_return' => $rent_obj->is_over,
'real_total' => round($rent_obj->real_total / 100, 2),
'rent_start_time' => $rent_obj->pay_time,
'rent_over_time' => $rent_obj->over_time,
'mac_no' => $rent_obj->machine->mac_no,
'rent_no' => $rent_obj->rent_no,
'phone' => $rent_obj->customer->phone,
];
return $data;
}
private function _formatAllStatusRent($rent_records_obj)
{
$data = [];
if ($rent_records_obj != null) {
foreach ($rent_records_obj as $k => $rent_record_obj) {
$data[$k]['rent_no'] = $rent_record_obj->rent_no;
$data[$k]['rent_time'] = $rent_record_obj->pay_time;
$data[$k]['real_total'] = $rent_record_obj->real_total;
$data[$k]['status'] = $rent_record_obj->is_over;
}
}
return $data;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: machengjun
* Date: 2018/3/14
* Time: 下午5:27
*/
namespace App\Http\Controllers\Api\Business;
use App\Http\Controllers\Controller;
use App\Repositories\Business\SpotRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class SpotController extends Controller
{
protected $spot;
public function __construct(SpotRepository $spot)
{
$this->spot = $spot;
}
public function profile(Request $request)
{
Log::info("[mySpotList]params" . json_encode($request->all()));
$spot_obj = $this->spot->getToShowSpotObj($request->get('user'));
$response['data'] = $this->_formatSpotProfile($spot_obj);
return $this->responseSuccess($response);
}
public function mySpotList(Request $request)
{
Log::info("[mySpotList]params" . json_encode($request->all()));
$spots_obj = $this->spot->getMylist($request->get('user'));
$spot_id = $this->spot->getSelectedSpot($request->get('user'));
$response = $this->_formatMySpotList($spots_obj, $spot_id);
return $this->responseSuccess($response);
}
public function changeSpotSelected(Request $request)
{
$spot_id = $request->get('spot_id');
//验证指定景点权限
$this->spot->spotPermission($request->get('user'), $spot_id);
$this->spot->setSpotSelected($request->get('user'), $spot_id);
return $this->responseSuccess();
}
private function _formatSpotProfile($spot_obj)
{
$data = [
'business_time' => $spot_obj->time . '-' . $spot_obj->overtime,
'address' => $spot_obj->address,
'spot_name' => $spot_obj->spotname,
];
return $data;
}
private function _formatMySpotList($spots_obj, $selected_spot_id)
{
$data = [];
if ($selected_spot_id) {
foreach ($spots_obj as $k => $spot_obj) {
if ($spot_obj->id == $selected_spot_id) {
$data['spots'][$k]['selected'] = 1;
}
$data['spots'][$k]['spot_id'] = $spot_obj->id;
$data['spots'][$k]['spot_name'] = $spot_obj->spotname;
}
} else {
foreach ($spots_obj as $k => $spot_obj) {
if ($k == 0) {
$data['spots'][$k]['selected'] = 1;
}
$data['spots'][$k]['spot_id'] = $spot_obj->id;
$data['spots'][$k]['spot_name'] = $spot_obj->spotname;
}
}
return $data;
}
}
\ No newline at end of file
<?php
namespace App\Http\Controllers;
use App\Modules\Onenet\Facades\Onenet;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function responseSuccess($params = array())
{
$responseArray = array_merge($params, ["error_code"=>0]);
return response()->json($responseArray);
}
public function responseSuccessWithObject($obj)
{
if ($obj)
{
if (!is_array($obj))
{
$obj = $obj->toArray();
}
}
else
{
$obj = array();
}
$obj['error_code'] = 0;
return response()->json($obj);
}
}
<?php
/**
* Created by PhpStorm.
* User: machengjun
* Date: 2018/2/12
* Time: 上午11:41
*/
namespace App\Http\Controllers\Api\Customers;
use App\Exceptions\Api\ApiException;
use App\Http\Controllers\LoginController;
use App\Modules\Enums\ErrorCode;
use App\Modules\Models\CouponOrder\CouponOrder;
use App\Repositories\Customers\CouponRepository;
use App\Repositories\Customers\SMSRepository;
use Illuminate\Http\Request;
use App\Modules\Enums\SuccessCode;
use Illuminate\Support\Facades\Log;
/**
* Class CouponController
* @package App\Http\Controllers\Api
*/
class CouponController extends LoginController
{
protected $sms;
protected $coupon;
public function __construct(SMSRepository $sms, CouponRepository $coupon)
{
parent::__construct();
$this->sms = $sms;
$this->coupon = $coupon;
}
public function checkPhone()
{
Log::info("[checkPhone]");
$response['success_code'] = SuccessCode::PHONE_NOT_BINDING;
$response['success_mes'] = trans('api.success.phone_not_binding');
if ($this->user->phone) {
$response['success_code'] = SuccessCode::PHONE_BINDING;
$response['success_mes'] = trans('api.success.phone_binding');
$response['phone'] = substr_replace($this->user->phone,'*****',3,5);
}
return $this->responseSuccess($response);
}
public function sendCode(Request $request)
{
Log::info("[sendCode] params:" . json_encode($request->all()));
$phone = $request->get('phone');
$this->sms->phoneSendCode($phone,92065,'灰兔智能');
$response['mes'] = trans('api.success.send_code_success');
return $this->responseSuccess($response);
}
function register(Request $request)
{
Log::info("[sendCode] params:" . json_encode($request->all()));
$data = $request->only('phone', 'code');
if ($this->user->phone) {
throw new ApiException(ErrorCode::CUSTOMER_HAS_REGISTER, trans('api.error.customer_has_register'));
}
$res = $this->coupon->validate($data['phone'], $data['code']);
$res = 3;
switch ($res) {
case 1:
$response['success_code'] = SuccessCode::PHONE_VALIDATE_CODE_EXPIRE;
$response['success_mes'] = trans('api.success.phone_validate_code_expire');
return $this->responseSuccess($response);
case 2:
$response['success_code'] = SuccessCode::PHONE_VALIDATE_FAIL;
$response['success_mes'] = trans('api.success.phone_validate_fail');
return $this->responseSuccess($response);
default:
break;
}
$this->coupon->updatePhone($this->user, $data['phone']);
// $response = $this->coupon->autoSend($this->user->id);
$response['success_code'] = SuccessCode::BINDING_SUCCESS;
$response['success_mes'] = trans('api.success.binding_success');
return $this->responseSuccess($response);
}
function myRecord()
{
Log::info("[myRecord]");
$record_obj = $this->coupon->myAllRecord($this->user->id);
$res = $this->coupon->recordFormat($record_obj);
return $this->responseSuccess($res);
}
/** 扫描优惠券->状态
* @param Request $request
* @return mixed
* @throws ApiException
*/
public function scanCouponView(Request $request)
{
Log::info("[scanCouponView] params:" . json_encode($request->all()));
$data = $request->only('qrCode');//获取参数
$res = $this->coupon->checkBinder($data['qrCode']); //优惠券的具体数据
$response['coupon_data'] = '';
if ($res->user_id) {//是否已绑定
if ($res->user_id != $this->user->id) {//是否是绑定者
$response['success_code'] = SuccessCode::COUPON_HAS_BINDING;//27
$response['success_mes'] = trans('api.success.coupon_has_binding');
$response['coupon_data'] = $this->coupon->doCouponTypeInfo($data['qrCode']) * 0.01;
} else {
$response['success_code'] = SuccessCode::COUPON_SELF_BINDING;//28
$response['success_mes'] = trans('api.success.coupon_self_binding');
$response['coupon_data'] = $this->coupon->doCouponInfo($data['qrCode']);
}
} else {
//绑定页面
$response['success_code'] = SuccessCode::COUPON_NOT_BINDING;//26
$response['success_mes'] = trans('api.success.coupon_not_binding');
$response['coupon_data'] = $res['bonus'] * 0.01;
}
return $this->responseSuccess($response);
}
/**
* @param Request $request
* @return mixed
* @throws ApiException
*/
public function couponBind(Request $request)
{
Log::info("[couponBind] params:" . json_encode($request->all()));
$data = $request->only('qrCode', 'oid');//获取参数
$resp = $this->coupon->doCouponBind($this->user->id, $data['qrCode'], $data['oid']);
switch ($resp){
case 1://绑定失败 正在绑定操作
$response['success_code'] = SuccessCode::COUPON_IS_BINDING;//29
$response['success_mes'] = trans('api.success.coupon_is_binding');
break;
case 2:// 绑定失败 已被他人绑定
$response['success_code'] = SuccessCode::COUPON_HAS_OTHER_BINDING;//30
$response['success_mes'] = trans('api.success.coupon_has_other_binding');
break;
case 3:// 绑定失败 您已绑定
$response['success_code'] = SuccessCode::COUPON_SELF_BINDING;//28
$response['success_mes'] = trans('api.success.coupon_self_binding');
$response['coupon_data'] = $this->coupon->doCouponInfo($data['qrCode']);
break;
case 4:// 绑定成功
$response['success_code'] = SuccessCode::COUPON_SELF_BINDING_SUCCESS;//31
$response['success_mes'] = trans('api.success.coupon_self_binding_success');
$response['coupon_data'] = $this->coupon->doCouponInfo($data['qrCode']);
break;
case 5:// 绑定失败
$response['success_code'] = SuccessCode::COUPON_SELF_BINDING_FAIL;//32
$response['success_mes'] = trans('api.success.coupon_self_binding_fail');
break;
default:
break;
}
return $this->responseSuccess($response);
}
/**
* @param Request $request
* @return mixed
* @throws ApiException
*/
public function getCoupon(Request $request)
{
Log::info("[getCoupon] params:" . json_encode($request->all()));
$data = $request->only('qrCode');//获取参数
$res = $this->coupon->doGetCoupon($this->user->id, $data['qrCode']);
switch ($res){
case 1://领取失败 正在领取操作 请勿连续 请求
$response['success_code'] = SuccessCode::COUPON_IS_GETTING;//33
$response['success_mes'] = trans('api.success.coupon_is_getting');
break;
case 2:// 领取失败 您已领取过
$response['success_code'] = SuccessCode::COUPON_HAS_GETTING;//34
$response['success_mes'] = trans('api.success.coupon_has_getting');
break;
case 3:// 领取成功
$response['success_code'] = SuccessCode::COUPON_GETTING_SUCCESS;//35
$response['success_mes'] = trans('api.success.coupon_getting_success');
break;
case 4:// 领取失败 系统故障 稍后再试
$response['success_code'] = SuccessCode::COUPON_GETTING_FAIL;//36
$response['success_mes'] = trans('api.success.coupon_getting_fail');
break;
default:
break;
}
return $this->responseSuccess($response);
}
}
\ No newline at end of file
<?php
namespace App\Http\Controllers\Api\Customers;
use App\Common\Http;
use App\Http\Requests\Customer\Api\CustomerLoginViaAlipayRequest;
use App\Modules\Enums\ErrorCode;
use App\Exceptions\Api\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Customer\Api\CustomerLoginRequest;
use App\Http\Requests\Customer\Api\CustomerLoginViaSmsRequest;
use App\Http\Requests\Customer\Api\QiniuCallbackRequest;
use App\Http\Requests\Customer\Api\SmsRequest;
use App\Http\Requests\Customer\Api\StoreCustomerRequest;
use App\Http\Requests\Customer\Api\UpdateCustomerPasswordRequest;
use App\Modules\Models\Customer\Customer;
use App\Repositories\Customers\CustomerRepository;
use App\Util\PhoneUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
/**
* Class CustomerController
* @package App\Http\Controllers\Api
*/
class CustomerController extends Controller
{
/**
* @var CustomerRepository
*/
protected $customers;
/**
* @param CustomerRepository $customers
*/
public function __construct(CustomerRepository $customers)
{
$this->customers = $customers;
}
/**
* Authenticate User
* @param CustomerLoginRequest $request
* @return string
*/
public function login(CustomerLoginRequest $request)
{
Log::info("params" . json_encode($request->all()));
$response = $this->customers->login($request->only("telephone", "password"));
return $this->responseSuccess($response);
}
/**
* Authenticate User via sms
* @param CustomerLoginViaSmsRequest $request
* @return \Illuminate\Http\JsonResponse
*/
public function loginViaSms(CustomerLoginViaSmsRequest $request)
{
Log::info("params" . json_encode($request->all()));
$response = $this->customers->login($request->only("telephone", "sms"));
return $this->responseSuccess($response);
}
/**
* @param CustomerLoginViaAlipayRequest $request
* @return \Illuminate\Http\JsonResponse
*/
public function loginViaAlipay(CustomerLoginViaAlipayRequest $request)
{
Log::info("params" . json_encode($request->all()));
$response = $this->customers->loginViaAlipay($request->all());
return $this->responseSuccess($response);
}
/**
* @param $session_key
* @param $encryptedData
* @param $iv
* @return bool|mixed
*/
public function decryptData($session_key, $encryptedData, $iv)
{
if (strlen($session_key) != 24) {
return false;
}
$aesKey = base64_decode($session_key);
if (strlen($iv) != 24) {
return false;
}
$aesIV = base64_decode($iv);
$aesCipher = base64_decode($encryptedData);
$result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
Log::info("[decryptData] data:" . $result);
$dataArr = json_decode($result, true);
if (!$dataArr) {
return false;
}
if ($dataArr['watermark']['appid'] != config('constants.wechat.mini_program_id')) {
return false;
}
return $dataArr;
}
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse
* @throws ApiException
*/
public function loginWechatViaMiniprogram(Request $request)
{
Log::info("[loginWechatViaMiniprogram] params:" . json_encode($request->all()));
$code = $request->get('code');
$url = sprintf(config('constants.wechat.open_id_url') . '?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code', config('constants.wechat.mini_program_id'), config('constants.wechat.mini_program_secret'), $code);
$response = Http::WechatPostWithSecurity("", $url);
Log::info("[wechatOpenId] response:" . $response);
$response = json_decode($response, true);
if(!isset($response['session_key'])){
throw new ApiException(ErrorCode::CODE_ERROR, trans('api.error.code_error'));
}
$decryptData = $this->decryptData($response['session_key'], $request->get('encryptedData'), $request->get('iv'));
if (!$decryptData) {
Log::info('login failed');
throw new ApiException(ErrorCode::LOGIN_FAILED, trans('api.error.login_failed'));
}
//decrypt data
$response = $this->customers->wechat_miniprogram_login($decryptData);
return $this->responseSuccess($response);
}
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function wechatOpenId(Request $request)
{
$code = $request->get('code');
$url = sprintf(config('constants.wechat.open_id_url') . '?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code', config('constants.wechat.mini_program_id'), config('constants.wechat.mini_program_secret'), $code);
$response = Http::WechatPostWithSecurity("", $url);
Log::info("[wechatOpenId] response:" . $response);
$response = json_decode($response, true);
$customer = Auth::User();
if (empty($customer->mini_program_open_id) && isset($response['openid'])) {
$customer->mini_program_open_id = $response['openid'];
$customer->save();
}
return $this->responseSuccess($response);
}
/**
* Get current user info
* @param Request $request
* @return string
*/
public function current(Request $request)
{
$user = Auth::User();
if ($user->username == $user->telephone) {
$user->username = PhoneUtil::maskPhone($user->username);
}
$user->telephone = PhoneUtil::maskPhone($user->telephone);
$user->error_code = 0;
return response()->json($user);
}
/**
* Register user
* @param StoreCustomerRequest $request
* @return string
*/
public function register(StoreCustomerRequest $request)
{
$this->customers->create($request->all());
return $this->responseSuccess();
}
/**
* Reset password
* @param UpdateCustomerPasswordRequest $request
* @return string
*/
public function resetPassword(UpdateCustomerPasswordRequest $request)
{
$this->customers->updatePassword($request->all());
return $this->responseSuccess();
}
/**
* Get Other user info
* @param string $id
* @param Request $request
* @return string
*/
public function userDetail($id, Request $request)
{
return "detail" . $id;
}
/**
* @param SmsRequest $request
* @return \Illuminate\Http\JsonResponse
* @throws ApiException
*/
public function sms(SmsRequest $request)
{
$this->customers->sms($request->all());
return $this->responseSuccess();
}
/**
* Update user info
* @param Request $request
* @return string
*/
public function update(Request $request)
{
$this->customers->update(Auth::User(), $request->all());
return $this->responseSuccess();
}
/**
* Logout User
* @param Request $request
* @return string
*/
public function logout(Request $request)
{
$this->customers->logout();
return $this->responseSuccess();
}
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function headImageUploadToken(Request $request)
{
$token = $this->customers->headImageUploadToken(Auth::User());
return $this->responseSuccess(compact('token'));
}
/**
* @param QiniuCallbackRequest $request
* @return \Illuminate\Http\JsonResponse
*/
public function headerUpdateCallback(QiniuCallbackRequest $request)
{
Log::info("params" . json_encode($request->all()));
$userId = $request->get('userId');
$fileKey = $request->get('fkey');
$customer = Customer::find($userId);
$head_image = $fileKey;
$this->customers->update($customer, compact('head_image'));
$param = array('head_image' => config('constants.qiniu.user_bucket_url') . $head_image);
return $this->responseSuccess($param);
}
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function refreshToken(Request $request)
{
$response = $this->customers->refreshToken();
return $this->responseSuccess($response);
}
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function checkToken(Request $request)
{
$response = $this->customers->checkToken();
return $this->responseSuccess($response);
}
}
\ No newline at end of file
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment